create-prisma-php-app 4.0.0-alpha.5 → 4.0.0-alpha.7

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,5 +1,5 @@
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";import{randomBytes}from"crypto";const __filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename);let updateAnswer=null;const nonBackendFiles=["favicon.ico","\\src\\app\\index.php","metadata.php","not-found.php","error.php"],dockerFiles=[".dockerignore","docker-compose.yml","Dockerfile","apache.conf"];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 c=`http://localhost/${n}`;c=c.endsWith("/")?c.slice(0,-1):c;const o=c.replace(/(?<!:)(\/\/+)/g,"/"),i=n.replace(/\/\/+/g,"/");return{bsTarget:`${o}/`,bsPathRewrite:{"^/":`/${i.startsWith("/")?i.substring(1):i}/`}}}async function updatePackageJson(e,s){const t=path.join(e,"package.json");if(checkExcludeFiles(t))return;const n=JSON.parse(fs.readFileSync(t,"utf8"));n.scripts={...n.scripts,projectName:"tsx settings/project-name.ts"};let c=[];if(s.tailwindcss&&(n.scripts={...n.scripts,tailwind:"postcss src/app/css/tailwind.css -o src/app/css/styles.css --watch","tailwind:build":"postcss src/app/css/tailwind.css -o src/app/css/styles.css"},c.push("tailwind")),s.websocket&&(n.scripts={...n.scripts,websocket:"tsx settings/restart-websocket.ts"},c.push("websocket")),s.docker&&(n.scripts={...n.scripts,docker:"docker-compose up"},c.push("docker")),s.swaggerDocs){const e=s.prisma?"tsx settings/auto-swagger-docs.ts":"tsx settings/swagger-config.ts";n.scripts={...n.scripts,"create-swagger-docs":e}}let o={...n.scripts};o.browserSync="tsx settings/bs-config.ts",o["browserSync:build"]="tsx settings/build.ts",o.dev=`npm-run-all projectName -p browserSync ${c.join(" ")}`,o.build=`npm-run-all${s.tailwindcss?" tailwind:build":""} browserSync:build`,n.scripts=o,n.type="module",fs.writeFileSync(t,JSON.stringify(n,null,2))}async function updateComposerJson(e){const s=path.join(e,"composer.json");if(checkExcludeFiles(s))return;let t;if(fs.existsSync(s)){{const e=fs.readFileSync(s,"utf8");t=JSON.parse(e)}t.autoload={"psr-4":{"":"src/"}},t.version="1.0.0",fs.writeFileSync(s,JSON.stringify(t,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\nvar ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,n,"utf8")}function generateAuthSecret(){return randomBytes(33).toString("base64")}function generateHexEncodedKey(e=16){return randomBytes(e).toString("hex")}function copyRecursiveSync(e,s,t){const n=fs.existsSync(e),c=n&&fs.statSync(e);if(n&&c&&c.isDirectory()){const n=s.toLowerCase();if(!t.websocket&&n.includes("src\\websocket"))return;if(t.backendOnly&&n.includes("src\\app\\js")||t.backendOnly&&n.includes("src\\app\\css")||t.backendOnly&&n.includes("src\\app\\assets"))return;if(!t.swaggerDocs&&n.includes("src\\app\\swagger-docs"))return;const c=s.replace(/\\/g,"/");if(updateAnswer?.excludeFilePath?.includes(c))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.ts")||s.includes("restart-websocket.bat")||s.includes("websocket-server.php")))return;if(!t.docker&&dockerFiles.some((e=>s.includes(e))))return;if(t.backendOnly&&nonBackendFiles.some((e=>s.includes(e))))return;if(!t.backendOnly&&s.includes("route.php"))return;if(t.backendOnly&&!t.swaggerDocs&&s.includes("layout.php"))return;if(!t.swaggerDocs&&s.includes("swagger-config.ts"))return;if(t.tailwindcss&&s.includes("index.css"))return;if((!t.swaggerDocs||!t.prisma)&&(s.includes("auto-swagger-docs.ts")||s.includes("prisma-schema-config.json")))return;fs.copyFileSync(e,s,0)}}async function executeCopy(e,s,t){s.forEach((({src:s,dest:n})=>{copyRecursiveSync(path.join(__dirname,s),path.join(e,n),t)}))}function modifyPostcssConfig(e){const s=path.join(e,"postcss.config.js");if(checkExcludeFiles(s))return;fs.writeFileSync(s,'export default {\n plugins: {\n "@tailwindcss/postcss": {},\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"),n="";s.backendOnly||(s.tailwindcss||(n='\n <link href="<?= Request::baseUrl; ?>/css/index.css" rel="stylesheet" />'),n+='\n <script src="<?= Request::baseUrl; ?>/js/morphdom-umd.min.js"><\/script>\n <script src="<?= Request::baseUrl; ?>/js/json5.min.js"><\/script>\n <script src="<?= Request::baseUrl; ?>/js/index.js"><\/script>');let c="";s.backendOnly||(c=s.tailwindcss?` <link href="<?= Request::baseUrl; ?>/css/styles.css" rel="stylesheet" /> ${n}`:n),e=e.replace("</head>",`${c}\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){return!!updateAnswer?.isUpdate&&(updateAnswer?.excludeFilePath?.includes(e.replace(/\\/g,"/"))??!1)}async function createDirectoryStructure(e,s){const t=[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/tsconfig.json",dest:"/tsconfig.json"},{src:"/app-gitignore",dest:"/.gitignore"}];s.tailwindcss&&t.push({src:"/postcss.config.js",dest:"/postcss.config.js"}),s.websocket&&t.push({src:"/websocket-server.php",dest:"/websocket-server.php"});const n=[{src:"/settings",dest:"/settings"},{src:"/src",dest:"/src"}];s.docker&&n.push({src:"/.dockerignore",dest:"/.dockerignore"},{src:"/docker-compose.yml",dest:"/docker-compose.yml"},{src:"/Dockerfile",dest:"/Dockerfile"},{src:"/apache.conf",dest:"/apache.conf"}),t.forEach((({src:s,dest:t})=>{const n=path.join(__dirname,s),c=path.join(e,t);if(checkExcludeFiles(c))return;const o=fs.readFileSync(n,"utf8");fs.writeFileSync(c,o,{flag:"w"})})),await executeCopy(e,n,s),await updatePackageJson(e,s),await updateComposerJson(e),s.backendOnly||await updateIndexJsForWebSocket(e,s),s.tailwindcss&&modifyPostcssConfig(e),(s.tailwindcss||!s.backendOnly||s.swaggerDocs)&&modifyLayoutPHP(e,s);const c=generateAuthSecret(),o=generateHexEncodedKey(),i=`# Authentication secret key for JWT or session encryption.\nAUTH_SECRET="${c}"\n# Name of the authentication cookie.\nAUTH_COOKIE_NAME="${generateHexEncodedKey(8)}"\n\n# PHPMailer SMTP configuration (uncomment and set as needed)\n# SMTP_HOST="smtp.gmail.com" # Your SMTP host\n# SMTP_USERNAME="john.doe@gmail.com" # Your SMTP username\n# SMTP_PASSWORD="123456" # Your SMTP password\n# SMTP_PORT="587" # 587 for TLS, 465 for SSL, or your SMTP port\n# SMTP_ENCRYPTION="ssl" # ssl or tls\n# MAIL_FROM="john.doe@gmail.com" # Sender email address\n# MAIL_FROM_NAME="John Doe" # Sender name\n\n# Show errors in the browser (development only). Set to false in production.\nSHOW_ERRORS="true"\n\n# Application timezone (default: UTC)\nAPP_TIMEZONE="UTC"\n\n# Application environment (development or production)\nAPP_ENV="development"\n\n# Enable or disable application cache (default: false)\nCACHE_ENABLED="false"\n# Cache time-to-live in seconds (default: 600)\nCACHE_TTL="600"\n\n# Local storage key for browser storage (auto-generated if not set).\n# Spaces will be replaced with underscores and converted to lowercase.\nLOCALSTORE_KEY="${o}"\n\n# Secret key for encrypting function calls.\nFUNCTION_CALL_SECRET="${generateHexEncodedKey(32)}"`;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)}async function getAnswer(e={}){const s=[];e.projectName||s.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.backendOnly||s.push({type:"toggle",name:"backendOnly",message:`Would you like to create a ${chalk.blue("backend-only project")}?`,initial:!1,active:"Yes",inactive:"No"});const t=()=>{process.exit(0)},n=await prompts(s,{onCancel:t}),c=[];n.backendOnly||e.backendOnly?(e.swaggerDocs||c.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,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"}),e.docker||c.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"})):(e.swaggerDocs||c.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),e.tailwindcss||c.push({type:"toggle",name:"tailwindcss",message:`Would you like to use ${chalk.blue("Tailwind CSS")}?`,initial:!1,active:"Yes",inactive:"No"}),e.websocket||c.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!1,active:"Yes",inactive:"No"}),e.prisma||c.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!1,active:"Yes",inactive:"No"}),e.docker||c.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"}));const o=await prompts(c,{onCancel:t});return{projectName:n.projectName?String(n.projectName).trim().replace(/ /g,"-"):e.projectName??"my-app",backendOnly:n.backendOnly??e.backendOnly??!1,swaggerDocs:o.swaggerDocs??e.swaggerDocs??!1,tailwindcss:o.tailwindcss??e.tailwindcss??!1,websocket:o.websocket??e.websocket??!1,prisma:o.prisma??e.prisma??!1,docker:o.docker??e.docker??!1}}async function uninstallNpmDependencies(e,s,t=!1){s.forEach((e=>{}));const n=`npm uninstall ${t?"--save-dev":"--save"} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}async function uninstallComposerDependencies(e,s){s.forEach((e=>{}));const t=`C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar remove ${s.join(" ")}`;execSync(t,{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)};function compareVersions(e,s){const t=e.split(".").map(Number),n=s.split(".").map(Number);for(let e=0;e<t.length;e++){if(t[e]>n[e])return 1;if(t[e]<n[e])return-1}return 0}function getInstalledPackageVersion(e){try{const s=execSync(`npm list -g ${e} --depth=0`).toString().match(new RegExp(`${e}@(\\d+\\.\\d+\\.\\d+)`));return s?s[1]:null}catch(e){return null}}
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";import{randomBytes}from"crypto";const __filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename);let updateAnswer=null;const nonBackendFiles=["favicon.ico","\\src\\app\\index.php","metadata.php","not-found.php","error.php"],dockerFiles=[".dockerignore","docker-compose.yml","Dockerfile","apache.conf"];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 c=`http://localhost/${n}`;c=c.endsWith("/")?c.slice(0,-1):c;const o=c.replace(/(?<!:)(\/\/+)/g,"/"),i=n.replace(/\/\/+/g,"/");return{bsTarget:`${o}/`,bsPathRewrite:{"^/":`/${i.startsWith("/")?i.substring(1):i}/`}}}async function updatePackageJson(e,s){const t=path.join(e,"package.json");if(checkExcludeFiles(t))return;const n=JSON.parse(fs.readFileSync(t,"utf8"));n.scripts={...n.scripts,projectName:"tsx settings/project-name.ts"};let c=[];if(s.tailwindcss&&(n.scripts={...n.scripts,tailwind:"postcss src/app/css/tailwind.css -o src/app/css/styles.css --watch","tailwind:build":"postcss src/app/css/tailwind.css -o src/app/css/styles.css"},c.push("tailwind")),s.websocket&&(n.scripts={...n.scripts,websocket:"tsx settings/restart-websocket.ts"},c.push("websocket")),s.docker&&(n.scripts={...n.scripts,docker:"docker-compose up"},c.push("docker")),s.swaggerDocs){const e=s.prisma?"tsx settings/auto-swagger-docs.ts":"tsx settings/swagger-config.ts";n.scripts={...n.scripts,"create-swagger-docs":e}}let o={...n.scripts};o.browserSync="tsx settings/bs-config.ts",o["browserSync:build"]="tsx settings/build.ts",o.dev=`npm-run-all projectName -p browserSync ${c.join(" ")}`,o.build=`npm-run-all${s.tailwindcss?" tailwind:build":""} browserSync:build`,n.scripts=o,n.type="module",fs.writeFileSync(t,JSON.stringify(n,null,2))}async function updateComposerJson(e){const s=path.join(e,"composer.json");if(checkExcludeFiles(s))return;let t;if(fs.existsSync(s)){{const e=fs.readFileSync(s,"utf8");t=JSON.parse(e)}t.autoload={"psr-4":{"":"src/"}},t.version="1.0.0",fs.writeFileSync(s,JSON.stringify(t,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\nvar ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,n,"utf8")}function generateAuthSecret(){return randomBytes(33).toString("base64")}function generateHexEncodedKey(e=16){return randomBytes(e).toString("hex")}function copyRecursiveSync(e,s,t){const n=fs.existsSync(e),c=n&&fs.statSync(e);if(n&&c&&c.isDirectory()){const n=s.toLowerCase();if(!t.websocket&&n.includes("src\\lib\\websocket"))return;if(t.backendOnly&&n.includes("src\\app\\js")||t.backendOnly&&n.includes("src\\app\\css")||t.backendOnly&&n.includes("src\\app\\assets"))return;if(!t.swaggerDocs&&n.includes("src\\app\\swagger-docs"))return;const c=s.replace(/\\/g,"/");if(updateAnswer?.excludeFilePath?.includes(c))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.ts")||s.includes("restart-websocket.bat")))return;if(!t.docker&&dockerFiles.some((e=>s.includes(e))))return;if(t.backendOnly&&nonBackendFiles.some((e=>s.includes(e))))return;if(!t.backendOnly&&s.includes("route.php"))return;if(t.backendOnly&&!t.swaggerDocs&&s.includes("layout.php"))return;if(!t.swaggerDocs&&s.includes("swagger-config.ts"))return;if(t.tailwindcss&&s.includes("index.css"))return;if((!t.swaggerDocs||!t.prisma)&&(s.includes("auto-swagger-docs.ts")||s.includes("prisma-schema-config.json")))return;fs.copyFileSync(e,s,0)}}async function executeCopy(e,s,t){s.forEach((({src:s,dest:n})=>{copyRecursiveSync(path.join(__dirname,s),path.join(e,n),t)}))}function modifyPostcssConfig(e){const s=path.join(e,"postcss.config.js");if(checkExcludeFiles(s))return;fs.writeFileSync(s,'export default {\n plugins: {\n "@tailwindcss/postcss": {},\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"),n="";s.backendOnly||(s.tailwindcss||(n='\n <link href="<?= Request::baseUrl; ?>/css/index.css" rel="stylesheet" />'),n+='\n <script src="<?= Request::baseUrl; ?>/js/morphdom-umd.min.js"><\/script>\n <script src="<?= Request::baseUrl; ?>/js/json5.min.js"><\/script>\n <script src="<?= Request::baseUrl; ?>/js/index.js"><\/script>');let c="";s.backendOnly||(c=s.tailwindcss?` <link href="<?= Request::baseUrl; ?>/css/styles.css" rel="stylesheet" /> ${n}`:n),e=e.replace("</head>",`${c}\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){return!!updateAnswer?.isUpdate&&(updateAnswer?.excludeFilePath?.includes(e.replace(/\\/g,"/"))??!1)}async function createDirectoryStructure(e,s){const t=[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/tsconfig.json",dest:"/tsconfig.json"},{src:"/app-gitignore",dest:"/.gitignore"}];s.tailwindcss&&t.push({src:"/postcss.config.js",dest:"/postcss.config.js"});const n=[{src:"/settings",dest:"/settings"},{src:"/src",dest:"/src"}];s.docker&&n.push({src:"/.dockerignore",dest:"/.dockerignore"},{src:"/docker-compose.yml",dest:"/docker-compose.yml"},{src:"/Dockerfile",dest:"/Dockerfile"},{src:"/apache.conf",dest:"/apache.conf"}),t.forEach((({src:s,dest:t})=>{const n=path.join(__dirname,s),c=path.join(e,t);if(checkExcludeFiles(c))return;const o=fs.readFileSync(n,"utf8");fs.writeFileSync(c,o,{flag:"w"})})),await executeCopy(e,n,s),await updatePackageJson(e,s),await updateComposerJson(e),s.backendOnly||await updateIndexJsForWebSocket(e,s),s.tailwindcss&&modifyPostcssConfig(e),(s.tailwindcss||!s.backendOnly||s.swaggerDocs)&&modifyLayoutPHP(e,s);const c=generateAuthSecret(),o=generateHexEncodedKey(),i=`# Authentication secret key for JWT or session encryption.\nAUTH_SECRET="${c}"\n# Name of the authentication cookie.\nAUTH_COOKIE_NAME="${generateHexEncodedKey(8)}"\n\n# PHPMailer SMTP configuration (uncomment and set as needed)\n# SMTP_HOST="smtp.gmail.com" # Your SMTP host\n# SMTP_USERNAME="john.doe@gmail.com" # Your SMTP username\n# SMTP_PASSWORD="123456" # Your SMTP password\n# SMTP_PORT="587" # 587 for TLS, 465 for SSL, or your SMTP port\n# SMTP_ENCRYPTION="ssl" # ssl or tls\n# MAIL_FROM="john.doe@gmail.com" # Sender email address\n# MAIL_FROM_NAME="John Doe" # Sender name\n\n# Show errors in the browser (development only). Set to false in production.\nSHOW_ERRORS="true"\n\n# Application timezone (default: UTC)\nAPP_TIMEZONE="UTC"\n\n# Application environment (development or production)\nAPP_ENV="development"\n\n# Enable or disable application cache (default: false)\nCACHE_ENABLED="false"\n# Cache time-to-live in seconds (default: 600)\nCACHE_TTL="600"\n\n# Local storage key for browser storage (auto-generated if not set).\n# Spaces will be replaced with underscores and converted to lowercase.\nLOCALSTORE_KEY="${o}"\n\n# Secret key for encrypting function calls.\nFUNCTION_CALL_SECRET="${generateHexEncodedKey(32)}"`;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)}async function getAnswer(e={}){const s=[];e.projectName||s.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.backendOnly||s.push({type:"toggle",name:"backendOnly",message:`Would you like to create a ${chalk.blue("backend-only project")}?`,initial:!1,active:"Yes",inactive:"No"});const t=()=>{process.exit(0)},n=await prompts(s,{onCancel:t}),c=[];n.backendOnly||e.backendOnly?(e.swaggerDocs||c.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,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"}),e.docker||c.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"})):(e.swaggerDocs||c.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),e.tailwindcss||c.push({type:"toggle",name:"tailwindcss",message:`Would you like to use ${chalk.blue("Tailwind CSS")}?`,initial:!1,active:"Yes",inactive:"No"}),e.websocket||c.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!1,active:"Yes",inactive:"No"}),e.prisma||c.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!1,active:"Yes",inactive:"No"}),e.docker||c.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"}));const o=await prompts(c,{onCancel:t});return{projectName:n.projectName?String(n.projectName).trim().replace(/ /g,"-"):e.projectName??"my-app",backendOnly:n.backendOnly??e.backendOnly??!1,swaggerDocs:o.swaggerDocs??e.swaggerDocs??!1,tailwindcss:o.tailwindcss??e.tailwindcss??!1,websocket:o.websocket??e.websocket??!1,prisma:o.prisma??e.prisma??!1,docker:o.docker??e.docker??!1}}async function uninstallNpmDependencies(e,s,t=!1){s.forEach((e=>{}));const n=`npm uninstall ${t?"--save-dev":"--save"} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}async function uninstallComposerDependencies(e,s){s.forEach((e=>{}));const t=`C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar remove ${s.join(" ")}`;execSync(t,{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)};function compareVersions(e,s){const t=e.split(".").map(Number),n=s.split(".").map(Number);for(let e=0;e<t.length;e++){if(t[e]>n[e])return 1;if(t[e]<n[e])return-1}return 0}function getInstalledPackageVersion(e){try{const s=execSync(`npm list -g ${e} --depth=0`).toString().match(new RegExp(`${e}@(\\d+\\.\\d+\\.\\d+)`));return s?s[1]:null}catch(e){return null}}
3
3
  /**
4
4
  * Install dependencies in the specified directory.
5
5
  * @param {string} baseDir - The base directory where to install the dependencies.
@@ -7,380 +7,449 @@ import{execSync}from"child_process";import fs from"fs";import{fileURLToPath}from
7
7
  * @param {boolean} [isDev=false] - Whether to install the dependencies as devDependencies.
8
8
  */
9
9
  async function installNpmDependencies(baseDir, dependencies, isDev = false) {
10
- console.log("Initializing new Node.js project...");
11
- // Initialize a package.json if it doesn't exist
12
- if (!fs.existsSync(path.join(baseDir, "package.json"))) {
13
- execSync("npm init -y", {
14
- stdio: "inherit",
15
- cwd: baseDir,
16
- });
17
- }
18
- // Log the dependencies being installed
19
- console.log(`${isDev ? "Installing development dependencies" : "Installing dependencies"}:`);
20
- dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
21
- // Prepare the npm install command with the appropriate flag for dev dependencies
22
- const npmInstallCommand = `npm install ${isDev ? "--save-dev" : ""} ${dependencies.join(" ")}`;
23
- // Execute the npm install command
24
- execSync(npmInstallCommand, {
25
- stdio: "inherit",
26
- cwd: baseDir,
10
+ console.log("Initializing new Node.js project...");
11
+ // Initialize a package.json if it doesn't exist
12
+ if (!fs.existsSync(path.join(baseDir, "package.json"))) {
13
+ execSync("npm init -y", {
14
+ stdio: "inherit",
15
+ cwd: baseDir,
27
16
  });
17
+ }
18
+ // Log the dependencies being installed
19
+ console.log(
20
+ `${
21
+ isDev ? "Installing development dependencies" : "Installing dependencies"
22
+ }:`
23
+ );
24
+ dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
25
+ // Prepare the npm install command with the appropriate flag for dev dependencies
26
+ const npmInstallCommand = `npm install ${
27
+ isDev ? "--save-dev" : ""
28
+ } ${dependencies.join(" ")}`;
29
+ // Execute the npm install command
30
+ execSync(npmInstallCommand, {
31
+ stdio: "inherit",
32
+ cwd: baseDir,
33
+ });
28
34
  }
29
35
  async function installComposerDependencies(baseDir, dependencies) {
30
- console.log("Initializing new Composer project...");
31
- // Initialize a composer.json if it doesn't exist
32
- if (!fs.existsSync(path.join(baseDir, "composer.json"))) {
33
- execSync(`composer init -n --name="tsnc/prisma-php-app" --require="php:^8.2"`, {
34
- stdio: "inherit",
35
- cwd: baseDir,
36
- });
37
- }
38
- // Log the dependencies being installed
39
- console.log("Installing Composer dependencies:");
40
- dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
41
- // Prepare the composer require command
42
- const composerRequireCommand = `C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar require ${dependencies.join(" ")}`;
43
- // Execute the composer require command
44
- execSync(composerRequireCommand, {
36
+ console.log("Initializing new Composer project...");
37
+ // Initialize a composer.json if it doesn't exist
38
+ if (!fs.existsSync(path.join(baseDir, "composer.json"))) {
39
+ execSync(
40
+ `composer init -n --name="tsnc/prisma-php-app" --require="php:^8.2"`,
41
+ {
45
42
  stdio: "inherit",
46
43
  cwd: baseDir,
47
- });
44
+ }
45
+ );
46
+ }
47
+ // Log the dependencies being installed
48
+ console.log("Installing Composer dependencies:");
49
+ dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
50
+ // Prepare the composer require command
51
+ const composerRequireCommand = `C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar require ${dependencies.join(
52
+ " "
53
+ )}`;
54
+ // Execute the composer require command
55
+ execSync(composerRequireCommand, {
56
+ stdio: "inherit",
57
+ cwd: baseDir,
58
+ });
48
59
  }
49
60
  const npmPinnedVersions = {
50
- "@tailwindcss/postcss": "^4.1.11",
51
- "@types/browser-sync": "^2.29.0",
52
- "@types/node": "^24.0.7",
53
- "@types/prompts": "^2.4.9",
54
- "browser-sync": "^3.0.4",
55
- chalk: "^5.4.1",
56
- "chokidar-cli": "^3.0.0",
57
- cssnano: "^7.0.7",
58
- "http-proxy-middleware": "^3.0.5",
59
- "npm-run-all": "^4.1.5",
60
- "php-parser": "^3.2.4",
61
- postcss: "^8.5.6",
62
- "postcss-cli": "^11.0.1",
63
- prompts: "^2.4.2",
64
- tailwindcss: "^4.1.11",
65
- tsx: "^4.20.3",
66
- typescript: "^5.8.3",
61
+ "@tailwindcss/postcss": "^4.1.11",
62
+ "@types/browser-sync": "^2.29.0",
63
+ "@types/node": "^24.0.7",
64
+ "@types/prompts": "^2.4.9",
65
+ "browser-sync": "^3.0.4",
66
+ chalk: "^5.4.1",
67
+ "chokidar-cli": "^3.0.0",
68
+ cssnano: "^7.0.7",
69
+ "http-proxy-middleware": "^3.0.5",
70
+ "npm-run-all": "^4.1.5",
71
+ "php-parser": "^3.2.4",
72
+ postcss: "^8.5.6",
73
+ "postcss-cli": "^11.0.1",
74
+ prompts: "^2.4.2",
75
+ tailwindcss: "^4.1.11",
76
+ tsx: "^4.20.3",
77
+ typescript: "^5.8.3",
67
78
  };
68
79
  function npmPkg(name) {
69
- return npmPinnedVersions[name] ? `${name}@${npmPinnedVersions[name]}` : name;
80
+ return npmPinnedVersions[name] ? `${name}@${npmPinnedVersions[name]}` : name;
70
81
  }
71
82
  const composerPinnedVersions = {
72
- "vlucas/phpdotenv": "^5.6.2",
73
- "firebase/php-jwt": "^6.11.1",
74
- "phpmailer/phpmailer": "^6.10.0",
75
- "guzzlehttp/guzzle": "^7.9.3",
76
- "ezyang/htmlpurifier": "^4.18.0",
77
- "symfony/uid": "^7.2.0",
78
- "brick/math": "^0.13.1",
79
- "cboden/ratchet": "^0.4.4",
80
- "tsnc/prisma-php": "^1.0.0",
83
+ "vlucas/phpdotenv": "^5.6.2",
84
+ "firebase/php-jwt": "^6.11.1",
85
+ "phpmailer/phpmailer": "^6.10.0",
86
+ "guzzlehttp/guzzle": "^7.9.3",
87
+ "ezyang/htmlpurifier": "^4.18.0",
88
+ "symfony/uid": "^7.2.0",
89
+ "brick/math": "^0.13.1",
90
+ "cboden/ratchet": "^0.4.4",
91
+ "tsnc/prisma-php": "^1.0.0",
81
92
  };
82
93
  function composerPkg(name) {
83
- return composerPinnedVersions[name]
84
- ? `${name}:${composerPinnedVersions[name]}`
85
- : name;
94
+ return composerPinnedVersions[name]
95
+ ? `${name}:${composerPinnedVersions[name]}`
96
+ : name;
86
97
  }
87
98
  async function main() {
88
- try {
89
- const args = process.argv.slice(2);
90
- let projectName = args[0];
91
- let answer = null;
92
- if (projectName) {
93
- let useBackendOnly = args.includes("--backend-only");
94
- let useSwaggerDocs = args.includes("--swagger-docs");
95
- let useTailwind = args.includes("--tailwindcss");
96
- let useWebsocket = args.includes("--websocket");
97
- let usePrisma = args.includes("--prisma");
98
- let useDocker = args.includes("--docker");
99
- const predefinedAnswers = {
100
- projectName,
101
- backendOnly: useBackendOnly,
102
- swaggerDocs: useSwaggerDocs,
103
- tailwindcss: useTailwind,
104
- websocket: useWebsocket,
105
- prisma: usePrisma,
106
- docker: useDocker,
107
- };
108
- answer = await getAnswer(predefinedAnswers);
109
- if (answer === null) {
110
- console.log(chalk.red("Installation cancelled."));
111
- return;
112
- }
113
- const currentDir = process.cwd();
114
- const configPath = path.join(currentDir, "prisma-php.json");
115
- if (fs.existsSync(configPath)) {
116
- const localSettings = readJsonFile(configPath);
117
- let excludeFiles = [];
118
- localSettings.excludeFiles?.map((file) => {
119
- const filePath = path.join(currentDir, file);
120
- if (fs.existsSync(filePath))
121
- excludeFiles.push(filePath.replace(/\\/g, "/"));
122
- });
123
- updateAnswer = {
124
- projectName,
125
- backendOnly: answer?.backendOnly ?? false,
126
- swaggerDocs: answer?.swaggerDocs ?? false,
127
- tailwindcss: answer?.tailwindcss ?? false,
128
- websocket: answer?.websocket ?? false,
129
- prisma: answer?.prisma ?? false,
130
- docker: answer?.docker ?? false,
131
- isUpdate: true,
132
- excludeFiles: localSettings.excludeFiles ?? [],
133
- excludeFilePath: excludeFiles ?? [],
134
- filePath: currentDir,
135
- };
136
- }
137
- }
138
- else {
139
- answer = await getAnswer();
140
- }
141
- if (answer === null) {
142
- console.warn(chalk.red("Installation cancelled."));
143
- return;
144
- }
145
- const latestVersionOfCreatePrismaPhpApp = await fetchPackageVersion("create-prisma-php-app");
146
- const isCreatePrismaPhpAppInstalled = getInstalledPackageVersion("create-prisma-php-app");
147
- if (isCreatePrismaPhpAppInstalled) {
148
- if (compareVersions(isCreatePrismaPhpAppInstalled, latestVersionOfCreatePrismaPhpApp) === -1) {
149
- execSync("npm uninstall -g create-prisma-php-app", {
150
- stdio: "inherit",
151
- });
152
- execSync("npm install -g create-prisma-php-app", {
153
- stdio: "inherit",
154
- });
155
- }
99
+ try {
100
+ const args = process.argv.slice(2);
101
+ let projectName = args[0];
102
+ let answer = null;
103
+ if (projectName) {
104
+ let useBackendOnly = args.includes("--backend-only");
105
+ let useSwaggerDocs = args.includes("--swagger-docs");
106
+ let useTailwind = args.includes("--tailwindcss");
107
+ let useWebsocket = args.includes("--websocket");
108
+ let usePrisma = args.includes("--prisma");
109
+ let useDocker = args.includes("--docker");
110
+ const predefinedAnswers = {
111
+ projectName,
112
+ backendOnly: useBackendOnly,
113
+ swaggerDocs: useSwaggerDocs,
114
+ tailwindcss: useTailwind,
115
+ websocket: useWebsocket,
116
+ prisma: usePrisma,
117
+ docker: useDocker,
118
+ };
119
+ answer = await getAnswer(predefinedAnswers);
120
+ if (answer === null) {
121
+ console.log(chalk.red("Installation cancelled."));
122
+ return;
123
+ }
124
+ const currentDir = process.cwd();
125
+ const configPath = path.join(currentDir, "prisma-php.json");
126
+ if (fs.existsSync(configPath)) {
127
+ const localSettings = readJsonFile(configPath);
128
+ let excludeFiles = [];
129
+ localSettings.excludeFiles?.map((file) => {
130
+ const filePath = path.join(currentDir, file);
131
+ if (fs.existsSync(filePath))
132
+ excludeFiles.push(filePath.replace(/\\/g, "/"));
133
+ });
134
+ updateAnswer = {
135
+ projectName,
136
+ backendOnly: answer?.backendOnly ?? false,
137
+ swaggerDocs: answer?.swaggerDocs ?? false,
138
+ tailwindcss: answer?.tailwindcss ?? false,
139
+ websocket: answer?.websocket ?? false,
140
+ prisma: answer?.prisma ?? false,
141
+ docker: answer?.docker ?? false,
142
+ isUpdate: true,
143
+ excludeFiles: localSettings.excludeFiles ?? [],
144
+ excludeFilePath: excludeFiles ?? [],
145
+ filePath: currentDir,
146
+ };
147
+ }
148
+ } else {
149
+ answer = await getAnswer();
150
+ }
151
+ if (answer === null) {
152
+ console.warn(chalk.red("Installation cancelled."));
153
+ return;
154
+ }
155
+ const latestVersionOfCreatePrismaPhpApp = await fetchPackageVersion(
156
+ "create-prisma-php-app"
157
+ );
158
+ const isCreatePrismaPhpAppInstalled = getInstalledPackageVersion(
159
+ "create-prisma-php-app"
160
+ );
161
+ if (isCreatePrismaPhpAppInstalled) {
162
+ if (
163
+ compareVersions(
164
+ isCreatePrismaPhpAppInstalled,
165
+ latestVersionOfCreatePrismaPhpApp
166
+ ) === -1
167
+ ) {
168
+ execSync("npm uninstall -g create-prisma-php-app", {
169
+ stdio: "inherit",
170
+ });
171
+ execSync("npm install -g create-prisma-php-app", {
172
+ stdio: "inherit",
173
+ });
174
+ }
175
+ } else {
176
+ execSync("npm install -g create-prisma-php-app", { stdio: "inherit" });
177
+ }
178
+ // Create the project directory
179
+ if (!projectName) fs.mkdirSync(answer.projectName);
180
+ const currentDir = process.cwd();
181
+ let projectPath = projectName
182
+ ? currentDir
183
+ : path.join(currentDir, answer.projectName);
184
+ if (!projectName) process.chdir(answer.projectName);
185
+ let npmDependencies = [
186
+ npmPkg("typescript"),
187
+ npmPkg("@types/node"),
188
+ npmPkg("tsx"),
189
+ npmPkg("http-proxy-middleware"),
190
+ npmPkg("chalk"),
191
+ npmPkg("npm-run-all"),
192
+ npmPkg("browser-sync"),
193
+ npmPkg("@types/browser-sync"),
194
+ npmPkg("php-parser"),
195
+ ];
196
+ let composerDependencies = [
197
+ composerPkg("vlucas/phpdotenv"),
198
+ composerPkg("firebase/php-jwt"),
199
+ composerPkg("phpmailer/phpmailer"),
200
+ composerPkg("guzzlehttp/guzzle"),
201
+ composerPkg("ezyang/htmlpurifier"),
202
+ composerPkg("symfony/uid"),
203
+ composerPkg("brick/math"),
204
+ composerPkg("tsnc/prisma-php"),
205
+ ];
206
+ if (answer.swaggerDocs) {
207
+ npmDependencies.push(
208
+ npmPkg("swagger-jsdoc"),
209
+ npmPkg("@types/swagger-jsdoc")
210
+ );
211
+ }
212
+ if (answer.swaggerDocs && answer.prisma) {
213
+ npmDependencies.push(npmPkg("prompts"), npmPkg("@types/prompts"));
214
+ }
215
+ if (answer.tailwindcss) {
216
+ npmDependencies.push(
217
+ npmPkg("tailwindcss"),
218
+ npmPkg("postcss"),
219
+ npmPkg("postcss-cli"),
220
+ npmPkg("@tailwindcss/postcss"),
221
+ npmPkg("cssnano")
222
+ );
223
+ }
224
+ if (answer.websocket) {
225
+ npmDependencies.push(npmPkg("chokidar-cli"));
226
+ composerDependencies.push("cboden/ratchet");
227
+ }
228
+ if (answer.prisma) {
229
+ execSync("npm install -g prisma-client-php", { stdio: "inherit" });
230
+ }
231
+ await installNpmDependencies(projectPath, npmDependencies, true);
232
+ await installComposerDependencies(projectPath, composerDependencies);
233
+ if (!projectName) {
234
+ execSync("npx tsc --init", { stdio: "inherit" });
235
+ }
236
+ await createDirectoryStructure(projectPath, answer);
237
+ if (answer.prisma) {
238
+ execSync("npx ppo init --prisma-php", { stdio: "inherit" });
239
+ }
240
+ if (answer.swaggerDocs) {
241
+ const swaggerDocsPath = path.join(
242
+ projectPath,
243
+ "src",
244
+ "app",
245
+ "swagger-docs"
246
+ );
247
+ // Check if the directory exists
248
+ if (fs.existsSync(swaggerDocsPath)) {
249
+ // If it exists and is not empty, remove it before cloning
250
+ if (fs.readdirSync(swaggerDocsPath).length > 0) {
251
+ console.log("Removing existing swagger-docs directory...");
252
+ fs.rmSync(swaggerDocsPath, { recursive: true, force: true });
156
253
  }
157
- else {
158
- execSync("npm install -g create-prisma-php-app", { stdio: "inherit" });
254
+ }
255
+ // Clone the Git repository into the swagger-docs directory
256
+ execSync(
257
+ `git clone https://github.com/TheSteelNinjaCode/prisma-php-swagger-docs.git ${swaggerDocsPath}`,
258
+ { stdio: "inherit" }
259
+ );
260
+ // delete the folder .git
261
+ fs.rmSync(path.join(swaggerDocsPath, ".git"), {
262
+ recursive: true,
263
+ force: true,
264
+ });
265
+ }
266
+ if (updateAnswer?.isUpdate) {
267
+ const updateUninstallNpmDependencies = [];
268
+ const updateUninstallComposerDependencies = [];
269
+ if (updateAnswer.backendOnly) {
270
+ nonBackendFiles.forEach((file) => {
271
+ const filePath = path.join(projectPath, "src", "app", file);
272
+ if (fs.existsSync(filePath)) {
273
+ fs.unlinkSync(filePath); // Delete each file if it exists
274
+ console.log(`${file} was deleted successfully.`);
275
+ } else {
276
+ console.log(`${file} does not exist.`);
277
+ }
278
+ });
279
+ const backendOnlyFolders = ["js", "css"];
280
+ backendOnlyFolders.forEach((folder) => {
281
+ const folderPath = path.join(projectPath, "src", "app", folder);
282
+ if (fs.existsSync(folderPath)) {
283
+ fs.rmSync(folderPath, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
284
+ console.log(`${folder} was deleted successfully.`);
285
+ } else {
286
+ console.log(`${folder} does not exist.`);
287
+ }
288
+ });
289
+ }
290
+ if (!updateAnswer.swaggerDocs) {
291
+ const swaggerDocsFolder = path.join(
292
+ projectPath,
293
+ "src",
294
+ "app",
295
+ "swagger-docs"
296
+ );
297
+ if (fs.existsSync(swaggerDocsFolder)) {
298
+ fs.rmSync(swaggerDocsFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
299
+ console.log(`swagger-docs was deleted successfully.`);
159
300
  }
160
- // Create the project directory
161
- if (!projectName)
162
- fs.mkdirSync(answer.projectName);
163
- const currentDir = process.cwd();
164
- let projectPath = projectName
165
- ? currentDir
166
- : path.join(currentDir, answer.projectName);
167
- if (!projectName)
168
- process.chdir(answer.projectName);
169
- let npmDependencies = [
170
- npmPkg("typescript"),
171
- npmPkg("@types/node"),
172
- npmPkg("tsx"),
173
- npmPkg("http-proxy-middleware"),
174
- npmPkg("chalk"),
175
- npmPkg("npm-run-all"),
176
- npmPkg("browser-sync"),
177
- npmPkg("@types/browser-sync"),
178
- npmPkg("php-parser"),
179
- ];
180
- let composerDependencies = [
181
- composerPkg("vlucas/phpdotenv"),
182
- composerPkg("firebase/php-jwt"),
183
- composerPkg("phpmailer/phpmailer"),
184
- composerPkg("guzzlehttp/guzzle"),
185
- composerPkg("ezyang/htmlpurifier"),
186
- composerPkg("symfony/uid"),
187
- composerPkg("brick/math"),
188
- composerPkg("tsnc/prisma-php"),
301
+ const swaggerFiles = ["swagger-config.ts"];
302
+ swaggerFiles.forEach((file) => {
303
+ const filePath = path.join(projectPath, "settings", file);
304
+ if (fs.existsSync(filePath)) {
305
+ fs.unlinkSync(filePath); // Delete each file if it exists
306
+ console.log(`${file} was deleted successfully.`);
307
+ } else {
308
+ console.log(`${file} does not exist.`);
309
+ }
310
+ });
311
+ updateUninstallNpmDependencies.push(
312
+ "swagger-jsdoc",
313
+ "@types/swagger-jsdoc",
314
+ "prompts",
315
+ "@types/prompts"
316
+ );
317
+ }
318
+ if (!updateAnswer.tailwindcss) {
319
+ const tailwindFiles = ["postcss.config.js"];
320
+ tailwindFiles.forEach((file) => {
321
+ const filePath = path.join(projectPath, file);
322
+ if (fs.existsSync(filePath)) {
323
+ fs.unlinkSync(filePath); // Delete each file if it exists
324
+ console.log(`${file} was deleted successfully.`);
325
+ } else {
326
+ console.log(`${file} does not exist.`);
327
+ }
328
+ });
329
+ updateUninstallNpmDependencies.push(
330
+ "tailwindcss",
331
+ "postcss",
332
+ "postcss-cli",
333
+ "@tailwindcss/postcss",
334
+ "cssnano"
335
+ );
336
+ }
337
+ if (!updateAnswer.websocket) {
338
+ const websocketFiles = [
339
+ "restart-websocket.ts",
340
+ "restart-websocket.bat",
189
341
  ];
190
- if (answer.swaggerDocs) {
191
- npmDependencies.push(npmPkg("swagger-jsdoc"), npmPkg("@types/swagger-jsdoc"));
192
- }
193
- if (answer.swaggerDocs && answer.prisma) {
194
- npmDependencies.push(npmPkg("prompts"), npmPkg("@types/prompts"));
195
- }
196
- if (answer.tailwindcss) {
197
- npmDependencies.push(npmPkg("tailwindcss"), npmPkg("postcss"), npmPkg("postcss-cli"), npmPkg("@tailwindcss/postcss"), npmPkg("cssnano"));
198
- }
199
- if (answer.websocket) {
200
- npmDependencies.push(npmPkg("chokidar-cli"));
201
- composerDependencies.push("cboden/ratchet");
202
- }
203
- if (answer.prisma) {
204
- execSync("npm install -g prisma-client-php", { stdio: "inherit" });
205
- }
206
- await installNpmDependencies(projectPath, npmDependencies, true);
207
- await installComposerDependencies(projectPath, composerDependencies);
208
- if (!projectName) {
209
- execSync("npx tsc --init", { stdio: "inherit" });
210
- }
211
- await createDirectoryStructure(projectPath, answer);
212
- if (answer.prisma) {
213
- execSync("npx ppo init --prisma-php", { stdio: "inherit" });
214
- }
215
- if (answer.swaggerDocs) {
216
- const swaggerDocsPath = path.join(projectPath, "src", "app", "swagger-docs");
217
- // Check if the directory exists
218
- if (fs.existsSync(swaggerDocsPath)) {
219
- // If it exists and is not empty, remove it before cloning
220
- if (fs.readdirSync(swaggerDocsPath).length > 0) {
221
- console.log("Removing existing swagger-docs directory...");
222
- fs.rmSync(swaggerDocsPath, { recursive: true, force: true });
223
- }
224
- }
225
- // Clone the Git repository into the swagger-docs directory
226
- execSync(`git clone https://github.com/TheSteelNinjaCode/prisma-php-swagger-docs.git ${swaggerDocsPath}`, { stdio: "inherit" });
227
- // delete the folder .git
228
- fs.rmSync(path.join(swaggerDocsPath, ".git"), {
229
- recursive: true,
230
- force: true,
231
- });
232
- }
233
- if (updateAnswer?.isUpdate) {
234
- const updateUninstallNpmDependencies = [];
235
- const updateUninstallComposerDependencies = [];
236
- if (updateAnswer.backendOnly) {
237
- nonBackendFiles.forEach((file) => {
238
- const filePath = path.join(projectPath, "src", "app", file);
239
- if (fs.existsSync(filePath)) {
240
- fs.unlinkSync(filePath); // Delete each file if it exists
241
- console.log(`${file} was deleted successfully.`);
242
- }
243
- else {
244
- console.log(`${file} does not exist.`);
245
- }
246
- });
247
- const backendOnlyFolders = ["js", "css"];
248
- backendOnlyFolders.forEach((folder) => {
249
- const folderPath = path.join(projectPath, "src", "app", folder);
250
- if (fs.existsSync(folderPath)) {
251
- fs.rmSync(folderPath, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
252
- console.log(`${folder} was deleted successfully.`);
253
- }
254
- else {
255
- console.log(`${folder} does not exist.`);
256
- }
257
- });
258
- }
259
- if (!updateAnswer.swaggerDocs) {
260
- const swaggerDocsFolder = path.join(projectPath, "src", "app", "swagger-docs");
261
- if (fs.existsSync(swaggerDocsFolder)) {
262
- fs.rmSync(swaggerDocsFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
263
- console.log(`swagger-docs was deleted successfully.`);
264
- }
265
- const swaggerFiles = ["swagger-config.ts"];
266
- swaggerFiles.forEach((file) => {
267
- const filePath = path.join(projectPath, "settings", file);
268
- if (fs.existsSync(filePath)) {
269
- fs.unlinkSync(filePath); // Delete each file if it exists
270
- console.log(`${file} was deleted successfully.`);
271
- }
272
- else {
273
- console.log(`${file} does not exist.`);
274
- }
275
- });
276
- updateUninstallNpmDependencies.push("swagger-jsdoc", "@types/swagger-jsdoc", "prompts", "@types/prompts");
277
- }
278
- if (!updateAnswer.tailwindcss) {
279
- const tailwindFiles = ["postcss.config.js"];
280
- tailwindFiles.forEach((file) => {
281
- const filePath = path.join(projectPath, file);
282
- if (fs.existsSync(filePath)) {
283
- fs.unlinkSync(filePath); // Delete each file if it exists
284
- console.log(`${file} was deleted successfully.`);
285
- }
286
- else {
287
- console.log(`${file} does not exist.`);
288
- }
289
- });
290
- updateUninstallNpmDependencies.push("tailwindcss", "postcss", "postcss-cli", "@tailwindcss/postcss", "cssnano");
291
- }
292
- if (!updateAnswer.websocket) {
293
- const websocketFiles = [
294
- "restart-websocket.ts",
295
- "restart-websocket.bat",
296
- ];
297
- websocketFiles.forEach((file) => {
298
- const filePath = path.join(projectPath, "settings", file);
299
- if (fs.existsSync(filePath)) {
300
- fs.unlinkSync(filePath); // Delete each file if it exists
301
- console.log(`${file} was deleted successfully.`);
302
- }
303
- else {
304
- console.log(`${file} does not exist.`);
305
- }
306
- });
307
- const websocketFolder = path.join(projectPath, "src", "Websocket");
308
- if (fs.existsSync(websocketFolder)) {
309
- fs.rmSync(websocketFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
310
- console.log(`Websocket folder was deleted successfully.`);
311
- }
312
- const websocketServerFile = path.join(projectPath, "websocket-server.php");
313
- if (fs.existsSync(websocketServerFile)) {
314
- fs.unlinkSync(websocketServerFile); // Delete the file if it exists
315
- console.log(`websocket-server.php was deleted successfully.`);
316
- }
317
- updateUninstallNpmDependencies.push("chokidar-cli");
318
- updateUninstallComposerDependencies.push("cboden/ratchet");
319
- }
320
- if (!updateAnswer.prisma) {
321
- updateUninstallNpmDependencies.push("prisma", "@prisma/client", "@prisma/internals");
322
- }
323
- if (!updateAnswer.docker) {
324
- const dockerFiles = [
325
- ".dockerignore",
326
- "docker-compose.yml",
327
- "Dockerfile",
328
- "apache.conf",
329
- ];
330
- dockerFiles.forEach((file) => {
331
- const filePath = path.join(projectPath, file);
332
- if (fs.existsSync(filePath)) {
333
- fs.unlinkSync(filePath); // Delete each file if it exists
334
- console.log(`${file} was deleted successfully.`);
335
- }
336
- else {
337
- console.log(`${file} does not exist.`);
338
- }
339
- });
340
- }
341
- if (updateUninstallNpmDependencies.length > 0) {
342
- await uninstallNpmDependencies(projectPath, updateUninstallNpmDependencies, true);
343
- }
344
- if (updateUninstallComposerDependencies.length > 0) {
345
- await uninstallComposerDependencies(projectPath, updateUninstallComposerDependencies);
346
- }
342
+ websocketFiles.forEach((file) => {
343
+ const filePath = path.join(projectPath, "settings", file);
344
+ if (fs.existsSync(filePath)) {
345
+ fs.unlinkSync(filePath); // Delete each file if it exists
346
+ console.log(`${file} was deleted successfully.`);
347
+ } else {
348
+ console.log(`${file} does not exist.`);
349
+ }
350
+ });
351
+ const websocketFolder = path.join(
352
+ projectPath,
353
+ "src",
354
+ "Lib",
355
+ "Websocket"
356
+ );
357
+ if (fs.existsSync(websocketFolder)) {
358
+ fs.rmSync(websocketFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
359
+ console.log(`Websocket folder was deleted successfully.`);
347
360
  }
348
- const projectPathModified = projectPath.replace(/\\/g, "\\");
349
- const bsConfig = bsConfigUrls(projectPathModified);
350
- const prismaPhpConfig = {
351
- projectName: answer.projectName,
352
- projectRootPath: projectPathModified,
353
- phpEnvironment: "XAMPP",
354
- phpRootPathExe: "C:\\xampp\\php\\php.exe",
355
- bsTarget: bsConfig.bsTarget,
356
- bsPathRewrite: bsConfig.bsPathRewrite,
357
- backendOnly: answer.backendOnly,
358
- swaggerDocs: answer.swaggerDocs,
359
- tailwindcss: answer.tailwindcss,
360
- websocket: answer.websocket,
361
- prisma: answer.prisma,
362
- docker: answer.docker,
363
- version: latestVersionOfCreatePrismaPhpApp,
364
- excludeFiles: updateAnswer?.excludeFiles ?? [],
365
- };
366
- fs.writeFileSync(path.join(projectPath, "prisma-php.json"), JSON.stringify(prismaPhpConfig, null, 2), { flag: "w" });
367
- if (updateAnswer?.isUpdate) {
368
- execSync("C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update", {
369
- stdio: "inherit",
370
- });
361
+ updateUninstallNpmDependencies.push("chokidar-cli");
362
+ updateUninstallComposerDependencies.push("cboden/ratchet");
363
+ }
364
+ if (!updateAnswer.prisma) {
365
+ updateUninstallNpmDependencies.push(
366
+ "prisma",
367
+ "@prisma/client",
368
+ "@prisma/internals"
369
+ );
370
+ }
371
+ if (!updateAnswer.docker) {
372
+ const dockerFiles = [
373
+ ".dockerignore",
374
+ "docker-compose.yml",
375
+ "Dockerfile",
376
+ "apache.conf",
377
+ ];
378
+ dockerFiles.forEach((file) => {
379
+ const filePath = path.join(projectPath, file);
380
+ if (fs.existsSync(filePath)) {
381
+ fs.unlinkSync(filePath); // Delete each file if it exists
382
+ console.log(`${file} was deleted successfully.`);
383
+ } else {
384
+ console.log(`${file} does not exist.`);
385
+ }
386
+ });
387
+ }
388
+ if (updateUninstallNpmDependencies.length > 0) {
389
+ await uninstallNpmDependencies(
390
+ projectPath,
391
+ updateUninstallNpmDependencies,
392
+ true
393
+ );
394
+ }
395
+ if (updateUninstallComposerDependencies.length > 0) {
396
+ await uninstallComposerDependencies(
397
+ projectPath,
398
+ updateUninstallComposerDependencies
399
+ );
400
+ }
401
+ }
402
+ const projectPathModified = projectPath.replace(/\\/g, "\\");
403
+ const bsConfig = bsConfigUrls(projectPathModified);
404
+ const prismaPhpConfig = {
405
+ projectName: answer.projectName,
406
+ projectRootPath: projectPathModified,
407
+ phpEnvironment: "XAMPP",
408
+ phpRootPathExe: "C:\\xampp\\php\\php.exe",
409
+ phpGenerateClassPath: "src/Lib/Prisma/Classes",
410
+ bsTarget: bsConfig.bsTarget,
411
+ bsPathRewrite: bsConfig.bsPathRewrite,
412
+ backendOnly: answer.backendOnly,
413
+ swaggerDocs: answer.swaggerDocs,
414
+ tailwindcss: answer.tailwindcss,
415
+ websocket: answer.websocket,
416
+ prisma: answer.prisma,
417
+ docker: answer.docker,
418
+ version: latestVersionOfCreatePrismaPhpApp,
419
+ excludeFiles: updateAnswer?.excludeFiles ?? [],
420
+ };
421
+ fs.writeFileSync(
422
+ path.join(projectPath, "prisma-php.json"),
423
+ JSON.stringify(prismaPhpConfig, null, 2),
424
+ { flag: "w" }
425
+ );
426
+ if (updateAnswer?.isUpdate) {
427
+ execSync(
428
+ "C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update",
429
+ {
430
+ stdio: "inherit",
371
431
  }
372
- else {
373
- execSync("C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install", {
374
- stdio: "inherit",
375
- });
432
+ );
433
+ } else {
434
+ execSync(
435
+ "C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install",
436
+ {
437
+ stdio: "inherit",
376
438
  }
377
- console.log("\n=========================\n");
378
- console.log(`${chalk.green("Success!")} Prisma PHP project successfully created in ${chalk.green(`${currentDir.replace(/\\/g, "/")}/${answer.projectName}`)}!`);
379
- console.log("\n=========================");
380
- }
381
- catch (error) {
382
- console.error("Error while creating the project:", error);
383
- process.exit(1);
439
+ );
384
440
  }
441
+ console.log("\n=========================\n");
442
+ console.log(
443
+ `${chalk.green(
444
+ "Success!"
445
+ )} Prisma PHP project successfully created in ${chalk.green(
446
+ `${currentDir.replace(/\\/g, "/")}/${answer.projectName}`
447
+ )}!`
448
+ );
449
+ console.log("\n=========================");
450
+ } catch (error) {
451
+ console.error("Error while creating the project:", error);
452
+ process.exit(1);
453
+ }
385
454
  }
386
455
  main();