-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
executable file
·251 lines (209 loc) · 9.21 KB
/
cli.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
#!/usr/bin/env node
const readline = require("readline");
const fs = require("fs-extra");
const path = require("path");
const {
processRoutes,
processSinglePage,
loadRoutesFromFile,
VALID_FORMATS,
DEFAULT_FORMAT,
isValidUrl
} = require("./src/core");
const logger = require("./utils/logger");
const {
displayBanner,
displayError,
displayTips,
colors
} = require("./src/ui/display");
/**
* Validate command line arguments and process accordingly
* @returns {Promise<boolean>} - True if arguments were processed, false if interactive mode should be used
*/
async function processCommandLineArgs() {
const args = process.argv.slice(2);
// No arguments - use interactive mode
if (args.length === 0) {
return false;
}
try {
// Check if the first argument is a URL
if (isValidUrl(args[0])) {
const url = args[0];
const format = args[1] && VALID_FORMATS.includes(args[1]) ? args[1] : DEFAULT_FORMAT;
console.log(`${colors.cyan}${colors.bright}Processing single page: ${url}${colors.reset}`);
console.log(`${colors.dim}Output format: ${format}${colors.reset}\n`);
await processSinglePage(url, format);
console.log(`\n${colors.green}${colors.bright}✓ Successfully processed page: ${url}${colors.reset}`);
console.log(`${colors.dim}Output files are available in the 'output' directory.${colors.reset}`);
return true;
}
// Check if first argument is a routes file
if (args[0].endsWith('.json')) {
const routesFile = args[0];
const format = args[1] && VALID_FORMATS.includes(args[1]) ? args[1] : DEFAULT_FORMAT;
const baseUrl = args[2] || undefined;
console.log(`${colors.cyan}${colors.bright}Processing routes from file: ${routesFile}${colors.reset}`);
if (!fs.existsSync(routesFile)) {
displayError(`Routes file not found: ${routesFile}`, true);
}
const routes = await loadRoutesFromFile(routesFile);
console.log(`${colors.dim}Found ${routes.length} routes in file${colors.reset}`);
console.log(`${colors.dim}Base URL: ${baseUrl || 'Default'}${colors.reset}`);
console.log(`${colors.dim}Output format: ${format}${colors.reset}\n`);
await processRoutes(baseUrl, routes, format);
console.log(`\n${colors.green}${colors.bright}✓ Successfully processed routes from file: ${routesFile}${colors.reset}`);
console.log(`${colors.dim}Output files are available in the 'output' directory.${colors.reset}`);
return true;
}
// Default to interactive mode
return false;
} catch (error) {
displayError(error.message, true);
return true; // Never reaches here due to process.exit()
}
}
// Create interface for user input
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
/**
* Main CLI function with improved error handling
*/
async function startCLI() {
try {
// Check if a specific banner was requested
const args = process.argv.slice(2);
const bannerArgIndex = args.findIndex(arg => arg === '--banner');
let bannerId = null;
if (bannerArgIndex !== -1 && bannerArgIndex + 1 < args.length) {
bannerId = args[bannerArgIndex + 1];
// Remove the banner arguments so they don't interfere with other processing
args.splice(bannerArgIndex, 2);
}
// Check if we should hide the ICJIA banner
const hideIcjia = args.includes('--no-icjia');
if (hideIcjia) {
// Remove the argument so it doesn't interfere with other processing
const hideIndex = args.indexOf('--no-icjia');
args.splice(hideIndex, 1);
}
// Display application banner
displayBanner(bannerId, !hideIcjia);
// Check for command line arguments first
const argProcessed = await processCommandLineArgs();
if (argProcessed) {
process.exit(0);
}
// Log CLI startup
logger.info("CLI interface started");
// Ask for base URL
rl.question(`${colors.blue}Base URL ${colors.dim}[https://icjia.illinois.gov]:${colors.reset} `, (baseUrl) => {
// Use default if empty
baseUrl = baseUrl || "https://icjia.illinois.gov";
// Validate URL
if (!isValidUrl(baseUrl)) {
displayError(`Invalid URL format: ${baseUrl}`);
rl.close();
process.exit(1);
}
logger.debug("User entered base URL", { baseUrl });
// Ask for routes
rl.question(
`${colors.blue}Routes (comma-separated) ${colors.dim}[/about,researchHub]:${colors.reset} `,
(routesInput) => {
// Use default if empty
const routes = routesInput
? routesInput.split(",").map((route) => route.trim())
: ["/about", "researchHub"];
// Basic validation for routes
if (routes.some(route => route.trim() === '')) {
displayError('Invalid route: empty routes are not allowed');
rl.close();
process.exit(1);
}
logger.debug("User entered routes", { routes });
// Ask for format
rl.question(
`${colors.blue}Output format (${VALID_FORMATS.join(", ")}) ${colors.dim}[${DEFAULT_FORMAT}]:${colors.reset} `,
(format) => {
// Use default if empty or invalid
format =
format && VALID_FORMATS.includes(format) ? format : DEFAULT_FORMAT;
logger.debug("User selected format", { format });
console.log(`\n${colors.bright}Configuration:${colors.reset}`);
console.log(`${colors.cyan}• Base URL:${colors.reset} ${baseUrl}`);
console.log(`${colors.cyan}• Routes:${colors.reset} ${JSON.stringify(routes)}`);
console.log(`${colors.cyan}• Format:${colors.reset} ${format}`);
// Display helpful tips
displayTips(baseUrl, routes, format);
// Confirm and process
rl.question(`${colors.green}Proceed with content generation? (y/n):${colors.reset} `, async (answer) => {
if (
answer.toLowerCase() === "y" ||
answer.toLowerCase() === "yes"
) {
rl.close();
console.log(`\n${colors.bright}${colors.yellow}Starting content generation...${colors.reset}\n`);
logger.info("User confirmed, starting content generation", {
baseUrl,
routes,
format
});
// Process the routes with progress display
const totalRoutes = routes.length;
let processedRoutes = 0;
// Setup progress tracking
const updateInterval = setInterval(() => {
const percent = Math.round((processedRoutes / totalRoutes) * 100);
process.stdout.write(`\r${colors.dim}Progress: ${processedRoutes}/${totalRoutes} routes (${percent}%)${colors.reset}`);
}, 500);
// Monitor route processing events
const originalConsoleInfo = console.info;
console.info = function() {
if (arguments[0] && typeof arguments[0] === 'string' &&
arguments[0].includes('Generated files for')) {
processedRoutes++;
}
originalConsoleInfo.apply(console, arguments);
};
try {
await processRoutes(baseUrl, routes, format);
// Clear progress interval
clearInterval(updateInterval);
// Reset console.info
console.info = originalConsoleInfo;
console.log(`\n\n${colors.bright}${colors.green}✓ Content generation completed successfully!${colors.reset}`);
console.log(`${colors.dim}Output files are available in the 'output' directory.${colors.reset}`);
logger.info("Content generation completed successfully");
} catch (error) {
// Clear progress interval
clearInterval(updateInterval);
// Reset console.info
console.info = originalConsoleInfo;
displayError(`Error during content generation: ${error.message}`);
logger.error("Error during content generation", {
error: error.message,
stack: error.stack
});
process.exit(1);
}
} else {
console.log(`${colors.yellow}Content generation cancelled.${colors.reset}`);
logger.info("User cancelled content generation");
rl.close();
}
});
}
);
}
);
});
} catch (error) {
displayError(`Unexpected error: ${error.message}`, true);
}
}
// Start the CLI
startCLI();