-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfrontend_setup.js
More file actions
350 lines (288 loc) · 9.37 KB
/
frontend_setup.js
File metadata and controls
350 lines (288 loc) · 9.37 KB
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
#!/usr/bin/env node
/**
* Frontend Setup Script for FlipFile
*
* This script sets up the frontend environment, installs dependencies,
* runs tests, and starts the development server.
*/
const { execSync, spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const projectRoot = process.cwd();
const frontendDir = path.join(projectRoot, 'frontend');
// Print colorful output
const colors = {
reset: '\x1b[0m',
green: '\x1b[32m',
yellow: '\x1b[33m',
red: '\x1b[31m',
blue: '\x1b[34m'
};
function printHeading(text) {
console.log(`\n${colors.blue}--- ${text} ---${colors.reset}`);
}
function printSuccess(text) {
console.log(`${colors.green}✓ ${text}${colors.reset}`);
}
function printWarning(text) {
console.log(`${colors.yellow}⚠ ${text}${colors.reset}`);
}
function printError(text) {
console.log(`${colors.red}✗ ${text}${colors.reset}`);
}
function runCommand(command, cwd = projectRoot) {
try {
console.log(`Running: ${command}`);
execSync(command, { cwd, stdio: 'inherit' });
return true;
} catch (error) {
printError(`Command failed: ${command}`);
return false;
}
}
async function prompt(question) {
return new Promise((resolve) => {
rl.question(question, (answer) => {
resolve(answer);
});
});
}
// Check Node.js and npm versions
function checkNodeVersion() {
printHeading('Checking Node.js Version');
try {
const nodeVersion = execSync('node -v').toString().trim();
const npmVersion = execSync('npm -v').toString().trim();
console.log(`Node.js version: ${nodeVersion}`);
console.log(`npm version: ${npmVersion}`);
const versionNumber = nodeVersion.substring(1).split('.');
const major = parseInt(versionNumber[0], 10);
if (major < 14) {
printWarning('Recommended Node.js version is 14 or higher.');
return false;
}
printSuccess('Node.js version check passed');
return true;
} catch (error) {
printError('Failed to check Node.js version. Make sure Node.js is installed.');
return false;
}
}
// Verify package.json exists and has necessary fields
async function verifyPackageJson() {
printHeading('Verifying package.json');
const packageJsonPath = path.join(frontendDir, 'package.json');
if (!fs.existsSync(packageJsonPath)) {
printWarning('package.json not found in frontend directory.');
const rootPackageJsonPath = path.join(projectRoot, 'package.json');
if (fs.existsSync(rootPackageJsonPath)) {
printWarning('Found package.json in root directory. Copying to frontend directory.');
fs.copyFileSync(rootPackageJsonPath, packageJsonPath);
printSuccess('Copied package.json to frontend directory');
} else {
printWarning('Creating a basic package.json file');
const packageJson = {
name: 'fileflip-frontend',
version: '0.1.0',
private: true,
dependencies: {
'react': '^18.2.0',
'react-dom': '^18.2.0',
'react-scripts': '5.0.1',
'axios': '^1.3.4',
'tailwindcss': '^3.3.0',
'@tailwindcss/forms': '^0.5.3'
},
scripts: {
'start': 'react-scripts start',
'build': 'react-scripts build',
'test': 'react-scripts test',
'eject': 'react-scripts eject'
},
eslintConfig: {
extends: ['react-app']
},
browserslist: {
production: ['>0.2%', 'not dead', 'not op_mini all'],
development: ['last 1 chrome version', 'last 1 firefox version', 'last 1 safari version']
}
};
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
printSuccess('Created basic package.json file');
}
} else {
printSuccess('package.json found in frontend directory');
}
// Verify package.json has required scripts
try {
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath));
if (!packageJson.scripts || !packageJson.scripts.start) {
printWarning('package.json is missing the "start" script');
packageJson.scripts = packageJson.scripts || {};
packageJson.scripts.start = packageJson.scripts.start || 'react-scripts start';
packageJson.scripts.build = packageJson.scripts.build || 'react-scripts build';
packageJson.scripts.test = packageJson.scripts.test || 'react-scripts test';
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
printSuccess('Updated package.json with required scripts');
}
} catch (error) {
printError(`Failed to verify package.json: ${error.message}`);
}
return true;
}
// Install dependencies
async function installDependencies() {
printHeading('Installing Frontend Dependencies');
// Check if node_modules exists
const nodeModulesPath = path.join(frontendDir, 'node_modules');
if (fs.existsSync(nodeModulesPath)) {
const answer = await prompt('node_modules directory already exists. Reinstall dependencies? (y/n): ');
if (answer.toLowerCase() !== 'y') {
printSuccess('Skipping dependency installation');
return true;
}
}
if (runCommand('npm install', frontendDir)) {
printSuccess('Dependencies installed successfully');
return true;
} else {
printError('Failed to install dependencies');
return false;
}
}
// Verify src directory structure
function verifySrcStructure() {
printHeading('Verifying Frontend Source Structure');
const srcDir = path.join(frontendDir, 'src');
if (!fs.existsSync(srcDir)) {
printWarning('src directory not found. Creating basic structure...');
fs.mkdirSync(srcDir, { recursive: true });
}
// Create necessary subdirectories
const dirs = [
'components',
'pages',
'services',
'styles',
'utils'
];
dirs.forEach(dir => {
const dirPath = path.join(srcDir, dir);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
printSuccess(`Created ${dir} directory`);
}
});
// Check for index file
const indexPath = path.join(srcDir, 'index.tsx');
if (!fs.existsSync(indexPath)) {
printWarning('index.tsx not found. Creating basic file...');
const indexContent = `import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
`;
fs.writeFileSync(indexPath, indexContent);
printSuccess('Created basic index.tsx file');
}
// Check for App file
const appPath = path.join(srcDir, 'App.tsx');
if (!fs.existsSync(appPath)) {
printWarning('App.tsx not found. Creating basic file...');
const appContent = `import React from 'react';
function App() {
return (
<div className="min-h-screen bg-gray-100">
<header className="bg-white shadow">
<div className="max-w-7xl mx-auto py-6 px-4">
<h1 className="text-3xl font-bold text-gray-900">FileFlip</h1>
</div>
</header>
<main>
<div className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
<div className="px-4 py-6 sm:px-0">
<div className="border-4 border-dashed border-gray-200 rounded-lg h-96 flex items-center justify-center">
<p className="text-gray-500">Welcome to FileFlip! Frontend is running successfully.</p>
</div>
</div>
</div>
</main>
</div>
);
}
export default App;
`;
fs.writeFileSync(appPath, appContent);
printSuccess('Created basic App.tsx file');
}
return true;
}
// Run frontend tests
function runTests() {
printHeading('Running Frontend Tests');
try {
execSync('npm test -- --watchAll=false', { cwd: frontendDir, stdio: 'inherit' });
printSuccess('Tests completed');
return true;
} catch (error) {
printWarning('Tests failed or no tests found. This is not critical for development.');
return true;
}
}
// Start frontend development server
function startDevServer() {
printHeading('Starting Frontend Development Server');
console.log('Starting React development server...');
const server = spawn('npm', ['start'], {
cwd: frontendDir,
stdio: 'inherit',
shell: true
});
server.on('error', (error) => {
printError(`Failed to start development server: ${error.message}`);
});
process.on('SIGINT', () => {
server.kill('SIGINT');
process.exit();
});
}
// Main function
async function main() {
console.log(`${colors.blue}=== FlipFile Frontend Setup and Development ===\n${colors.reset}`);
// Check Node.js version
if (!checkNodeVersion()) {
const answer = await prompt('Continue anyway? (y/n): ');
if (answer.toLowerCase() !== 'y') {
rl.close();
return;
}
}
// Verify package.json
await verifyPackageJson();
// Install dependencies
if (!await installDependencies()) {
printError('Failed to install dependencies. Trying to continue...');
}
// Verify src structure
verifySrcStructure();
// Run tests
runTests();
// Start development server
startDevServer();
// Keep readline interface open for the server
}
// Run the script
main().catch(error => {
printError(`An error occurred: ${error.message}`);
rl.close();
});