-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmern_setup.py
More file actions
332 lines (276 loc) · 9.85 KB
/
mern_setup.py
File metadata and controls
332 lines (276 loc) · 9.85 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
import subprocess
import os
import sys
import json
import tkinter as tk
from tkinter import filedialog
def run_command(command, cwd=None):
try:
process = subprocess.Popen(
command,
cwd=cwd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
stdout, stderr = process.communicate()
if process.returncode != 0:
print(f"Command failed: {stderr}")
return False
return True
except Exception as e:
print(f"Error executing command: {str(e)}")
return False
def modify_css(path):
css_content = """@tailwind base;
@tailwind components;
@tailwind utilities;"""
with open(os.path.join(path, 'src', 'index.css'), 'w') as f:
f.write(css_content)
def create_tailwind_config(path):
config_content = """/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
animation: {
'spin-slow': 'spin 20s linear infinite',
},
},
},
plugins: [],
}"""
with open(os.path.join(path, 'tailwind.config.js'), 'w') as f:
f.write(config_content)
def create_postcss_config(path):
config_content = """export default {
plugins: {
'tailwindcss/nesting': {},
tailwindcss: {},
autoprefixer: {},
},
}"""
with open(os.path.join(path, 'postcss.config.js'), 'w') as f:
f.write(config_content)
def setup_mern(folder_name="mern-stack-app"):
try:
# Create and configure root window with HiDPI support
try:
from ctypes import windll
windll.shcore.SetProcessDpiAwareness(2)
except:
pass
root = tk.Tk()
try:
root.tk.call('tk', 'scaling', root.winfo_fpixels('1i')/72.0)
except:
pass
root.withdraw()
path = filedialog.askdirectory(
title="Select Directory for MERN Project"
)
if not path:
return False
full_path = os.path.join(path, folder_name)
# Create main project directories
backend_path = os.path.join(full_path, 'backend')
frontend_path = os.path.join(full_path, 'frontend')
os.makedirs(full_path)
os.makedirs(backend_path)
os.makedirs(frontend_path)
# Setup Backend
print("\nSetting up MERN Backend...")
# Initialize backend package.json with corrected scripts
backend_package = {
"name": f"{folder_name}-backend",
"version": "1.0.0",
"description": "MERN Stack Backend initialized by Scripty",
"main": "src/index.ts",
"scripts": {
"dev": "nodemon src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
}
}
with open(os.path.join(backend_path, 'package.json'), 'w') as f:
json.dump(backend_package, f, indent=2)
# Install backend dependencies
backend_commands = [
"npm install express cors dotenv mongoose jsonwebtoken bcryptjs --yes",
"npm install -D typescript @types/node @types/express @types/cors @types/mongoose @types/jsonwebtoken @types/bcryptjs ts-node nodemon --yes",
"npx tsc --init" # Removed --yes flag as it's not supported by tsc
]
for cmd in backend_commands:
print(f"\nExecuting: {cmd}")
if not run_command(cmd, cwd=backend_path):
return False
# Create backend directory structure
backend_src = os.path.join(backend_path, 'src')
os.makedirs(os.path.join(backend_src, 'routes'), exist_ok=True)
os.makedirs(os.path.join(backend_src, 'models'), exist_ok=True)
os.makedirs(os.path.join(backend_src, 'middleware'), exist_ok=True)
# Create nodemon.json
nodemon_config = {
"watch": ["src"],
"ext": ".ts,.js",
"ignore": [],
"exec": "ts-node ./src/index.ts"
}
with open(os.path.join(backend_path, 'nodemon.json'), 'w') as f:
json.dump(nodemon_config, f, indent=2)
# Create main server file (index.ts)
server_content = """import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
// Load environment variables
dotenv.config();
const app = express();
const port = process.env.PORT || 5000;
// Middleware
app.use(cors());
app.use(express.json());
// Basic route for testing
app.get('/api/test', (req, res) => {
res.json({ message: 'Backend is working! Initialize by Scripty' });
});
app.listen(port, () => {
console.log(`[server]: Server is running at http://localhost:${port}`);
console.log(`Environment: ${process.env.NODE_ENV}`);
});"""
with open(os.path.join(backend_src, 'index.ts'), 'w') as f:
f.write(server_content)
# Create backend .env
env_content = """PORT=5000
MONGODB_URI=mongodb://localhost:27017/mern_db
JWT_SECRET=your_jwt_secret
NODE_ENV=development"""
with open(os.path.join(backend_path, '.env'), 'w') as f:
f.write(env_content)
# Create tsconfig.json with correct settings
tsconfig = {
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": True,
"esModuleInterop": True,
"skipLibCheck": True,
"forceConsistentCasingInFileNames": True
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
with open(os.path.join(backend_path, 'tsconfig.json'), 'w') as f:
json.dump(tsconfig, f, indent=2)
# Setup Frontend
print("\nSetting up MERN Frontend...")
frontend_commands = [
f"npm create vite@latest . --yes -- --template react-ts",
"npm install --yes",
"npm install -D tailwindcss@3.3.0 postcss@8.4.31 autoprefixer@10.4.14 --yes",
"npm install axios @tanstack/react-query react-router-dom --yes"
]
for cmd in frontend_commands:
print(f"\nExecuting: {cmd}")
if not run_command(cmd, cwd=frontend_path):
return False
# Use the same helper functions as setup_vite
create_tailwind_config(frontend_path)
create_postcss_config(frontend_path)
modify_css(frontend_path)
# Create frontend .env
frontend_env = """VITE_API_URL=http://localhost:5000/api"""
with open(os.path.join(frontend_path, '.env'), 'w') as f:
f.write(frontend_env)
# Update App.tsx with MERN-specific content
app_content = """import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
const queryClient = new QueryClient()
function App() {
return (
<QueryClientProvider client={queryClient}>
<Router>
<div className="min-h-screen bg-gray-50">
<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">
MERN Stack App <span className="text-purple-600">by Scripty</span>
</h1>
</div>
</header>
<main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
<div className="px-4 py-6 sm:px-0">
<Routes>
<Route path="/" element={<div>Welcome to your MERN Stack app!</div>} />
</Routes>
</div>
</main>
</div>
</Router>
</QueryClientProvider>
)
}
export default App"""
with open(os.path.join(frontend_path, 'src', 'App.tsx'), 'w') as f:
f.write(app_content)
# Create README
readme_content = f"""# {folder_name}
MERN (MongoDB, Express, React, Node.js) Stack project initialized by Scripty
## Project Structure
{folder_name}/
- backend/ # Express + TypeScript backend
- frontend/ # React + TypeScript frontend
## Getting Started
1. Start MongoDB locally or update MONGODB_URI in backend/.env
2. Start the backend:
cd backend
npm install
npm run dev
3. Start the frontend:
cd frontend
npm install
npm run dev"""
with open(os.path.join(full_path, 'README.md'), 'w') as f:
f.write(readme_content)
return True
except Exception as e:
print(f"Error setting up MERN project: {e}")
return False
async def func(args):
"""Handler function for MERN Stack project setup"""
try:
folder_name = args.get("folder_name", "mern_project")
if setup_mern(folder_name):
return json.dumps({
"success": True,
"message": f"MERN Stack project created successfully in {folder_name}"
})
else:
return json.dumps({
"success": False,
"error": "Project setup failed. Check console for details."
})
except Exception as e:
return json.dumps({
"success": False,
"error": str(e)
})
object = {
"name": "mern_setup",
"description": "Create a new MERN Stack project with TypeScript and TailwindCSS",
"parameters": {
"type": "object",
"properties": {
"folder_name": {
"type": "string",
"description": "Name of the project folder",
"default": "mern_project"
}
}
}
}