create-prisma-php-app 1.11.7 → 1.11.520

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.
Files changed (2) hide show
  1. package/dist/index.js +847 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,2 +1,848 @@
1
1
  #!/usr/bin/env node
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 bsConfigUrls(e){const s=e.indexOf("\\htdocs\\");if(-1===s)return{bsTarget:"",bsPathRewrite:{}};const t=e.substring(0,s+"\\htdocs\\".length).replace(/\\/g,"\\\\"),n=e.replace(new RegExp(`^${t}`),"").replace(/\\/g,"/");let i=`http://localhost/${n}`;i=i.endsWith("/")?i.slice(0,-1):i;const c=i.replace(/(?<!:)(\/\/+)/g,"/"),r=n.replace(/\/\/+/g,"/");return{bsTarget:`${c}/`,bsPathRewrite:{"^/":`/${r.startsWith("/")?r.substring(1):r}/`}}}function configureBrowserSyncCommand(e){const s=path.join(e,"settings","bs-config.cjs");return fs.writeFileSync(s,'const { createProxyMiddleware } = require("http-proxy-middleware");\nconst fs = require("fs");\n\nconst jsonData = fs.readFileSync("prisma-php.json", "utf8");\nconst config = JSON.parse(jsonData);\n\nmodule.exports = {\n proxy: "http://localhost:3000",\n middleware: [\n (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 createProxyMiddleware({\n target: config.bsTarget,\n changeOrigin: true,\n pathRewrite: config.bsPathRewrite,\n }),\n ],\n files: "src/**/*.*",\n notify: false,\n open: false,\n ghostMode: false,\n};',"utf8"),"browser-sync start --config settings/bs-config.cjs"}async function updatePackageJson(e,s){const t=path.join(e,"package.json");if(checkExcludeFiles(t))return;const n=JSON.parse(fs.readFileSync(t,"utf8")),i=configureBrowserSyncCommand(e);n.scripts=Object.assign(Object.assign({},n.scripts),{projectName:"node settings/project-name.cjs"});let c=[];s.tailwindcss&&(n.scripts=Object.assign(Object.assign({},n.scripts),{tailwind:"postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch"}),c.push("tailwind")),s.websocket&&(n.scripts=Object.assign(Object.assign({},n.scripts),{websocket:"node ./settings/restart-websocket.cjs"}),c.push("websocket"));const r=Object.assign({},n.scripts);r["browser-sync"]=i,r.dev=c.length>0?`npm-run-all --parallel projectName browser-sync ${c.join(" ")}`:"npm-run-all --parallel projectName browser-sync",n.scripts=r,n.type="module",s.prisma&&(n.prisma={seed:"node prisma/seed.js"}),fs.writeFileSync(t,JSON.stringify(n,null,2))}async function updateComposerJson(e,s){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"})),s.prisma&&(n.require=Object.assign(Object.assign({},n.require),{"ramsey/uuid":"5.x-dev","hidehalo/nanoid-php":"1.x-dev"})),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,t){const n=fs.existsSync(e),i=n&&fs.statSync(e);if(n&&i&&i.isDirectory()){const n=s.toLowerCase();if(!t.websocket&&n.includes("src\\lib\\websocket"))return;if(!t.prisma&&n.includes("src\\lib\\prisma"))return;fs.existsSync(s)||fs.mkdirSync(s,{recursive:!0}),fs.readdirSync(e).forEach((n=>{copyRecursiveSync(path.join(e,n),path.join(s,n),t)}))}else{if(checkExcludeFiles(s))return;if(!t.tailwindcss&&(s.includes("tailwind.css")||s.includes("styles.css")))return;if(!t.websocket&&(s.includes("restart-websocket.cjs")||s.includes("restart-websocket.bat")))return;fs.copyFileSync(e,s,0)}}async function executeCopy(e,s,t){s.forEach((({srcDir:s,destDir:n})=>{copyRecursiveSync(path.join(__dirname,s),path.join(e,n),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 <script src="<?php echo $baseUrl; ?>js/index.js"><\/script>\n <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">',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");checkExcludeFiles(t)||fs.writeFileSync(t,s,{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){const t=[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/../composer.json",dest:"/composer.json"}];(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(t.push({src:"/.env",dest:"/.env"},{src:"/tsconfig.json",dest:"/tsconfig.json"}),updateAnswer.tailwindcss&&t.push({src:"/postcss.config.js",dest:"/postcss.config.js"},{src:"/tailwind.config.js",dest:"/tailwind.config.js"}));const n=[{srcDir:"/settings",destDir:"/settings"},{srcDir:"/src",destDir:"/src"}];s.prisma&&n.push({srcDir:"/prisma",destDir:"/prisma"}),t.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,n,s),await updatePackageJson(e,s),await updateComposerJson(e,s),await updateIndexJsForWebSocket(e,s),s.tailwindcss?(createOrUpdateTailwindConfig(e),modifyLayoutPHP(e,!0),modifyPostcssConfig(e)):modifyLayoutPHP(e,!1);const i='# Prisma PHP Auth Secret Key For development only - Change this in production\nAUTH_SECRET=uxsjXVPHN038DEYls2Kw0QUgBcXKUyrjv416nIFWPY4= \n \n# PHPMailer\n# SMTP_HOST=smtp.gmail.com or your SMTP host\n# SMTP_USERNAME=john.doe@gmail.com or your SMTP username\n# SMTP_PASSWORD=123456\n# SMTP_PORT=587 for TLS, 465 for SSL or your SMTP port\n# SMTP_ENCRYPTION=ssl or tls\n# MAIL_FROM=john.doe@gmail.com\n# MAIL_FROM_NAME="John Doe"';if(s.prisma){const s=`${'# Environment variables declared in this file are automatically made available to Prisma.\n# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema\n\n# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.\n# See the documentation for all the connection string options: https://pris.ly/d/connection-strings\n\nDATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"'}\n\n${i}`;await createOrUpdateEnvFile(e,s)}else await createOrUpdateEnvFile(e,i);await createUpdateGitignoreFile(e,["vendor",".env","node_modules"])}async function getAnswer(e={}){var s,t,n,i;const c=[];e.projectName||c.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.tailwindcss||c.push({type:"toggle",name:"tailwindcss",message:`Would you like to use ${chalk.blue("Tailwind CSS")}?`,initial:!0,active:"Yes",inactive:"No"}),e.websocket||c.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!0,active:"Yes",inactive:"No"}),e.prisma||c.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!0,active:"Yes",inactive:"No"});const r=c,a=()=>{process.exit(0)};try{const c=await prompts(r,{onCancel:a});return 0===Object.keys(c).length?null:{projectName:c.projectName?String(c.projectName).trim().replace(/ /g,"-"):null!==(s=e.projectName)&&void 0!==s?s:"my-app",tailwindcss:null!==(t=c.tailwindcss)&&void 0!==t?t:e.tailwindcss,websocket:null!==(n=c.websocket)&&void 0!==n?n:e.websocket,prisma:null!==(i=c.prisma)&&void 0!==i?i:e.prisma}}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,c;try{const r=process.argv.slice(2);let a=r[0],o=null;if(a){const c={projectName:a,tailwindcss:r.includes("--tailwindcss"),websocket:r.includes("--websocket"),prisma:r.includes("--prisma")};if(o=await getAnswer(c),null===o)return;const p=process.cwd(),l=path.join(p,"prisma-php.json"),d=readJsonFile(l);let u=[];null===(e=d.excludeFiles)||void 0===e||e.map((e=>{const s=path.join(p,e);fs.existsSync(s)&&u.push(s.replace(/\\/g,"/"))})),updateAnswer={projectName:a,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,prisma:null!==(n=null==o?void 0:o.prisma)&&void 0!==n&&n,isUpdate:!0,excludeFiles:null!==(i=d.excludeFiles)&&void 0!==i?i:[],excludeFilePath:null!=u?u:[],filePath:p}}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"}),a||fs.mkdirSync(o.projectName);const p=process.cwd();let l=a?p:path.join(p,o.projectName);a||process.chdir(o.projectName);const d=["typescript","@types/node","ts-node","http-proxy-middleware@^3.0.0","npm-run-all"];o.tailwindcss&&d.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano"),o.websocket&&d.push("chokidar-cli"),o.prisma&&d.push("prisma","@prisma/client"),await installDependencies(l,d,!0),a||execSync("npx tsc --init",{stdio:"inherit"}),o.tailwindcss&&execSync("npx tailwindcss init -p",{stdio:"inherit"}),o.prisma&&(fs.existsSync(path.join(l,"prisma"))||execSync("npx prisma init",{stdio:"inherit"})),await createDirectoryStructure(l,o);const u=path.join(l,"public");if(fs.existsSync(u)||fs.mkdirSync(u),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")}updateAnswer.websocket||e.push("chokidar-cli"),updateAnswer.prisma||e.push("prisma","@prisma/client"),e.length>0&&await uninstallDependencies(l,e,!0)}const h=await fetchPackageVersion("create-prisma-php-app"),f=l.replace(/\\/g,"\\"),m=bsConfigUrls(f),w=o.prisma?"src/Lib/Prisma/Classes":"",y={projectName:o.projectName,projectRootPath:f,phpEnvironment:"XAMPP",phpRootPathExe:"C:\\xampp\\php\\php.exe",phpGenerateClassPath:w,bsTarget:m.bsTarget,bsPathRewrite:m.bsPathRewrite,tailwindcss:o.tailwindcss,websocket:o.websocket,prisma:o.prisma,version:h,excludeFiles:null!==(c=null==updateAnswer?void 0:updateAnswer.excludeFiles)&&void 0!==c?c:[]};fs.writeFileSync(path.join(l,"prisma-php.json"),JSON.stringify(y,null,2),{flag:"w"}),(null==updateAnswer?void 0:updateAnswer.isUpdate)?execSync("C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update",{stdio:"inherit"}):execSync("C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install",{stdio:"inherit"})}catch(e){process.exit(1)}}main();
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 bsConfigUrls(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(
17
+ "Invalid PROJECT_ROOT_PATH. The path does not contain \\htdocs\\"
18
+ );
19
+ return {
20
+ bsTarget: "",
21
+ bsPathRewrite: {},
22
+ };
23
+ }
24
+ // Extract the path up to and including 'htdocs\\'
25
+ const basePathToRemove = projectSettings.PROJECT_ROOT_PATH.substring(
26
+ 0,
27
+ htdocsIndex + "\\htdocs\\".length
28
+ );
29
+ // Escape backslashes for the regex pattern
30
+ const escapedBasePathToRemove = basePathToRemove.replace(/\\/g, "\\\\");
31
+ // Remove the base path and replace backslashes with forward slashes for URL compatibility
32
+ const relativeWebPath = projectSettings.PROJECT_ROOT_PATH.replace(
33
+ new RegExp(`^${escapedBasePathToRemove}`),
34
+ ""
35
+ ).replace(/\\/g, "/");
36
+ // Construct the Browser Sync command with the correct proxy URL, being careful not to affect the protocol part
37
+ let proxyUrl = `http://localhost/${relativeWebPath}`;
38
+ // Ensure the proxy URL does not end with a slash before appending '/public'
39
+ proxyUrl = proxyUrl.endsWith("/") ? proxyUrl.slice(0, -1) : proxyUrl;
40
+ // Clean the URL by replacing "//" with "/" but not affecting "http://"
41
+ // We replace instances of "//" that are not preceded by ":"
42
+ const cleanUrl = proxyUrl.replace(/(?<!:)(\/\/+)/g, "/");
43
+ const cleanRelativeWebPath = relativeWebPath.replace(/\/\/+/g, "/");
44
+ // Correct the relativeWebPath to ensure it does not start with a "/"
45
+ const adjustedRelativeWebPath = cleanRelativeWebPath.startsWith("/")
46
+ ? cleanRelativeWebPath.substring(1)
47
+ : cleanRelativeWebPath;
48
+ return {
49
+ bsTarget: `${cleanUrl}/`,
50
+ bsPathRewrite: {
51
+ "^/": `/${adjustedRelativeWebPath}/`,
52
+ },
53
+ };
54
+ }
55
+ function configureBrowserSyncCommand(baseDir, projectSettings) {
56
+ // TypeScript content to write
57
+ const bsConfigTsContent = `const { createProxyMiddleware } = require("http-proxy-middleware");
58
+ const fs = require("fs");
59
+
60
+ const jsonData = fs.readFileSync("prisma-php.json", "utf8");
61
+ const config = JSON.parse(jsonData);
62
+
63
+ module.exports = {
64
+ proxy: "http://localhost:3000",
65
+ middleware: [
66
+ (req, res, next) => {
67
+ res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
68
+ res.setHeader("Pragma", "no-cache");
69
+ res.setHeader("Expires", "0");
70
+ next();
71
+ },
72
+ createProxyMiddleware({
73
+ target: config.bsTarget,
74
+ changeOrigin: true,
75
+ pathRewrite: config.bsPathRewrite,
76
+ }),
77
+ ],
78
+ files: "src/**/*.*",
79
+ notify: false,
80
+ open: false,
81
+ ghostMode: false,
82
+ };`;
83
+ // Determine the path and write the bs-config.js
84
+ const bsConfigPath = path.join(baseDir, "settings", "bs-config.cjs");
85
+ fs.writeFileSync(bsConfigPath, bsConfigTsContent, "utf8");
86
+ // Return the Browser Sync command string, using the cleaned URL
87
+ return `browser-sync start --config settings/bs-config.cjs`;
88
+ }
89
+ async function updatePackageJson(baseDir, projectSettings, answer) {
90
+ const packageJsonPath = path.join(baseDir, "package.json");
91
+ if (checkExcludeFiles(packageJsonPath)) return;
92
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
93
+ // Use the new function to configure the Browser Sync command
94
+ const browserSyncCommand = configureBrowserSyncCommand(
95
+ baseDir,
96
+ projectSettings
97
+ );
98
+ packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), {
99
+ projectName: "node settings/project-name.cjs",
100
+ });
101
+ let answersToInclude = [];
102
+ if (answer.tailwindcss) {
103
+ packageJson.scripts = Object.assign(
104
+ Object.assign({}, packageJson.scripts),
105
+ {
106
+ tailwind:
107
+ "postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch",
108
+ }
109
+ );
110
+ answersToInclude.push("tailwind");
111
+ }
112
+ if (answer.websocket) {
113
+ packageJson.scripts = Object.assign(
114
+ Object.assign({}, packageJson.scripts),
115
+ { websocket: "node ./settings/restart-websocket.cjs" }
116
+ );
117
+ answersToInclude.push("websocket");
118
+ }
119
+ // if (answer.prisma) {
120
+ // packageJson.scripts = {
121
+ // ...packageJson.scripts,
122
+ // postinstall: "prisma generate",
123
+ // };
124
+ // }
125
+ // Initialize with existing scripts
126
+ const updatedScripts = Object.assign({}, packageJson.scripts);
127
+ // Conditionally add "browser-sync" command
128
+ updatedScripts["browser-sync"] = browserSyncCommand;
129
+ // Conditionally set the "dev" command
130
+ updatedScripts.dev =
131
+ answersToInclude.length > 0
132
+ ? `npm-run-all --parallel projectName browser-sync ${answersToInclude.join(
133
+ " "
134
+ )}`
135
+ : `npm-run-all --parallel projectName browser-sync`;
136
+ // Finally, assign the updated scripts back to packageJson
137
+ packageJson.scripts = updatedScripts;
138
+ packageJson.type = "module";
139
+ if (answer.prisma)
140
+ packageJson.prisma = {
141
+ seed: "node prisma/seed.js",
142
+ };
143
+ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
144
+ }
145
+ async function updateComposerJson(baseDir, answer) {
146
+ const composerJsonPath = path.join(baseDir, "composer.json");
147
+ if (checkExcludeFiles(composerJsonPath)) return;
148
+ let composerJson;
149
+ // Check if the composer.json file exists
150
+ if (fs.existsSync(composerJsonPath)) {
151
+ // Read the current composer.json content
152
+ const composerJsonContent = fs.readFileSync(composerJsonPath, "utf8");
153
+ composerJson = JSON.parse(composerJsonContent);
154
+ } else {
155
+ console.error("composer.json does not exist.");
156
+ return;
157
+ }
158
+ // Conditionally add WebSocket dependency
159
+ if (answer.websocket) {
160
+ composerJson.require = Object.assign(
161
+ Object.assign({}, composerJson.require),
162
+ { "cboden/ratchet": "^0.4.4" }
163
+ );
164
+ }
165
+ if (answer.prisma) {
166
+ composerJson.require = Object.assign(
167
+ Object.assign({}, composerJson.require),
168
+ { "ramsey/uuid": "5.x-dev", "hidehalo/nanoid-php": "1.x-dev" }
169
+ );
170
+ }
171
+ // Write the modified composer.json back to the file
172
+ fs.writeFileSync(composerJsonPath, JSON.stringify(composerJson, null, 2));
173
+ console.log("composer.json updated successfully.");
174
+ }
175
+ async function updateIndexJsForWebSocket(baseDir, answer) {
176
+ if (!answer.websocket) {
177
+ return;
178
+ }
179
+ const indexPath = path.join(baseDir, "src", "app", "js", "index.js");
180
+ if (checkExcludeFiles(indexPath)) return;
181
+ let indexContent = fs.readFileSync(indexPath, "utf8");
182
+ // WebSocket initialization code to be appended
183
+ const webSocketCode = `
184
+ // WebSocket initialization
185
+ const ws = new WebSocket("ws://localhost:8080");
186
+ `;
187
+ // Append WebSocket code if user chose to use WebSocket
188
+ indexContent += webSocketCode;
189
+ fs.writeFileSync(indexPath, indexContent, "utf8");
190
+ console.log("WebSocket code added to index.js successfully.");
191
+ }
192
+ // This function updates the .gitignore file
193
+ async function createUpdateGitignoreFile(baseDir, additions) {
194
+ const gitignorePath = path.join(baseDir, ".gitignore");
195
+ if (checkExcludeFiles(gitignorePath)) return;
196
+ // Check if the .gitignore file exists, create if it doesn't
197
+ let gitignoreContent = "";
198
+ if (fs.existsSync(gitignorePath)) {
199
+ gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
200
+ }
201
+ additions.forEach((addition) => {
202
+ if (!gitignoreContent.includes(addition)) {
203
+ gitignoreContent += `\n${addition}`;
204
+ }
205
+ });
206
+ // Ensure there's no leading newline if the file was just created
207
+ gitignoreContent = gitignoreContent.trimStart();
208
+ fs.writeFileSync(gitignorePath, gitignoreContent);
209
+ }
210
+ // Recursive copy function
211
+ function copyRecursiveSync(src, dest) {
212
+ console.log("🚀 ~ copyRecursiveSync ~ dest:", dest);
213
+ console.log("🚀 ~ copyRecursiveSync ~ src:", src);
214
+ const exists = fs.existsSync(src);
215
+ const stats = exists && fs.statSync(src);
216
+ const isDirectory = exists && stats && stats.isDirectory();
217
+ if (isDirectory) {
218
+ if (!fs.existsSync(dest)) fs.mkdirSync(dest, { recursive: true });
219
+ fs.readdirSync(src).forEach((childItemName) => {
220
+ copyRecursiveSync(
221
+ path.join(src, childItemName),
222
+ path.join(dest, childItemName)
223
+ );
224
+ });
225
+ } else {
226
+ if (checkExcludeFiles(dest)) return;
227
+ fs.copyFileSync(src, dest, 0);
228
+ }
229
+ }
230
+ // Function to execute the recursive copy for entire directories
231
+ async function executeCopy(baseDir, directoriesToCopy, answer) {
232
+ directoriesToCopy.forEach(({ srcDir, destDir }) => {
233
+ if (!answer.prisma && srcDir === "/prisma-client-php") return;
234
+ const sourcePath = path.join(__dirname, srcDir);
235
+ const destPath = path.join(baseDir, destDir);
236
+ copyRecursiveSync(sourcePath, destPath);
237
+ });
238
+ }
239
+ function createOrUpdateTailwindConfig(baseDir) {
240
+ console.log("🚀 ~ createOrUpdateTailwindConfig ~ baseDir:", baseDir);
241
+ const filePath = path.join(baseDir, "tailwind.config.js");
242
+ if (checkExcludeFiles(filePath)) return;
243
+ const newContent = [
244
+ "./src/app/**/*.{html,js,php}",
245
+ // Add more paths as needed
246
+ ];
247
+ let configData = fs.readFileSync(filePath, "utf8");
248
+ console.log("🚀 ~ createOrUpdateTailwindConfig ~ configData:", configData);
249
+ const contentArrayString = newContent
250
+ .map((item) => ` "${item}"`)
251
+ .join(",\n");
252
+ configData = configData.replace(
253
+ /content: \[\],/g,
254
+ `content: [\n${contentArrayString}\n],`
255
+ );
256
+ fs.writeFileSync(filePath, configData, { flag: "w" });
257
+ console.log(chalk.green("Tailwind configuration updated successfully."));
258
+ }
259
+ function modifyPostcssConfig(baseDir) {
260
+ const filePath = path.join(baseDir, "postcss.config.js");
261
+ if (checkExcludeFiles(filePath)) return;
262
+ const newContent = `export default {
263
+ plugins: {
264
+ tailwindcss: {},
265
+ autoprefixer: {},
266
+ cssnano: {},
267
+ },
268
+ };`;
269
+ fs.writeFileSync(filePath, newContent, { flag: "w" });
270
+ console.log(chalk.green("postcss.config.js updated successfully."));
271
+ }
272
+ function modifyLayoutPHP(baseDir, useTailwind) {
273
+ const layoutPath = path.join(baseDir, "src", "app", "layout.php");
274
+ if (checkExcludeFiles(layoutPath)) return;
275
+ try {
276
+ let indexContent = fs.readFileSync(layoutPath, "utf8");
277
+ const stylesAndLinks = `\n <link href="<?php echo $baseUrl; ?>css/index.css" rel="stylesheet">\n <script src="<?php echo $baseUrl; ?>js/index.js"></script>\n <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">`;
278
+ // Tailwind CSS link or CDN script
279
+ const tailwindLink = useTailwind
280
+ ? ` <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet"> ${stylesAndLinks}`
281
+ : ` <script src="https://cdn.tailwindcss.com"></script> ${stylesAndLinks}`;
282
+ // Insert before the closing </head> tag
283
+ indexContent = indexContent.replace("</head>", `${tailwindLink}\n</head>`);
284
+ fs.writeFileSync(layoutPath, indexContent, { flag: "w" });
285
+ console.log(
286
+ chalk.green(
287
+ `index.php modified successfully for ${
288
+ useTailwind ? "local Tailwind CSS" : "Tailwind CSS CDN"
289
+ }.`
290
+ )
291
+ );
292
+ } catch (error) {
293
+ console.error(chalk.red("Error modifying index.php:"), error);
294
+ }
295
+ }
296
+ // This function updates or creates the .env file
297
+ async function createOrUpdateEnvFile(baseDir, content) {
298
+ const envPath = path.join(baseDir, ".env");
299
+ if (checkExcludeFiles(envPath)) return;
300
+ let envContent = fs.existsSync(envPath)
301
+ ? fs.readFileSync(envPath, "utf8")
302
+ : "";
303
+ // Check if the content already exists in the .env file
304
+ if (!envContent.includes(content)) {
305
+ envContent += `${envContent !== "" ? "\n\n" : ""}${content}`;
306
+ fs.writeFileSync(envPath, envContent, { flag: "w" });
307
+ } else {
308
+ console.log(".env file already contains the content.");
309
+ }
310
+ }
311
+ function checkExcludeFiles(destPath) {
312
+ var _a, _b;
313
+ if (
314
+ !(updateAnswer === null || updateAnswer === void 0
315
+ ? void 0
316
+ : updateAnswer.isUpdate)
317
+ )
318
+ return false;
319
+ return (_b =
320
+ (_a =
321
+ updateAnswer === null || updateAnswer === void 0
322
+ ? void 0
323
+ : updateAnswer.excludeFilePath) === null || _a === void 0
324
+ ? void 0
325
+ : _a.includes(destPath.replace(/\\/g, "/"))) !== null && _b !== void 0
326
+ ? _b
327
+ : false;
328
+ }
329
+ async function createDirectoryStructure(baseDir, answer, projectSettings) {
330
+ console.log("🚀 ~ baseDir:", baseDir);
331
+ console.log("🚀 ~ answer:", answer);
332
+ console.log("🚀 ~ projectSettings:", projectSettings);
333
+ const filesToCopy = [
334
+ { src: "/bootstrap.php", dest: "/bootstrap.php" },
335
+ { src: "/.htaccess", dest: "/.htaccess" },
336
+ { src: "/../composer.json", dest: "/composer.json" },
337
+ ];
338
+ if (
339
+ updateAnswer === null || updateAnswer === void 0
340
+ ? void 0
341
+ : updateAnswer.isUpdate
342
+ ) {
343
+ filesToCopy.push(
344
+ { src: "/.env", dest: "/.env" },
345
+ { src: "/tsconfig.json", dest: "/tsconfig.json" }
346
+ );
347
+ if (updateAnswer.tailwindcss) {
348
+ filesToCopy.push(
349
+ { src: "/postcss.config.js", dest: "/postcss.config.js" },
350
+ { src: "/tailwind.config.js", dest: "/tailwind.config.js" }
351
+ );
352
+ }
353
+ }
354
+ // if (answer.websocket) {
355
+ // filesToCopy.push({
356
+ // src: "/../composer-websocket.lock",
357
+ // dest: "/composer.lock",
358
+ // });
359
+ // } else {
360
+ // filesToCopy.push({ src: "/../composer.lock", dest: "/composer.lock" });
361
+ // }
362
+ const directoriesToCopy = [
363
+ {
364
+ srcDir: "/settings",
365
+ destDir: "/settings",
366
+ },
367
+ {
368
+ srcDir: "/prisma",
369
+ destDir: "/prisma",
370
+ },
371
+ {
372
+ srcDir: "/src",
373
+ destDir: "/src",
374
+ },
375
+ ];
376
+ console.log("🚀 ~ directoriesToCopy:", directoriesToCopy);
377
+ filesToCopy.forEach(({ src, dest }) => {
378
+ const sourcePath = path.join(__dirname, src);
379
+ const destPath = path.join(baseDir, dest);
380
+ if (checkExcludeFiles(destPath)) return;
381
+ const code = fs.readFileSync(sourcePath, "utf8");
382
+ fs.writeFileSync(destPath, code, { flag: "w" });
383
+ });
384
+ await executeCopy(baseDir, directoriesToCopy, answer);
385
+ await updatePackageJson(baseDir, projectSettings, answer);
386
+ await updateComposerJson(baseDir, answer);
387
+ await updateIndexJsForWebSocket(baseDir, answer);
388
+ if (answer.tailwindcss) {
389
+ createOrUpdateTailwindConfig(baseDir);
390
+ modifyLayoutPHP(baseDir, true);
391
+ modifyPostcssConfig(baseDir);
392
+ } else {
393
+ modifyLayoutPHP(baseDir, false);
394
+ }
395
+ const prismaEnvContent = `# Environment variables declared in this file are automatically made available to Prisma.
396
+ # See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
397
+
398
+ # Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
399
+ # See the documentation for all the connection string options: https://pris.ly/d/connection-strings
400
+
401
+ DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"`;
402
+ const prismaPHPEnvContent = `# Prisma PHP Auth Secret Key For development only - Change this in production
403
+ AUTH_SECRET=uxsjXVPHN038DEYls2Kw0QUgBcXKUyrjv416nIFWPY4=
404
+
405
+ # PHPMailer
406
+ # SMTP_HOST=smtp.gmail.com or your SMTP host
407
+ # SMTP_USERNAME=john.doe@gmail.com or your SMTP username
408
+ # SMTP_PASSWORD=123456
409
+ # SMTP_PORT=587 for TLS, 465 for SSL or your SMTP port
410
+ # SMTP_ENCRYPTION=ssl or tls
411
+ # MAIL_FROM=john.doe@gmail.com
412
+ # MAIL_FROM_NAME="John Doe"`;
413
+ let envContent = prismaPHPEnvContent;
414
+ if (answer.prisma) {
415
+ envContent = `${prismaEnvContent}\n\n${prismaPHPEnvContent}`;
416
+ await createOrUpdateEnvFile(baseDir, envContent);
417
+ } else {
418
+ await createOrUpdateEnvFile(baseDir, envContent);
419
+ }
420
+ // Add vendor to .gitignore
421
+ await createUpdateGitignoreFile(baseDir, ["vendor", ".env", "node_modules"]);
422
+ }
423
+ async function getAnswer(predefinedAnswers = {}) {
424
+ var _a, _b, _c, _d;
425
+ console.log("🚀 ~ predefinedAnswers:", predefinedAnswers);
426
+ const questionsArray = [];
427
+ if (!predefinedAnswers.projectName) {
428
+ questionsArray.push({
429
+ type: "text",
430
+ name: "projectName",
431
+ message: "What is your project named?",
432
+ initial: "my-app",
433
+ });
434
+ }
435
+ if (!predefinedAnswers.tailwindcss) {
436
+ questionsArray.push({
437
+ type: "toggle",
438
+ name: "tailwindcss",
439
+ message: `Would you like to use ${chalk.blue("Tailwind CSS")}?`,
440
+ initial: true,
441
+ active: "Yes",
442
+ inactive: "No",
443
+ });
444
+ }
445
+ if (!predefinedAnswers.websocket) {
446
+ questionsArray.push({
447
+ type: "toggle",
448
+ name: "websocket",
449
+ message: `Would you like to use ${chalk.blue("Websocket")}?`,
450
+ initial: true,
451
+ active: "Yes",
452
+ inactive: "No",
453
+ });
454
+ }
455
+ if (!predefinedAnswers.prisma) {
456
+ questionsArray.push({
457
+ type: "toggle",
458
+ name: "prisma",
459
+ message: `Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,
460
+ initial: true,
461
+ active: "Yes",
462
+ inactive: "No",
463
+ });
464
+ }
465
+ const questions = questionsArray;
466
+ console.log("🚀 ~ questions:", questions);
467
+ const onCancel = () => {
468
+ console.log(chalk.red("Operation cancelled by the user."));
469
+ process.exit(0);
470
+ };
471
+ try {
472
+ const response = await prompts(questions, { onCancel });
473
+ console.log("🚀 ~ response:", response);
474
+ if (Object.keys(response).length === 0) {
475
+ return null;
476
+ }
477
+ return {
478
+ projectName: response.projectName
479
+ ? String(response.projectName).trim().replace(/ /g, "-")
480
+ : (_a = predefinedAnswers.projectName) !== null && _a !== void 0
481
+ ? _a
482
+ : "my-app",
483
+ tailwindcss:
484
+ (_b = response.tailwindcss) !== null && _b !== void 0
485
+ ? _b
486
+ : predefinedAnswers.tailwindcss,
487
+ websocket:
488
+ (_c = response.websocket) !== null && _c !== void 0
489
+ ? _c
490
+ : predefinedAnswers.websocket,
491
+ prisma:
492
+ (_d = response.prisma) !== null && _d !== void 0
493
+ ? _d
494
+ : predefinedAnswers.prisma,
495
+ };
496
+ } catch (error) {
497
+ console.error(chalk.red("Prompt error:"), error);
498
+ return null;
499
+ }
500
+ }
501
+ /**
502
+ * Install dependencies in the specified directory.
503
+ * @param {string} baseDir - The base directory where to install the dependencies.
504
+ * @param {string[]} dependencies - The list of dependencies to install.
505
+ * @param {boolean} [isDev=false] - Whether to install the dependencies as devDependencies.
506
+ */
507
+ async function installDependencies(baseDir, dependencies, isDev = false) {
508
+ console.log("Initializing new Node.js project...");
509
+ // Initialize a package.json if it doesn't exist
510
+ if (!fs.existsSync(path.join(baseDir, "package.json")))
511
+ execSync("npm init -y", {
512
+ stdio: "inherit",
513
+ cwd: baseDir,
514
+ });
515
+ // Log the dependencies being installed
516
+ console.log(
517
+ `${
518
+ isDev ? "Installing development dependencies" : "Installing dependencies"
519
+ }:`
520
+ );
521
+ dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
522
+ // Prepare the npm install command with the appropriate flag for dev dependencies
523
+ const npmInstallCommand = `npm install ${
524
+ isDev ? "--save-dev" : ""
525
+ } ${dependencies.join(" ")}`;
526
+ // Execute the npm install command
527
+ execSync(npmInstallCommand, {
528
+ stdio: "inherit",
529
+ cwd: baseDir,
530
+ });
531
+ }
532
+ async function uninstallDependencies(baseDir, dependencies, isDev = false) {
533
+ console.log("Uninstalling dependencies:");
534
+ dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
535
+ // Prepare the npm uninstall command with the appropriate flag for dev dependencies
536
+ const npmUninstallCommand = `npm uninstall ${
537
+ isDev ? "--save-dev" : "--save"
538
+ } ${dependencies.join(" ")}`;
539
+ // Execute the npm uninstall command
540
+ execSync(npmUninstallCommand, {
541
+ stdio: "inherit",
542
+ cwd: baseDir,
543
+ });
544
+ }
545
+ function fetchPackageVersion(packageName) {
546
+ return new Promise((resolve, reject) => {
547
+ https
548
+ .get(`https://registry.npmjs.org/${packageName}`, (res) => {
549
+ let data = "";
550
+ res.on("data", (chunk) => (data += chunk));
551
+ res.on("end", () => {
552
+ try {
553
+ const parsed = JSON.parse(data);
554
+ resolve(parsed["dist-tags"].latest);
555
+ } catch (error) {
556
+ reject(new Error("Failed to parse JSON response"));
557
+ }
558
+ });
559
+ })
560
+ .on("error", (err) => reject(err));
561
+ });
562
+ }
563
+ const readJsonFile = (filePath) => {
564
+ const jsonData = fs.readFileSync(filePath, "utf8");
565
+ return JSON.parse(jsonData);
566
+ };
567
+ async function main() {
568
+ var _a, _b, _c, _d, _e, _f;
569
+ try {
570
+ const args = process.argv.slice(2);
571
+ let projectName = args[0];
572
+ let answer = null;
573
+ if (projectName) {
574
+ let useTailwind = args.includes("--tailwindcss");
575
+ let useWebsocket = args.includes("--websocket");
576
+ let usePrisma = args.includes("--prisma");
577
+ const predefinedAnswers = {
578
+ projectName,
579
+ tailwindcss: useTailwind,
580
+ websocket: useWebsocket,
581
+ prisma: usePrisma,
582
+ };
583
+ console.log("🚀 ~ main ~ predefinedAnswers:", predefinedAnswers);
584
+ answer = await getAnswer(predefinedAnswers);
585
+ if (answer === null) {
586
+ console.log(chalk.red("Installation cancelled."));
587
+ return;
588
+ }
589
+ const currentDir = process.cwd();
590
+ const configPath = path.join(currentDir, "prisma-php.json");
591
+ const localSettings = readJsonFile(configPath);
592
+ let excludeFiles = [];
593
+ (_a = localSettings.excludeFiles) === null || _a === void 0
594
+ ? void 0
595
+ : _a.map((file) => {
596
+ const filePath = path.join(currentDir, file);
597
+ if (fs.existsSync(filePath))
598
+ excludeFiles.push(filePath.replace(/\\/g, "/"));
599
+ });
600
+ updateAnswer = {
601
+ projectName,
602
+ tailwindcss:
603
+ (_b =
604
+ answer === null || answer === void 0
605
+ ? void 0
606
+ : answer.tailwindcss) !== null && _b !== void 0
607
+ ? _b
608
+ : false,
609
+ websocket:
610
+ (_c =
611
+ answer === null || answer === void 0
612
+ ? void 0
613
+ : answer.websocket) !== null && _c !== void 0
614
+ ? _c
615
+ : false,
616
+ prisma:
617
+ (_d =
618
+ answer === null || answer === void 0 ? void 0 : answer.prisma) !==
619
+ null && _d !== void 0
620
+ ? _d
621
+ : false,
622
+ isUpdate: true,
623
+ excludeFiles:
624
+ (_e = localSettings.excludeFiles) !== null && _e !== void 0 ? _e : [],
625
+ excludeFilePath:
626
+ excludeFiles !== null && excludeFiles !== void 0 ? excludeFiles : [],
627
+ filePath: currentDir,
628
+ };
629
+ } else {
630
+ answer = await getAnswer();
631
+ }
632
+ if (answer === null) {
633
+ console.log(chalk.red("Installation cancelled."));
634
+ return;
635
+ }
636
+ execSync(`npm install -g create-prisma-php-app`, { stdio: "inherit" }); // TODO: Uncomment this line before publishing the package
637
+ // Support for browser-sync
638
+ execSync(`npm install -g browser-sync`, { stdio: "inherit" });
639
+ // Create the project directory
640
+ if (!projectName) fs.mkdirSync(answer.projectName);
641
+ const currentDir = process.cwd();
642
+ let projectPath = projectName
643
+ ? currentDir
644
+ : path.join(currentDir, answer.projectName);
645
+ if (!projectName) process.chdir(answer.projectName);
646
+ const dependencies = [
647
+ "typescript",
648
+ "@types/node",
649
+ "ts-node",
650
+ "http-proxy-middleware@^3.0.0",
651
+ "npm-run-all",
652
+ ];
653
+ if (answer.tailwindcss) {
654
+ dependencies.push(
655
+ "tailwindcss",
656
+ "autoprefixer",
657
+ "postcss",
658
+ "postcss-cli",
659
+ "cssnano"
660
+ );
661
+ }
662
+ if (answer.websocket) {
663
+ dependencies.push("chokidar-cli");
664
+ }
665
+ if (answer.prisma) {
666
+ dependencies.push("prisma", "@prisma/client");
667
+ }
668
+ await installDependencies(projectPath, dependencies, true);
669
+ if (!projectName) {
670
+ execSync(`npx tsc --init`, { stdio: "inherit" });
671
+ }
672
+ if (answer.tailwindcss)
673
+ execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
674
+ if (answer.prisma) {
675
+ if (!fs.existsSync(path.join(projectPath, "prisma")))
676
+ execSync(`npx prisma init`, { stdio: "inherit" });
677
+ }
678
+ const projectPathModified = projectPath.replace(/\\/g, "\\");
679
+ const PHP_GENERATE_CLASS_PATH = answer.prisma
680
+ ? "src/Lib/Prisma/Classes"
681
+ : "";
682
+ const projectSettings = {
683
+ PROJECT_NAME: answer.projectName,
684
+ PROJECT_ROOT_PATH: projectPathModified,
685
+ PHP_ROOT_PATH_EXE: "D:\\\\xampp\\\\php\\\\php.exe",
686
+ PHP_GENERATE_CLASS_PATH,
687
+ };
688
+ await createDirectoryStructure(projectPath, answer, projectSettings);
689
+ // execSync(`composer install`, { stdio: "inherit" });
690
+ // execSync(`composer dump-autoload`, { stdio: "inherit" });
691
+ // Create settings file
692
+ // const settingsPath = path.join(
693
+ // projectPath,
694
+ // "settings",
695
+ // "project-settings.js"
696
+ // );
697
+ // const settingsCode = `export const projectSettings = {
698
+ // PROJECT_NAME: "${answer.projectName}",
699
+ // PROJECT_ROOT_PATH: "${projectPath.replace(/\\/g, "\\\\")}",
700
+ // PHP_ROOT_PATH_EXE: "D:\\\\xampp\\\\php\\\\php.exe",
701
+ // PHP_GENERATE_CLASS_PATH: "src/Lib/Prisma/Classes",
702
+ // };`;
703
+ // fs.writeFileSync(settingsPath, settingsCode, { flag: "w" });
704
+ const publicDirPath = path.join(projectPath, "public");
705
+ if (!fs.existsSync(publicDirPath)) {
706
+ fs.mkdirSync(publicDirPath);
707
+ }
708
+ if (!answer.tailwindcss) {
709
+ const cssPath = path.join(projectPath, "src", "app", "css");
710
+ const tailwindFiles = ["tailwind.css", "styles.css"];
711
+ tailwindFiles.forEach((file) => {
712
+ const filePath = path.join(cssPath, file);
713
+ if (fs.existsSync(filePath)) {
714
+ fs.unlinkSync(filePath); // Delete each file if it exists
715
+ console.log(`${file} was deleted successfully.`);
716
+ } else {
717
+ console.log(`${file} does not exist.`);
718
+ }
719
+ });
720
+ }
721
+ // Update websocket if not chosen by the user
722
+ if (!answer.websocket) {
723
+ const wsPath = path.join(projectPath, "src", "Lib", "Websocket");
724
+ // Check if the websocket directory exists
725
+ if (fs.existsSync(wsPath)) {
726
+ // Use fs.rmSync with recursive option set to true to delete the directory and its contents
727
+ fs.rmSync(wsPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
728
+ console.log("Websocket directory was deleted successfully.");
729
+ } else {
730
+ console.log("Websocket directory does not exist.");
731
+ }
732
+ // Update settings directory if websocket is not chosen
733
+ const settingsPath = path.join(projectPath, "settings");
734
+ const websocketFiles = ["restart-websocket.cjs", "restart-websocket.bat"];
735
+ websocketFiles.forEach((file) => {
736
+ const filePath = path.join(settingsPath, file);
737
+ if (fs.existsSync(filePath)) {
738
+ fs.unlinkSync(filePath); // Delete each file if it exists
739
+ console.log(`${file} was deleted successfully.`);
740
+ } else {
741
+ console.log(`${file} does not exist.`);
742
+ }
743
+ });
744
+ }
745
+ if (!answer.prisma) {
746
+ const prismaPath = path.join(projectPath, "prisma");
747
+ const prismClassPath = path.join(projectPath, "src", "Lib", "Prisma");
748
+ // Check if the prisma directory exists
749
+ if (fs.existsSync(prismaPath)) {
750
+ // Use fs.rmSync with recursive option set to true to delete the directory and its contents
751
+ fs.rmSync(prismaPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
752
+ console.log("Prisma directory was deleted successfully.");
753
+ } else {
754
+ console.log("Prisma directory does not exist.");
755
+ }
756
+ // Check if the prisma class directory exists
757
+ if (fs.existsSync(prismClassPath)) {
758
+ // Use fs.rmSync with recursive option set to true to delete the directory and its contents
759
+ fs.rmSync(prismClassPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
760
+ console.log("Prisma class directory was deleted successfully.");
761
+ } else {
762
+ console.log("Prisma class directory does not exist.");
763
+ }
764
+ }
765
+ if (
766
+ updateAnswer === null || updateAnswer === void 0
767
+ ? void 0
768
+ : updateAnswer.isUpdate
769
+ ) {
770
+ const updateUninstallDependencies = [];
771
+ if (!updateAnswer.tailwindcss) {
772
+ const tailwindFiles = ["postcss.config.js", "tailwind.config.js"];
773
+ tailwindFiles.forEach((file) => {
774
+ const filePath = path.join(projectPath, file);
775
+ if (fs.existsSync(filePath)) {
776
+ fs.unlinkSync(filePath); // Delete each file if it exists
777
+ console.log(`${file} was deleted successfully.`);
778
+ } else {
779
+ console.log(`${file} does not exist.`);
780
+ }
781
+ });
782
+ updateUninstallDependencies.push(
783
+ "tailwindcss",
784
+ "autoprefixer",
785
+ "postcss",
786
+ "postcss-cli",
787
+ "cssnano"
788
+ );
789
+ }
790
+ if (!updateAnswer.websocket) {
791
+ updateUninstallDependencies.push("chokidar-cli");
792
+ }
793
+ if (!updateAnswer.prisma) {
794
+ updateUninstallDependencies.push("prisma", "@prisma/client");
795
+ }
796
+ if (updateUninstallDependencies.length > 0) {
797
+ await uninstallDependencies(
798
+ projectPath,
799
+ updateUninstallDependencies,
800
+ true
801
+ );
802
+ }
803
+ }
804
+ const version = await fetchPackageVersion("create-prisma-php-app");
805
+ const bsConfig = bsConfigUrls(projectSettings);
806
+ const phpGenerateClassPath = answer.prisma ? "src/Lib/Prisma/Classes" : "";
807
+ const prismaPhpConfig = {
808
+ projectName: answer.projectName,
809
+ projectRootPath: projectPathModified,
810
+ phpEnvironment: "XAMPP",
811
+ phpRootPathExe: "D:\\xampp\\php\\php.exe",
812
+ phpGenerateClassPath,
813
+ bsTarget: bsConfig.bsTarget,
814
+ bsPathRewrite: bsConfig.bsPathRewrite,
815
+ tailwindcss: answer.tailwindcss,
816
+ websocket: answer.websocket,
817
+ prisma: answer.prisma,
818
+ version,
819
+ excludeFiles:
820
+ (_f =
821
+ updateAnswer === null || updateAnswer === void 0
822
+ ? void 0
823
+ : updateAnswer.excludeFiles) !== null && _f !== void 0
824
+ ? _f
825
+ : [],
826
+ };
827
+ fs.writeFileSync(
828
+ path.join(projectPath, "prisma-php.json"),
829
+ JSON.stringify(prismaPhpConfig, null, 2),
830
+ { flag: "w" }
831
+ );
832
+ console.log("currentDir", currentDir);
833
+ console.log("projectPath", projectPath);
834
+ process.chdir(projectPath);
835
+ execSync(`composer install`, { stdio: "inherit" });
836
+ // execSync(`php composer install`, { stdio: "inherit" });
837
+ // execSync(`D:\\xampp\\php\\php.exe php composer install`, { stdio: "inherit" });
838
+ console.log(
839
+ `${chalk.green("Success!")} Prisma PHP project successfully created in ${
840
+ answer.projectName
841
+ }!`
842
+ );
843
+ } catch (error) {
844
+ console.error("Error while creating the project:", error);
845
+ process.exit(1);
846
+ }
847
+ }
848
+ main();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-prisma-php-app",
3
- "version": "1.11.7",
3
+ "version": "1.11.520",
4
4
  "description": "Prisma-PHP: A Revolutionary Library Bridging PHP with Prisma ORM",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",