create-prisma-php-app 1.6.63 → 1.7.0

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.
package/dist/index.js CHANGED
@@ -1,660 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import { execSync } from "child_process";
3
- import fs from "fs";
4
- import { fileURLToPath } from "url";
5
- import path from "path";
6
- import chalk from "chalk";
7
- import prompts from "prompts";
8
- import https from "https";
9
- const __filename = fileURLToPath(import.meta.url);
10
- const __dirname = path.dirname(__filename);
11
- let updateAnswer = null;
12
- function configureBrowserSyncCommand(baseDir, projectSettings) {
13
- // Identify the base path dynamically up to and including 'htdocs'
14
- const htdocsIndex = projectSettings.PROJECT_ROOT_PATH.indexOf("\\htdocs\\");
15
- if (htdocsIndex === -1) {
16
- console.error("Invalid PROJECT_ROOT_PATH. The path does not contain \\htdocs\\");
17
- return ""; // Return an empty string or handle the error as appropriate
18
- }
19
- // Extract the path up to and including 'htdocs\\'
20
- const basePathToRemove = projectSettings.PROJECT_ROOT_PATH.substring(0, htdocsIndex + "\\htdocs\\".length);
21
- // Escape backslashes for the regex pattern
22
- const escapedBasePathToRemove = basePathToRemove.replace(/\\/g, "\\\\");
23
- // Remove the base path and replace backslashes with forward slashes for URL compatibility
24
- const relativeWebPath = projectSettings.PROJECT_ROOT_PATH.replace(new RegExp(`^${escapedBasePathToRemove}`), "").replace(/\\/g, "/");
25
- // Construct the Browser Sync command with the correct proxy URL, being careful not to affect the protocol part
26
- let proxyUrl = `http://localhost/${relativeWebPath}`;
27
- // Ensure the proxy URL does not end with a slash before appending '/public'
28
- proxyUrl = proxyUrl.endsWith("/") ? proxyUrl.slice(0, -1) : proxyUrl;
29
- // Clean the URL by replacing "//" with "/" but not affecting "http://"
30
- // We replace instances of "//" that are not preceded by ":"
31
- const cleanUrl = proxyUrl.replace(/(?<!:)(\/\/+)/g, "/");
32
- const cleanRelativeWebPath = relativeWebPath.replace(/\/\/+/g, "/");
33
- // Correct the relativeWebPath to ensure it does not start with a "/"
34
- const adjustedRelativeWebPath = cleanRelativeWebPath.startsWith("/")
35
- ? cleanRelativeWebPath.substring(1)
36
- : cleanRelativeWebPath;
37
- // TypeScript content to write
38
- const bsConfigTsContent = `
39
- const { createProxyMiddleware } = require("http-proxy-middleware");
40
-
41
- module.exports = {
42
- // First middleware: Set Cache-Control headers
43
- function (req, res, next) {
44
- res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
45
- res.setHeader("Pragma", "no-cache");
46
- res.setHeader("Expires", "0");
47
- next();
48
- },
49
- // Use the 'middleware' option to create a proxy that masks the deep URL.
50
- middleware: [
51
- // This middleware intercepts requests to the root and proxies them to the deep path.
52
- createProxyMiddleware("/", {
53
- target:
54
- "${cleanUrl}",
55
- changeOrigin: true,
56
- pathRewrite: {
57
- "^/": "/${adjustedRelativeWebPath}", // Rewrite the path.
58
- },
59
- }),
60
- ],
61
- proxy: "http://localhost:3000", // Proxy the BrowserSync server.
62
- // serveStatic: ["src/app"], // Serve static files from this directory.
63
- files: "src/**/*.*",
64
- notify: false,
65
- open: false,
66
- ghostMode: false,
67
- };`;
68
- // Determine the path and write the bs-config.js
69
- const bsConfigPath = path.join(baseDir, "settings", "bs-config.cjs");
70
- fs.writeFileSync(bsConfigPath, bsConfigTsContent, "utf8");
71
- // Return the Browser Sync command string, using the cleaned URL
72
- return `browser-sync start --config settings/bs-config.cjs`;
73
- }
74
- async function updatePackageJson(baseDir, projectSettings, answer) {
75
- const packageJsonPath = path.join(baseDir, "package.json");
76
- if (checkExcludeFiles(packageJsonPath))
77
- return;
78
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
79
- // Use the new function to configure the Browser Sync command
80
- const browserSyncCommand = configureBrowserSyncCommand(baseDir, projectSettings);
81
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { postinstall: "prisma generate" });
82
- let answersToInclude = [];
83
- if (answer.tailwindcss) {
84
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { tailwind: "postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch" });
85
- answersToInclude.push("tailwind");
86
- }
87
- if (answer.websocket) {
88
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { websocket: "node ./settings/restartWebsocket.cjs" });
89
- answersToInclude.push("websocket");
90
- }
91
- // Initialize with existing scripts
92
- const updatedScripts = Object.assign({}, packageJson.scripts);
93
- // Conditionally add "browser-sync" command
94
- if (answersToInclude.length > 0) {
95
- updatedScripts["browser-sync"] = browserSyncCommand;
96
- }
97
- // Conditionally set the "dev" command
98
- updatedScripts.dev =
99
- answersToInclude.length > 0
100
- ? `npm-run-all --parallel browser-sync ${answersToInclude.join(" ")}`
101
- : browserSyncCommand;
102
- // Finally, assign the updated scripts back to packageJson
103
- packageJson.scripts = updatedScripts;
104
- packageJson.type = "module";
105
- packageJson.prisma = {
106
- seed: "node prisma/seed.js",
107
- };
108
- fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
109
- }
110
- async function updateComposerJson(baseDir, answer) {
111
- if (!answer.websocket)
112
- return;
113
- const composerJsonPath = path.join(baseDir, "composer.json");
114
- if (checkExcludeFiles(composerJsonPath))
115
- return;
116
- let composerJson;
117
- // Check if the composer.json file exists
118
- if (fs.existsSync(composerJsonPath)) {
119
- // Read the current composer.json content
120
- const composerJsonContent = fs.readFileSync(composerJsonPath, "utf8");
121
- composerJson = JSON.parse(composerJsonContent);
122
- }
123
- else {
124
- console.error("composer.json does not exist.");
125
- return;
126
- }
127
- // Conditionally add WebSocket dependency
128
- if (answer.websocket) {
129
- composerJson.require = Object.assign(Object.assign({}, composerJson.require), { "cboden/ratchet": "^0.4.4" });
130
- }
131
- // Write the modified composer.json back to the file
132
- fs.writeFileSync(composerJsonPath, JSON.stringify(composerJson, null, 2));
133
- console.log("composer.json updated successfully.");
134
- }
135
- async function updateIndexJsForWebSocket(baseDir, answer) {
136
- if (!answer.websocket) {
137
- return;
138
- }
139
- const indexPath = path.join(baseDir, "src", "app", "js", "index.js");
140
- if (checkExcludeFiles(indexPath))
141
- return;
142
- let indexContent = fs.readFileSync(indexPath, "utf8");
143
- // WebSocket initialization code to be appended
144
- const webSocketCode = `
145
- // WebSocket initialization
146
- const ws = new WebSocket("ws://localhost:8080");
147
- `;
148
- // Append WebSocket code if user chose to use WebSocket
149
- indexContent += webSocketCode;
150
- fs.writeFileSync(indexPath, indexContent, "utf8");
151
- console.log("WebSocket code added to index.js successfully.");
152
- }
153
- // This function updates the .gitignore file
154
- async function createUpdateGitignoreFile(baseDir, additions) {
155
- const gitignorePath = path.join(baseDir, ".gitignore");
156
- if (checkExcludeFiles(gitignorePath))
157
- return;
158
- // Check if the .gitignore file exists, create if it doesn't
159
- let gitignoreContent = "";
160
- if (fs.existsSync(gitignorePath)) {
161
- gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
162
- }
163
- additions.forEach((addition) => {
164
- if (!gitignoreContent.includes(addition)) {
165
- gitignoreContent += `\n${addition}`;
166
- }
167
- });
168
- // Ensure there's no leading newline if the file was just created
169
- gitignoreContent = gitignoreContent.trimStart();
170
- fs.writeFileSync(gitignorePath, gitignoreContent);
171
- }
172
- // Recursive copy function
173
- function copyRecursiveSync(src, dest) {
174
- console.log("🚀 ~ copyRecursiveSync ~ dest:", dest);
175
- console.log("🚀 ~ copyRecursiveSync ~ src:", src);
176
- const exists = fs.existsSync(src);
177
- const stats = exists && fs.statSync(src);
178
- const isDirectory = exists && stats && stats.isDirectory();
179
- if (isDirectory) {
180
- fs.mkdirSync(dest, { recursive: true });
181
- fs.readdirSync(src).forEach((childItemName) => {
182
- copyRecursiveSync(path.join(src, childItemName), path.join(dest, childItemName));
183
- });
184
- }
185
- else {
186
- if (checkExcludeFiles(dest))
187
- return;
188
- fs.copyFileSync(src, dest, 0);
189
- }
190
- }
191
- // Function to execute the recursive copy for entire directories
192
- async function executeCopy(baseDir, directoriesToCopy) {
193
- directoriesToCopy.forEach(({ srcDir, destDir }) => {
194
- const sourcePath = path.join(__dirname, srcDir);
195
- const destPath = path.join(baseDir, destDir);
196
- copyRecursiveSync(sourcePath, destPath);
197
- });
198
- }
199
- function createOrUpdateTailwindConfig(baseDir) {
200
- console.log("🚀 ~ createOrUpdateTailwindConfig ~ baseDir:", baseDir);
201
- const filePath = path.join(baseDir, "tailwind.config.js");
202
- if (checkExcludeFiles(filePath))
203
- return;
204
- const newContent = [
205
- "./src/app/**/*.{html,js,php}",
206
- // Add more paths as needed
207
- ];
208
- let configData = fs.readFileSync(filePath, "utf8");
209
- console.log("🚀 ~ createOrUpdateTailwindConfig ~ configData:", configData);
210
- const contentArrayString = newContent
211
- .map((item) => ` "${item}"`)
212
- .join(",\n");
213
- configData = configData.replace(/content: \[\],/g, `content: [\n${contentArrayString}\n],`);
214
- fs.writeFileSync(filePath, configData, { flag: "w" });
215
- console.log(chalk.green("Tailwind configuration updated successfully."));
216
- }
217
- function modifyPostcssConfig(baseDir) {
218
- const filePath = path.join(baseDir, "postcss.config.js");
219
- if (checkExcludeFiles(filePath))
220
- return;
221
- const newContent = `export default {
222
- plugins: {
223
- tailwindcss: {},
224
- autoprefixer: {},
225
- cssnano: {},
226
- },
227
- };`;
228
- fs.writeFileSync(filePath, newContent, { flag: "w" });
229
- console.log(chalk.green("postcss.config.js updated successfully."));
230
- }
231
- function modifyLayoutPHP(baseDir, useTailwind) {
232
- const layoutPath = path.join(baseDir, "src", "app", "layout.php");
233
- if (checkExcludeFiles(layoutPath))
234
- return;
235
- try {
236
- let indexContent = fs.readFileSync(layoutPath, "utf8");
237
- const stylesAndLinks = `\n <link href="<?php echo $baseUrl; ?>css/index.css" rel="stylesheet">\n <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">\n <script src="<?php echo $baseUrl; ?>js/index.js"></script>`;
238
- // Tailwind CSS link or CDN script
239
- const tailwindLink = useTailwind
240
- ? ` <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet"> ${stylesAndLinks}`
241
- : ` <script src="https://cdn.tailwindcss.com"></script> ${stylesAndLinks}`;
242
- // Insert before the closing </head> tag
243
- indexContent = indexContent.replace("</head>", `${tailwindLink}\n</head>`);
244
- fs.writeFileSync(layoutPath, indexContent, { flag: "w" });
245
- console.log(chalk.green(`index.php modified successfully for ${useTailwind ? "local Tailwind CSS" : "Tailwind CSS CDN"}.`));
246
- }
247
- catch (error) {
248
- console.error(chalk.red("Error modifying index.php:"), error);
249
- }
250
- }
251
- // This function updates or creates the .env file
252
- async function createOrUpdateEnvFile(baseDir, content) {
253
- const envPath = path.join(baseDir, ".env");
254
- if (checkExcludeFiles(envPath))
255
- return;
256
- let envContent = fs.existsSync(envPath)
257
- ? fs.readFileSync(envPath, "utf8")
258
- : "";
259
- // Check if the content already exists in the .env file
260
- if (!envContent.includes(content)) {
261
- envContent += `${envContent !== "" ? "\n\n" : ""}${content}`;
262
- fs.writeFileSync(envPath, envContent, { flag: "w" });
263
- }
264
- }
265
- function checkExcludeFiles(destPath) {
266
- var _a, _b;
267
- if (!(updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.isUpdate))
268
- return false;
269
- return ((_b = (_a = updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.excludeFilePath) === null || _a === void 0 ? void 0 : _a.includes(destPath.replace(/\\/g, "/"))) !== null && _b !== void 0 ? _b : false);
270
- }
271
- async function createDirectoryStructure(baseDir, answer, projectSettings) {
272
- console.log("🚀 ~ baseDir:", baseDir);
273
- console.log("🚀 ~ answer:", answer);
274
- console.log("🚀 ~ projectSettings:", projectSettings);
275
- const filesToCopy = [
276
- { src: "/bootstrap.php", dest: "/bootstrap.php" },
277
- { src: "/.htaccess", dest: "/.htaccess" },
278
- { src: "/../composer.json", dest: "/composer.json" },
279
- ];
280
- if (updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.isUpdate) {
281
- filesToCopy.push({ src: "/.env", dest: "/.env" }, { src: "/tsconfig.json", dest: "/tsconfig.json" });
282
- if (updateAnswer.tailwindcss) {
283
- filesToCopy.push({ src: "/postcss.config.js", dest: "/postcss.config.js" }, { src: "/tailwind.config.js", dest: "/tailwind.config.js" });
284
- }
285
- }
286
- // if (answer.websocket) {
287
- // filesToCopy.push({
288
- // src: "/../composer-websocket.lock",
289
- // dest: "/composer.lock",
290
- // });
291
- // } else {
292
- // filesToCopy.push({ src: "/../composer.lock", dest: "/composer.lock" });
293
- // }
294
- const directoriesToCopy = [
295
- {
296
- srcDir: "/settings",
297
- destDir: "/settings",
298
- },
299
- {
300
- srcDir: "/prisma",
301
- destDir: "/prisma",
302
- },
303
- {
304
- srcDir: "/src",
305
- destDir: "/src",
306
- },
307
- {
308
- srcDir: "/../vendor",
309
- destDir: "/vendor",
310
- },
311
- ];
312
- console.log("🚀 ~ directoriesToCopy:", directoriesToCopy);
313
- filesToCopy.forEach(({ src, dest }) => {
314
- const sourcePath = path.join(__dirname, src);
315
- const destPath = path.join(baseDir, dest);
316
- if (checkExcludeFiles(destPath))
317
- return;
318
- const code = fs.readFileSync(sourcePath, "utf8");
319
- fs.writeFileSync(destPath, code, { flag: "w" });
320
- });
321
- await executeCopy(baseDir, directoriesToCopy);
322
- await updatePackageJson(baseDir, projectSettings, answer);
323
- await updateComposerJson(baseDir, answer);
324
- await updateIndexJsForWebSocket(baseDir, answer);
325
- if (answer.tailwindcss) {
326
- createOrUpdateTailwindConfig(baseDir);
327
- modifyLayoutPHP(baseDir, true);
328
- modifyPostcssConfig(baseDir);
329
- }
330
- else {
331
- modifyLayoutPHP(baseDir, false);
332
- }
333
- const envContent = `# PHPMailer
334
- SMTP_HOST=
335
- SMTP_USERNAME=
336
- SMTP_PASSWORD=
337
- SMTP_PORT=
338
- SMTP_ENCRYPTION=ssl
339
- MAIL_FROM=
340
- MAIL_FROM_NAME=""`;
341
- await createOrUpdateEnvFile(baseDir, envContent);
342
- // Add vendor to .gitignore
343
- await createUpdateGitignoreFile(baseDir, ["vendor"]);
344
- }
345
- async function getAnswer(predefinedAnswers = {}) {
346
- var _a, _b, _c;
347
- console.log("🚀 ~ predefinedAnswers:", predefinedAnswers);
348
- const questionsArray = [];
349
- if (!predefinedAnswers.projectName) {
350
- questionsArray.push({
351
- type: "text",
352
- name: "projectName",
353
- message: "What is your project named?",
354
- initial: "my-app",
355
- });
356
- }
357
- if (!predefinedAnswers.tailwindcss) {
358
- questionsArray.push({
359
- type: "toggle",
360
- name: "tailwindcss",
361
- message: `Would you like to use ${chalk.blue("Tailwind CSS")}?`,
362
- initial: true,
363
- active: "Yes",
364
- inactive: "No",
365
- });
366
- }
367
- if (!predefinedAnswers.websocket) {
368
- questionsArray.push({
369
- type: "toggle",
370
- name: "websocket",
371
- message: `Would you like to use ${chalk.blue("Websocket")}?`,
372
- initial: true,
373
- active: "Yes",
374
- inactive: "No",
375
- });
376
- }
377
- const questions = questionsArray;
378
- console.log("🚀 ~ questions:", questions);
379
- const onCancel = () => {
380
- console.log(chalk.red("Operation cancelled by the user."));
381
- process.exit(0);
382
- };
383
- try {
384
- const response = await prompts(questions, { onCancel });
385
- console.log("🚀 ~ response:", response);
386
- if (Object.keys(response).length === 0) {
387
- return null;
388
- }
389
- return {
390
- projectName: response.projectName
391
- ? String(response.projectName).trim().replace(/ /g, "-")
392
- : (_a = predefinedAnswers.projectName) !== null && _a !== void 0 ? _a : "my-app",
393
- tailwindcss: (_b = response.tailwindcss) !== null && _b !== void 0 ? _b : predefinedAnswers.tailwindcss,
394
- websocket: (_c = response.websocket) !== null && _c !== void 0 ? _c : predefinedAnswers.websocket,
395
- };
396
- }
397
- catch (error) {
398
- console.error(chalk.red("Prompt error:"), error);
399
- return null;
400
- }
401
- }
402
- /**
403
- * Install dependencies in the specified directory.
404
- * @param {string} baseDir - The base directory where to install the dependencies.
405
- * @param {string[]} dependencies - The list of dependencies to install.
406
- * @param {boolean} [isDev=false] - Whether to install the dependencies as devDependencies.
407
- */
408
- async function installDependencies(baseDir, dependencies, isDev = false) {
409
- console.log("Initializing new Node.js project...");
410
- // Initialize a package.json if it doesn't exist
411
- if (!fs.existsSync(path.join(baseDir, "package.json")))
412
- execSync("npm init -y", {
413
- stdio: "inherit",
414
- cwd: baseDir,
415
- });
416
- // Log the dependencies being installed
417
- console.log(`${isDev ? "Installing development dependencies" : "Installing dependencies"}:`);
418
- dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
419
- // Prepare the npm install command with the appropriate flag for dev dependencies
420
- const npmInstallCommand = `npm install ${isDev ? "--save-dev" : ""} ${dependencies.join(" ")}`;
421
- // Execute the npm install command
422
- execSync(npmInstallCommand, {
423
- stdio: "inherit",
424
- cwd: baseDir,
425
- });
426
- }
427
- async function uninstallDependencies(baseDir, dependencies, isDev = false) {
428
- console.log("Uninstalling dependencies:");
429
- dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
430
- // Prepare the npm uninstall command with the appropriate flag for dev dependencies
431
- const npmUninstallCommand = `npm uninstall ${isDev ? "--save-dev" : "--save"} ${dependencies.join(" ")}`;
432
- // Execute the npm uninstall command
433
- execSync(npmUninstallCommand, {
434
- stdio: "inherit",
435
- cwd: baseDir,
436
- });
437
- }
438
- function fetchPackageVersion(packageName) {
439
- return new Promise((resolve, reject) => {
440
- https
441
- .get(`https://registry.npmjs.org/${packageName}`, (res) => {
442
- let data = "";
443
- res.on("data", (chunk) => (data += chunk));
444
- res.on("end", () => {
445
- try {
446
- const parsed = JSON.parse(data);
447
- resolve(parsed["dist-tags"].latest);
448
- }
449
- catch (error) {
450
- reject(new Error("Failed to parse JSON response"));
451
- }
452
- });
453
- })
454
- .on("error", (err) => reject(err));
455
- });
456
- }
457
- const readJsonFile = (filePath) => {
458
- const jsonData = fs.readFileSync(filePath, "utf8");
459
- return JSON.parse(jsonData);
460
- };
461
- async function main() {
462
- var _a, _b, _c, _d, _e;
463
- try {
464
- const args = process.argv.slice(2);
465
- let projectName = args[0];
466
- console.log("🚀 ~ main ~ projectName:", projectName);
467
- let answer = null;
468
- if (projectName) {
469
- let useTailwind = args.includes("--tailwindcss");
470
- let useWebsocket = args.includes("--websocket");
471
- const predefinedAnswers = {
472
- projectName,
473
- tailwindcss: useTailwind,
474
- websocket: useWebsocket,
475
- };
476
- answer = await getAnswer(predefinedAnswers);
477
- if (answer === null) {
478
- console.log(chalk.red("Installation cancelled."));
479
- return;
480
- }
481
- const currentDir = process.cwd();
482
- const configPath = path.join(currentDir, "prisma-php.json");
483
- const localSettings = readJsonFile(configPath);
484
- console.log("🚀 ~ main ~ localSettings:", localSettings);
485
- let excludeFiles = [];
486
- (_a = localSettings.excludeFiles) === null || _a === void 0 ? void 0 : _a.map((file) => {
487
- const filePath = path.join(currentDir, file);
488
- console.log("🚀 ~ localSettings.excludeFiles?.map ~ filePath:", filePath);
489
- if (fs.existsSync(filePath))
490
- excludeFiles.push(filePath.replace(/\\/g, "/"));
491
- });
492
- updateAnswer = {
493
- projectName,
494
- tailwindcss: (_b = answer === null || answer === void 0 ? void 0 : answer.tailwindcss) !== null && _b !== void 0 ? _b : false,
495
- websocket: (_c = answer === null || answer === void 0 ? void 0 : answer.websocket) !== null && _c !== void 0 ? _c : false,
496
- isUpdate: true,
497
- excludeFiles: (_d = localSettings.excludeFiles) !== null && _d !== void 0 ? _d : [],
498
- excludeFilePath: excludeFiles !== null && excludeFiles !== void 0 ? excludeFiles : [],
499
- filePath: currentDir,
500
- };
501
- console.log("🚀 ~ main ~ answer:", answer);
502
- }
503
- else {
504
- answer = await getAnswer();
505
- }
506
- if (answer === null) {
507
- console.log(chalk.red("Installation cancelled."));
508
- return;
509
- }
510
- // execSync(`npm install -g create-prisma-php-app`, { stdio: "inherit" }); // TODO: Uncomment this line before publishing the package
511
- execSync(`npm install -g create-prisma-php-app@alpha-update-command`, {
512
- stdio: "inherit",
513
- }); // TODO: Uncomment this line before publishing the package
514
- // Support for browser-sync
515
- execSync(`npm install -g browser-sync`, { stdio: "inherit" });
516
- // Create the project directory
517
- if (!projectName)
518
- fs.mkdirSync(answer.projectName);
519
- const currentDir = process.cwd();
520
- console.log("🚀 ~ main ~ currentDir:", currentDir);
521
- let projectPath = projectName
522
- ? currentDir
523
- : path.join(currentDir, answer.projectName);
524
- console.log("🚀 ~ main ~ projectPath:", projectPath);
525
- if (!projectName)
526
- process.chdir(answer.projectName);
527
- const dependencies = [
528
- "prisma",
529
- "@prisma/client",
530
- "typescript",
531
- "@types/node",
532
- "ts-node",
533
- "http-proxy-middleware",
534
- ];
535
- if (answer.tailwindcss) {
536
- dependencies.push("tailwindcss", "autoprefixer", "postcss", "postcss-cli", "cssnano");
537
- }
538
- if (answer.websocket) {
539
- dependencies.push("chokidar-cli");
540
- }
541
- if (answer.tailwindcss || answer.websocket) {
542
- dependencies.push("npm-run-all");
543
- }
544
- await installDependencies(projectPath, dependencies, true);
545
- if (!projectName) {
546
- execSync(`npx prisma init`, { stdio: "inherit" });
547
- execSync(`npx tsc --init`, { stdio: "inherit" });
548
- }
549
- if (answer.tailwindcss) {
550
- execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
551
- }
552
- const projectSettings = {
553
- PROJECT_NAME: answer.projectName,
554
- PROJECT_ROOT_PATH: projectPath.replace(/\\/g, "\\\\"),
555
- PHP_ROOT_PATH_EXE: "D:\\\\xampp\\\\php\\\\php.exe",
556
- PHP_GENERATE_CLASS_PATH: "src/lib/prisma/classes",
557
- };
558
- await createDirectoryStructure(projectPath, answer, projectSettings);
559
- // if (answer.tailwindcss) {
560
- // execSync(
561
- // `npx tailwindcss -i ./src/app/css/tailwind.css -o ./src/app/css/styles.css --minify`,
562
- // { stdio: "inherit" }
563
- // );
564
- // }
565
- // execSync(`composer install`, { stdio: "inherit" });
566
- // execSync(`composer dump-autoload`, { stdio: "inherit" });
567
- // Create settings file
568
- const settingsPath = path.join(projectPath, "settings", "project-settings.js");
569
- const settingsCode = `export const projectSettings = {
570
- PROJECT_NAME: "${answer.projectName}",
571
- PROJECT_ROOT_PATH: "${projectPath.replace(/\\/g, "\\\\")}",
572
- PHP_ROOT_PATH_EXE: "D:\\\\xampp\\\\php\\\\php.exe",
573
- PHP_GENERATE_CLASS_PATH: "src/lib/prisma/classes",
574
- };`;
575
- fs.writeFileSync(settingsPath, settingsCode, { flag: "w" });
576
- const publicDirPath = path.join(projectPath, "public");
577
- if (!fs.existsSync(publicDirPath)) {
578
- fs.mkdirSync(publicDirPath);
579
- }
580
- if (!answer.tailwindcss) {
581
- const cssPath = path.join(projectPath, "src", "app", "css");
582
- const tailwindFiles = ["tailwind.css", "styles.css"];
583
- tailwindFiles.forEach((file) => {
584
- const filePath = path.join(cssPath, file);
585
- if (fs.existsSync(filePath)) {
586
- fs.unlinkSync(filePath); // Delete each file if it exists
587
- console.log(`${file} was deleted successfully.`);
588
- }
589
- else {
590
- console.log(`${file} does not exist.`);
591
- }
592
- });
593
- }
594
- // Update websocket if not chosen by the user
595
- if (!answer.websocket) {
596
- const wsPath = path.join(projectPath, "src", "lib", "websocket");
597
- // Check if the websocket directory exists
598
- if (fs.existsSync(wsPath)) {
599
- // Use fs.rmSync with recursive option set to true to delete the directory and its contents
600
- fs.rmSync(wsPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
601
- console.log("Websocket directory was deleted successfully.");
602
- }
603
- else {
604
- console.log("Websocket directory does not exist.");
605
- }
606
- // Update settings directory if websocket is not chosen
607
- const settingsPath = path.join(projectPath, "settings");
608
- const websocketFiles = ["restartWebsocket.cjs", "restart_websocket.bat"];
609
- websocketFiles.forEach((file) => {
610
- const filePath = path.join(settingsPath, file);
611
- if (fs.existsSync(filePath)) {
612
- fs.unlinkSync(filePath); // Delete each file if it exists
613
- console.log(`${file} was deleted successfully.`);
614
- }
615
- else {
616
- console.log(`${file} does not exist.`);
617
- }
618
- });
619
- }
620
- if (updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.isUpdate) {
621
- console.log("🚀 ~ main ~ updateAnswer:", updateAnswer);
622
- const updateUninstallDependencies = [];
623
- if (!updateAnswer.tailwindcss) {
624
- const tailwindFiles = ["postcss.config.js", "tailwind.config.js"];
625
- tailwindFiles.forEach((file) => {
626
- const filePath = path.join(projectPath, file);
627
- if (fs.existsSync(filePath)) {
628
- fs.unlinkSync(filePath); // Delete each file if it exists
629
- console.log(`${file} was deleted successfully.`);
630
- }
631
- else {
632
- console.log(`${file} does not exist.`);
633
- }
634
- });
635
- updateUninstallDependencies.push("tailwindcss", "autoprefixer", "postcss", "postcss-cli", "cssnano");
636
- }
637
- if (!updateAnswer.websocket) {
638
- updateUninstallDependencies.push("chokidar-cli");
639
- }
640
- if (updateUninstallDependencies.length > 0) {
641
- await uninstallDependencies(projectPath, updateUninstallDependencies, true);
642
- }
643
- }
644
- const version = await fetchPackageVersion("create-prisma-php-app");
645
- const prismaPhpConfig = {
646
- projectName: answer.projectName,
647
- tailwindcss: answer.tailwindcss,
648
- websocket: answer.websocket,
649
- version,
650
- excludeFiles: (_e = updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.excludeFiles) !== null && _e !== void 0 ? _e : [],
651
- };
652
- fs.writeFileSync(path.join(projectPath, "prisma-php.json"), JSON.stringify(prismaPhpConfig, null, 2), { flag: "w" });
653
- console.log(`${chalk.green("Success!")} Prisma PHP project successfully created in ${answer.projectName}!`);
654
- }
655
- catch (error) {
656
- console.error("Error while creating the project:", error);
657
- process.exit(1);
658
- }
659
- }
660
- main();
2
+ import{execSync}from"child_process";import fs from"fs";import{fileURLToPath}from"url";import path from"path";import chalk from"chalk";import prompts from"prompts";import https from"https";const __filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename);let updateAnswer=null;function configureBrowserSyncCommand(e,s){const t=s.PROJECT_ROOT_PATH.indexOf("\\htdocs\\");if(-1===t)return"";const n=s.PROJECT_ROOT_PATH.substring(0,t+"\\htdocs\\".length).replace(/\\/g,"\\\\"),i=s.PROJECT_ROOT_PATH.replace(new RegExp(`^${n}`),"").replace(/\\/g,"/");let c=`http://localhost/${i}`;c=c.endsWith("/")?c.slice(0,-1):c;const r=c.replace(/(?<!:)(\/\/+)/g,"/"),o=i.replace(/\/\/+/g,"/"),a=`\n const { createProxyMiddleware } = require("http-proxy-middleware");\n\n module.exports = {\n // First middleware: Set Cache-Control headers\n function (req, res, next) {\n res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");\n res.setHeader("Pragma", "no-cache");\n res.setHeader("Expires", "0");\n next();\n },\n // Use the 'middleware' option to create a proxy that masks the deep URL.\n middleware: [\n // This middleware intercepts requests to the root and proxies them to the deep path.\n createProxyMiddleware("/", {\n target:\n "${r}",\n changeOrigin: true,\n pathRewrite: {\n "^/": "/${o.startsWith("/")?o.substring(1):o}", // Rewrite the path.\n },\n }),\n ],\n proxy: "http://localhost:3000", // Proxy the BrowserSync server.\n // serveStatic: ["src/app"], // Serve static files from this directory.\n files: "src/**/*.*",\n notify: false,\n open: false,\n ghostMode: false,\n };`,l=path.join(e,"settings","bs-config.cjs");return fs.writeFileSync(l,a,"utf8"),"browser-sync start --config settings/bs-config.cjs"}async function updatePackageJson(e,s,t){const n=path.join(e,"package.json");if(checkExcludeFiles(n))return;const i=JSON.parse(fs.readFileSync(n,"utf8")),c=configureBrowserSyncCommand(e,s);i.scripts=Object.assign(Object.assign({},i.scripts),{postinstall:"prisma generate"});let r=[];t.tailwindcss&&(i.scripts=Object.assign(Object.assign({},i.scripts),{tailwind:"postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch"}),r.push("tailwind")),t.websocket&&(i.scripts=Object.assign(Object.assign({},i.scripts),{websocket:"node ./settings/restartWebsocket.cjs"}),r.push("websocket"));const o=Object.assign({},i.scripts);r.length>0&&(o["browser-sync"]=c),o.dev=r.length>0?`npm-run-all --parallel browser-sync ${r.join(" ")}`:c,i.scripts=o,i.type="module",i.prisma={seed:"node prisma/seed.js"},fs.writeFileSync(n,JSON.stringify(i,null,2))}async function updateComposerJson(e,s){if(!s.websocket)return;const t=path.join(e,"composer.json");if(checkExcludeFiles(t))return;let n;if(fs.existsSync(t)){{const e=fs.readFileSync(t,"utf8");n=JSON.parse(e)}s.websocket&&(n.require=Object.assign(Object.assign({},n.require),{"cboden/ratchet":"^0.4.4"})),fs.writeFileSync(t,JSON.stringify(n,null,2))}}async function updateIndexJsForWebSocket(e,s){if(!s.websocket)return;const t=path.join(e,"src","app","js","index.js");if(checkExcludeFiles(t))return;let n=fs.readFileSync(t,"utf8");n+='\n// WebSocket initialization\nconst ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,n,"utf8")}async function createUpdateGitignoreFile(e,s){const t=path.join(e,".gitignore");if(checkExcludeFiles(t))return;let n="";fs.existsSync(t)&&(n=fs.readFileSync(t,"utf8")),s.forEach((e=>{n.includes(e)||(n+=`\n${e}`)})),n=n.trimStart(),fs.writeFileSync(t,n)}function copyRecursiveSync(e,s){const t=fs.existsSync(e),n=t&&fs.statSync(e);if(t&&n&&n.isDirectory())fs.mkdirSync(s,{recursive:!0}),fs.readdirSync(e).forEach((t=>{copyRecursiveSync(path.join(e,t),path.join(s,t))}));else{if(checkExcludeFiles(s))return;fs.copyFileSync(e,s,0)}}async function executeCopy(e,s){s.forEach((({srcDir:s,destDir:t})=>{copyRecursiveSync(path.join(__dirname,s),path.join(e,t))}))}function createOrUpdateTailwindConfig(e){const s=path.join(e,"tailwind.config.js");if(checkExcludeFiles(s))return;let t=fs.readFileSync(s,"utf8");const n=["./src/app/**/*.{html,js,php}"].map((e=>` "${e}"`)).join(",\n");t=t.replace(/content: \[\],/g,`content: [\n${n}\n],`),fs.writeFileSync(s,t,{flag:"w"})}function modifyPostcssConfig(e){const s=path.join(e,"postcss.config.js");if(checkExcludeFiles(s))return;fs.writeFileSync(s,"export default {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n cssnano: {},\n },\n};",{flag:"w"})}function modifyLayoutPHP(e,s){const t=path.join(e,"src","app","layout.php");if(!checkExcludeFiles(t))try{let e=fs.readFileSync(t,"utf8");const n='\n <link href="<?php echo $baseUrl; ?>css/index.css" rel="stylesheet">\n <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">\n <script src="<?php echo $baseUrl; ?>js/index.js"><\/script>',i=s?` <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet"> ${n}`:` <script src="https://cdn.tailwindcss.com"><\/script> ${n}`;e=e.replace("</head>",`${i}\n</head>`),fs.writeFileSync(t,e,{flag:"w"})}catch(e){}}async function createOrUpdateEnvFile(e,s){const t=path.join(e,".env");if(checkExcludeFiles(t))return;let n=fs.existsSync(t)?fs.readFileSync(t,"utf8"):"";n.includes(s)||(n+=`${""!==n?"\n\n":""}${s}`,fs.writeFileSync(t,n,{flag:"w"}))}function checkExcludeFiles(e){var s,t;return!!(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(null!==(t=null===(s=null==updateAnswer?void 0:updateAnswer.excludeFilePath)||void 0===s?void 0:s.includes(e.replace(/\\/g,"/")))&&void 0!==t&&t)}async function createDirectoryStructure(e,s,t){const n=[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/../composer.json",dest:"/composer.json"}];(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(n.push({src:"/.env",dest:"/.env"},{src:"/tsconfig.json",dest:"/tsconfig.json"}),updateAnswer.tailwindcss&&n.push({src:"/postcss.config.js",dest:"/postcss.config.js"},{src:"/tailwind.config.js",dest:"/tailwind.config.js"}));n.forEach((({src:s,dest:t})=>{const n=path.join(__dirname,s),i=path.join(e,t);if(checkExcludeFiles(i))return;const c=fs.readFileSync(n,"utf8");fs.writeFileSync(i,c,{flag:"w"})})),await executeCopy(e,[{srcDir:"/settings",destDir:"/settings"},{srcDir:"/prisma",destDir:"/prisma"},{srcDir:"/src",destDir:"/src"}]),await updatePackageJson(e,t,s),await updateComposerJson(e,s),await updateIndexJsForWebSocket(e,s),s.tailwindcss?(createOrUpdateTailwindConfig(e),modifyLayoutPHP(e,!0),modifyPostcssConfig(e)):modifyLayoutPHP(e,!1);await createOrUpdateEnvFile(e,'# PHPMailer\nSMTP_HOST=\nSMTP_USERNAME=\nSMTP_PASSWORD=\nSMTP_PORT=\nSMTP_ENCRYPTION=ssl\nMAIL_FROM=\nMAIL_FROM_NAME=""'),await createUpdateGitignoreFile(e,["vendor"])}async function getAnswer(e={}){var s,t,n;const i=[];e.projectName||i.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.tailwindcss||i.push({type:"toggle",name:"tailwindcss",message:`Would you like to use ${chalk.blue("Tailwind CSS")}?`,initial:!0,active:"Yes",inactive:"No"}),e.websocket||i.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!0,active:"Yes",inactive:"No"});const c=i,r=()=>{process.exit(0)};try{const i=await prompts(c,{onCancel:r});return 0===Object.keys(i).length?null:{projectName:i.projectName?String(i.projectName).trim().replace(/ /g,"-"):null!==(s=e.projectName)&&void 0!==s?s:"my-app",tailwindcss:null!==(t=i.tailwindcss)&&void 0!==t?t:e.tailwindcss,websocket:null!==(n=i.websocket)&&void 0!==n?n:e.websocket}}catch(e){return null}}async function installDependencies(e,s,t=!1){fs.existsSync(path.join(e,"package.json"))||execSync("npm init -y",{stdio:"inherit",cwd:e}),s.forEach((e=>{}));const n=`npm install ${t?"--save-dev":""} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}async function uninstallDependencies(e,s,t=!1){s.forEach((e=>{}));const n=`npm uninstall ${t?"--save-dev":"--save"} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}function fetchPackageVersion(e){return new Promise(((s,t)=>{https.get(`https://registry.npmjs.org/${e}`,(e=>{let n="";e.on("data",(e=>n+=e)),e.on("end",(()=>{try{const e=JSON.parse(n);s(e["dist-tags"].latest)}catch(e){t(new Error("Failed to parse JSON response"))}}))})).on("error",(e=>t(e)))}))}const readJsonFile=e=>{const s=fs.readFileSync(e,"utf8");return JSON.parse(s)};async function main(){var e,s,t,n,i;try{const c=process.argv.slice(2);let r=c[0],o=null;if(r){const i={projectName:r,tailwindcss:c.includes("--tailwindcss"),websocket:c.includes("--websocket")};if(o=await getAnswer(i),null===o)return;const a=process.cwd(),l=path.join(a,"prisma-php.json"),p=readJsonFile(l);let d=[];null===(e=p.excludeFiles)||void 0===e||e.map((e=>{const s=path.join(a,e);fs.existsSync(s)&&d.push(s.replace(/\\/g,"/"))})),updateAnswer={projectName:r,tailwindcss:null!==(s=null==o?void 0:o.tailwindcss)&&void 0!==s&&s,websocket:null!==(t=null==o?void 0:o.websocket)&&void 0!==t&&t,isUpdate:!0,excludeFiles:null!==(n=p.excludeFiles)&&void 0!==n?n:[],excludeFilePath:null!=d?d:[],filePath:a}}else o=await getAnswer();if(null===o)return;execSync("npm install -g create-prisma-php-app",{stdio:"inherit"}),execSync("npm install -g browser-sync",{stdio:"inherit"}),r||fs.mkdirSync(o.projectName);const a=process.cwd();let l=r?a:path.join(a,o.projectName);r||process.chdir(o.projectName);const p=["prisma","@prisma/client","typescript","@types/node","ts-node","http-proxy-middleware"];o.tailwindcss&&p.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano"),o.websocket&&p.push("chokidar-cli"),(o.tailwindcss||o.websocket)&&p.push("npm-run-all"),await installDependencies(l,p,!0),r||(execSync("npx prisma init",{stdio:"inherit"}),execSync("npx tsc --init",{stdio:"inherit"})),o.tailwindcss&&execSync("npx tailwindcss init -p",{stdio:"inherit"});const d={PROJECT_NAME:o.projectName,PROJECT_ROOT_PATH:l.replace(/\\/g,"\\\\"),PHP_ROOT_PATH_EXE:"D:\\\\xampp\\\\php\\\\php.exe",PHP_GENERATE_CLASS_PATH:"src/lib/prisma/classes"};await createDirectoryStructure(l,o,d);const u=path.join(l,"settings","project-settings.js"),f=`export const projectSettings = {\n PROJECT_NAME: "${o.projectName}",\n PROJECT_ROOT_PATH: "${l.replace(/\\/g,"\\\\")}",\n PHP_ROOT_PATH_EXE: "D:\\\\xampp\\\\php\\\\php.exe",\n PHP_GENERATE_CLASS_PATH: "src/lib/prisma/classes",\n };`;fs.writeFileSync(u,f,{flag:"w"});const h=path.join(l,"public");if(fs.existsSync(h)||fs.mkdirSync(h),!o.tailwindcss){const e=path.join(l,"src","app","css");["tailwind.css","styles.css"].forEach((s=>{const t=path.join(e,s);fs.existsSync(t)&&fs.unlinkSync(t)}))}if(!o.websocket){const e=path.join(l,"src","lib","websocket");fs.existsSync(e)&&fs.rmSync(e,{recursive:!0,force:!0});const s=path.join(l,"settings");["restartWebsocket.cjs","restart_websocket.bat"].forEach((e=>{const t=path.join(s,e);fs.existsSync(t)&&fs.unlinkSync(t)}))}if(null==updateAnswer?void 0:updateAnswer.isUpdate){const e=[];if(!updateAnswer.tailwindcss){["postcss.config.js","tailwind.config.js"].forEach((e=>{const s=path.join(l,e);fs.existsSync(s)&&fs.unlinkSync(s)})),e.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano")}if(updateAnswer.websocket||e.push("chokidar-cli"),e.length>0&&await uninstallDependencies(l,e,!0),fs.existsSync(path.join(l,"composer.lock"))){if(checkExcludeFiles(path.join(l,"composer.lock")))return;fs.unlinkSync(path.join(l,"composer.lock"))}}const w=await fetchPackageVersion("create-prisma-php-app"),y={projectName:o.projectName,tailwindcss:o.tailwindcss,websocket:o.websocket,version:w,excludeFiles:null!==(i=null==updateAnswer?void 0:updateAnswer.excludeFiles)&&void 0!==i?i:[]};fs.writeFileSync(path.join(l,"prisma-php.json"),JSON.stringify(y,null,2),{flag:"w"})}catch(e){process.exit(1)}}main();