create-prisma-php-app 3.1.20 → 4.0.0-alpha.10

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\\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}}
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||updateAnswer?.isUpdate||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??!1?(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,455 +7,378 @@ 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,
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,
16
27
  });
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
- });
34
28
  }
35
29
  async function installComposerDependencies(baseDir, dependencies) {
36
- console.log(
37
- chalk.green(
38
- `Composer project initialization: ${
39
- updateAnswer?.isUpdate
40
- ? "Updating existing project..."
41
- : "Setting up new project..."
42
- }`
43
- )
44
- );
45
- // Initialize a composer.json if it doesn't exist
46
- if (!fs.existsSync(path.join(baseDir, "composer.json"))) {
47
- execSync(
48
- `composer init -n \
30
+ console.log(chalk.green(`Composer project initialization: ${updateAnswer?.isUpdate
31
+ ? "Updating existing project..."
32
+ : "Setting up new project..."}`));
33
+ // Initialize a composer.json if it doesn't exist
34
+ if (!fs.existsSync(path.join(baseDir, "composer.json"))) {
35
+ execSync(`composer init -n \
49
36
  --name="tsnc/prisma-php-app" \
50
37
  --require="php:^8.2" \
51
- --version="1.0.0"`,
52
- { stdio: "inherit", cwd: baseDir }
53
- );
54
- }
55
- // Log the dependencies being installed
56
- console.log("Installing Composer dependencies:");
57
- dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
58
- // Prepare the composer require command
59
- const composerRequireCommand = `C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar require ${dependencies.join(
60
- " "
61
- )}`;
62
- // Execute the composer require command
63
- execSync(composerRequireCommand, {
64
- stdio: "inherit",
65
- cwd: baseDir,
66
- });
38
+ --version="1.0.0"`, { stdio: "inherit", cwd: baseDir });
39
+ }
40
+ // Log the dependencies being installed
41
+ console.log("Installing Composer dependencies:");
42
+ dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
43
+ // Prepare the composer require command
44
+ const composerRequireCommand = `C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar require ${dependencies.join(" ")}`;
45
+ // Execute the composer require command
46
+ execSync(composerRequireCommand, {
47
+ stdio: "inherit",
48
+ cwd: baseDir,
49
+ });
67
50
  }
68
51
  const npmPinnedVersions = {
69
- "@tailwindcss/postcss": "^4.1.11",
70
- "@types/browser-sync": "^2.29.0",
71
- "@types/node": "^24.0.7",
72
- "@types/prompts": "^2.4.9",
73
- "browser-sync": "^3.0.4",
74
- chalk: "^5.4.1",
75
- "chokidar-cli": "^3.0.0",
76
- cssnano: "^7.0.7",
77
- "http-proxy-middleware": "^3.0.5",
78
- "npm-run-all": "^4.1.5",
79
- "php-parser": "^3.2.4",
80
- postcss: "^8.5.6",
81
- "postcss-cli": "^11.0.1",
82
- prompts: "^2.4.2",
83
- tailwindcss: "^4.1.11",
84
- tsx: "^4.20.3",
85
- typescript: "^5.8.3",
52
+ "@tailwindcss/postcss": "^4.1.11",
53
+ "@types/browser-sync": "^2.29.0",
54
+ "@types/node": "^24.0.13",
55
+ "@types/prompts": "^2.4.9",
56
+ "browser-sync": "^3.0.4",
57
+ chalk: "^5.4.1",
58
+ "chokidar-cli": "^3.0.0",
59
+ cssnano: "^7.0.7",
60
+ "http-proxy-middleware": "^3.0.5",
61
+ "npm-run-all": "^4.1.5",
62
+ "php-parser": "^3.2.5",
63
+ postcss: "^8.5.6",
64
+ "postcss-cli": "^11.0.1",
65
+ prompts: "^2.4.2",
66
+ tailwindcss: "^4.1.11",
67
+ tsx: "^4.20.3",
68
+ typescript: "^5.8.3",
86
69
  };
87
70
  function npmPkg(name) {
88
- return npmPinnedVersions[name] ? `${name}@${npmPinnedVersions[name]}` : name;
71
+ return npmPinnedVersions[name] ? `${name}@${npmPinnedVersions[name]}` : name;
89
72
  }
90
73
  const composerPinnedVersions = {
91
- "vlucas/phpdotenv": "^5.6.2",
92
- "firebase/php-jwt": "^6.11.1",
93
- "phpmailer/phpmailer": "^6.10.0",
94
- "guzzlehttp/guzzle": "^7.9.3",
95
- "ezyang/htmlpurifier": "^4.18.0",
96
- "symfony/uid": "^7.2.0",
97
- "brick/math": "^0.13.1",
98
- "cboden/ratchet": "^0.4.4",
74
+ "vlucas/phpdotenv": "^5.6.2",
75
+ "firebase/php-jwt": "^6.11.1",
76
+ "phpmailer/phpmailer": "^6.10.0",
77
+ "guzzlehttp/guzzle": "^7.9.3",
78
+ "ezyang/htmlpurifier": "^4.18.0",
79
+ "symfony/uid": "^7.2.0",
80
+ "brick/math": "^0.13.1",
81
+ "cboden/ratchet": "^0.4.4",
82
+ "tsnc/prisma-php": "^1.0.0",
99
83
  };
100
84
  function composerPkg(name) {
101
- return composerPinnedVersions[name]
102
- ? `${name}:${composerPinnedVersions[name]}`
103
- : name;
85
+ return composerPinnedVersions[name]
86
+ ? `${name}:${composerPinnedVersions[name]}`
87
+ : name;
104
88
  }
105
89
  async function main() {
106
- try {
107
- const args = process.argv.slice(2);
108
- let projectName = args[0];
109
- let answer = null;
110
- if (projectName) {
111
- let useBackendOnly = args.includes("--backend-only");
112
- let useSwaggerDocs = args.includes("--swagger-docs");
113
- let useTailwind = args.includes("--tailwindcss");
114
- let useWebsocket = args.includes("--websocket");
115
- let usePrisma = args.includes("--prisma");
116
- let useDocker = args.includes("--docker");
117
- const predefinedAnswers = {
118
- projectName,
119
- backendOnly: useBackendOnly,
120
- swaggerDocs: useSwaggerDocs,
121
- tailwindcss: useTailwind,
122
- websocket: useWebsocket,
123
- prisma: usePrisma,
124
- docker: useDocker,
125
- };
126
- answer = await getAnswer(predefinedAnswers);
127
- if (answer === null) {
128
- console.log(chalk.red("Installation cancelled."));
129
- return;
130
- }
131
- const currentDir = process.cwd();
132
- const configPath = path.join(currentDir, "prisma-php.json");
133
- if (fs.existsSync(configPath)) {
134
- const localSettings = readJsonFile(configPath);
135
- let excludeFiles = [];
136
- localSettings.excludeFiles?.map((file) => {
137
- const filePath = path.join(currentDir, file);
138
- if (fs.existsSync(filePath))
139
- excludeFiles.push(filePath.replace(/\\/g, "/"));
140
- });
141
- updateAnswer = {
142
- projectName,
143
- backendOnly: answer?.backendOnly ?? false,
144
- swaggerDocs: answer?.swaggerDocs ?? false,
145
- tailwindcss: answer?.tailwindcss ?? false,
146
- websocket: answer?.websocket ?? false,
147
- prisma: answer?.prisma ?? false,
148
- docker: answer?.docker ?? false,
149
- isUpdate: true,
150
- excludeFiles: localSettings.excludeFiles ?? [],
151
- excludeFilePath: excludeFiles ?? [],
152
- filePath: currentDir,
153
- };
154
- }
155
- } else {
156
- answer = await getAnswer();
157
- }
158
- if (answer === null) {
159
- console.warn(chalk.red("Installation cancelled."));
160
- return;
161
- }
162
- const latestVersionOfCreatePrismaPhpApp = await fetchPackageVersion(
163
- "create-prisma-php-app"
164
- );
165
- const isCreatePrismaPhpAppInstalled = getInstalledPackageVersion(
166
- "create-prisma-php-app"
167
- );
168
- if (isCreatePrismaPhpAppInstalled) {
169
- if (
170
- compareVersions(
171
- isCreatePrismaPhpAppInstalled,
172
- latestVersionOfCreatePrismaPhpApp
173
- ) === -1
174
- ) {
175
- execSync("npm uninstall -g create-prisma-php-app", {
176
- stdio: "inherit",
177
- });
178
- execSync("npm install -g create-prisma-php-app", {
179
- stdio: "inherit",
180
- });
181
- }
182
- } else {
183
- execSync("npm install -g create-prisma-php-app", { stdio: "inherit" });
184
- }
185
- // Create the project directory
186
- if (!projectName) fs.mkdirSync(answer.projectName);
187
- const currentDir = process.cwd();
188
- let projectPath = projectName
189
- ? currentDir
190
- : path.join(currentDir, answer.projectName);
191
- if (!projectName) process.chdir(answer.projectName);
192
- let npmDependencies = [
193
- npmPkg("typescript"),
194
- npmPkg("@types/node"),
195
- npmPkg("tsx"),
196
- npmPkg("http-proxy-middleware"),
197
- npmPkg("chalk"),
198
- npmPkg("npm-run-all"),
199
- npmPkg("browser-sync"),
200
- npmPkg("@types/browser-sync"),
201
- npmPkg("php-parser"),
202
- ];
203
- let composerDependencies = [
204
- composerPkg("vlucas/phpdotenv"),
205
- composerPkg("firebase/php-jwt"),
206
- composerPkg("phpmailer/phpmailer"),
207
- composerPkg("guzzlehttp/guzzle"),
208
- composerPkg("ezyang/htmlpurifier"),
209
- composerPkg("symfony/uid"),
210
- composerPkg("brick/math"),
211
- ];
212
- if (answer.swaggerDocs) {
213
- npmDependencies.push(
214
- npmPkg("swagger-jsdoc"),
215
- npmPkg("@types/swagger-jsdoc")
216
- );
217
- }
218
- if (answer.swaggerDocs && answer.prisma) {
219
- npmDependencies.push(npmPkg("prompts"), npmPkg("@types/prompts"));
220
- }
221
- if (answer.tailwindcss) {
222
- npmDependencies.push(
223
- npmPkg("tailwindcss"),
224
- npmPkg("postcss"),
225
- npmPkg("postcss-cli"),
226
- npmPkg("@tailwindcss/postcss"),
227
- npmPkg("cssnano")
228
- );
229
- }
230
- if (answer.websocket) {
231
- npmDependencies.push(npmPkg("chokidar-cli"));
232
- composerDependencies.push("cboden/ratchet");
233
- }
234
- if (answer.prisma) {
235
- execSync("npm install -g prisma-client-php", { stdio: "inherit" });
236
- }
237
- await installNpmDependencies(projectPath, npmDependencies, true);
238
- await installComposerDependencies(projectPath, composerDependencies);
239
- if (!projectName) {
240
- execSync("npx tsc --init", { stdio: "inherit" });
241
- }
242
- await createDirectoryStructure(projectPath, answer);
243
- if (answer.prisma) {
244
- execSync("npx ppo init --prisma-php", { stdio: "inherit" });
245
- }
246
- if (answer.swaggerDocs) {
247
- const swaggerDocsPath = path.join(
248
- projectPath,
249
- "src",
250
- "app",
251
- "swagger-docs"
252
- );
253
- // Check if the directory exists
254
- if (fs.existsSync(swaggerDocsPath)) {
255
- // If it exists and is not empty, remove it before cloning
256
- if (fs.readdirSync(swaggerDocsPath).length > 0) {
257
- console.log("Removing existing swagger-docs directory...");
258
- fs.rmSync(swaggerDocsPath, { recursive: true, force: true });
90
+ try {
91
+ const args = process.argv.slice(2);
92
+ let projectName = args[0];
93
+ let answer = null;
94
+ if (projectName) {
95
+ let useBackendOnly = args.includes("--backend-only");
96
+ let useSwaggerDocs = args.includes("--swagger-docs");
97
+ let useTailwind = args.includes("--tailwindcss");
98
+ let useWebsocket = args.includes("--websocket");
99
+ let usePrisma = args.includes("--prisma");
100
+ let useDocker = args.includes("--docker");
101
+ const predefinedAnswers = {
102
+ projectName,
103
+ backendOnly: useBackendOnly,
104
+ swaggerDocs: useSwaggerDocs,
105
+ tailwindcss: useTailwind,
106
+ websocket: useWebsocket,
107
+ prisma: usePrisma,
108
+ docker: useDocker,
109
+ };
110
+ answer = await getAnswer(predefinedAnswers);
111
+ if (answer === null) {
112
+ console.log(chalk.red("Installation cancelled."));
113
+ return;
114
+ }
115
+ const currentDir = process.cwd();
116
+ const configPath = path.join(currentDir, "prisma-php.json");
117
+ if (fs.existsSync(configPath)) {
118
+ const localSettings = readJsonFile(configPath);
119
+ let excludeFiles = [];
120
+ localSettings.excludeFiles?.map((file) => {
121
+ const filePath = path.join(currentDir, file);
122
+ if (fs.existsSync(filePath))
123
+ excludeFiles.push(filePath.replace(/\\/g, "/"));
124
+ });
125
+ updateAnswer = {
126
+ projectName,
127
+ backendOnly: answer?.backendOnly ?? false,
128
+ swaggerDocs: answer?.swaggerDocs ?? false,
129
+ tailwindcss: answer?.tailwindcss ?? false,
130
+ websocket: answer?.websocket ?? false,
131
+ prisma: answer?.prisma ?? false,
132
+ docker: answer?.docker ?? false,
133
+ isUpdate: true,
134
+ excludeFiles: localSettings.excludeFiles ?? [],
135
+ excludeFilePath: excludeFiles ?? [],
136
+ filePath: currentDir,
137
+ };
138
+ }
259
139
  }
260
- }
261
- // Clone the Git repository into the swagger-docs directory
262
- execSync(
263
- `git clone https://github.com/TheSteelNinjaCode/prisma-php-swagger-docs.git ${swaggerDocsPath}`,
264
- { stdio: "inherit" }
265
- );
266
- // delete the folder .git
267
- fs.rmSync(path.join(swaggerDocsPath, ".git"), {
268
- recursive: true,
269
- force: true,
270
- });
271
- }
272
- if (updateAnswer?.isUpdate) {
273
- const updateUninstallNpmDependencies = [];
274
- const updateUninstallComposerDependencies = [];
275
- if (updateAnswer.backendOnly) {
276
- nonBackendFiles.forEach((file) => {
277
- const filePath = path.join(projectPath, "src", "app", file);
278
- if (fs.existsSync(filePath)) {
279
- fs.unlinkSync(filePath); // Delete each file if it exists
280
- console.log(`${file} was deleted successfully.`);
281
- } else {
282
- console.log(`${file} does not exist.`);
283
- }
284
- });
285
- const backendOnlyFolders = ["js", "css"];
286
- backendOnlyFolders.forEach((folder) => {
287
- const folderPath = path.join(projectPath, "src", "app", folder);
288
- if (fs.existsSync(folderPath)) {
289
- fs.rmSync(folderPath, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
290
- console.log(`${folder} was deleted successfully.`);
291
- } else {
292
- console.log(`${folder} does not exist.`);
293
- }
294
- });
295
- }
296
- if (!updateAnswer.swaggerDocs) {
297
- const swaggerDocsFolder = path.join(
298
- projectPath,
299
- "src",
300
- "app",
301
- "swagger-docs"
302
- );
303
- if (fs.existsSync(swaggerDocsFolder)) {
304
- fs.rmSync(swaggerDocsFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
305
- console.log(`swagger-docs was deleted successfully.`);
140
+ else {
141
+ answer = await getAnswer();
306
142
  }
307
- const swaggerFiles = ["swagger-config.ts"];
308
- swaggerFiles.forEach((file) => {
309
- const filePath = path.join(projectPath, "settings", file);
310
- if (fs.existsSync(filePath)) {
311
- fs.unlinkSync(filePath); // Delete each file if it exists
312
- console.log(`${file} was deleted successfully.`);
313
- } else {
314
- console.log(`${file} does not exist.`);
315
- }
316
- });
317
- updateUninstallNpmDependencies.push(
318
- "swagger-jsdoc",
319
- "@types/swagger-jsdoc",
320
- "prompts",
321
- "@types/prompts"
322
- );
323
- }
324
- if (!updateAnswer.tailwindcss) {
325
- const tailwindFiles = ["postcss.config.js"];
326
- tailwindFiles.forEach((file) => {
327
- const filePath = path.join(projectPath, file);
328
- if (fs.existsSync(filePath)) {
329
- fs.unlinkSync(filePath); // Delete each file if it exists
330
- console.log(`${file} was deleted successfully.`);
331
- } else {
332
- console.log(`${file} does not exist.`);
333
- }
334
- });
335
- updateUninstallNpmDependencies.push(
336
- "tailwindcss",
337
- "postcss",
338
- "postcss-cli",
339
- "@tailwindcss/postcss",
340
- "cssnano"
341
- );
342
- }
343
- if (!updateAnswer.websocket) {
344
- const websocketFiles = [
345
- "restart-websocket.ts",
346
- "restart-websocket.bat",
347
- ];
348
- websocketFiles.forEach((file) => {
349
- const filePath = path.join(projectPath, "settings", file);
350
- if (fs.existsSync(filePath)) {
351
- fs.unlinkSync(filePath); // Delete each file if it exists
352
- console.log(`${file} was deleted successfully.`);
353
- } else {
354
- console.log(`${file} does not exist.`);
355
- }
356
- });
357
- const websocketFolder = path.join(
358
- projectPath,
359
- "src",
360
- "Lib",
361
- "Websocket"
362
- );
363
- if (fs.existsSync(websocketFolder)) {
364
- fs.rmSync(websocketFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
365
- console.log(`Websocket folder was deleted successfully.`);
143
+ if (answer === null) {
144
+ console.warn(chalk.red("Installation cancelled."));
145
+ return;
146
+ }
147
+ const latestVersionOfCreatePrismaPhpApp = await fetchPackageVersion("create-prisma-php-app");
148
+ const isCreatePrismaPhpAppInstalled = getInstalledPackageVersion("create-prisma-php-app");
149
+ if (isCreatePrismaPhpAppInstalled) {
150
+ if (compareVersions(isCreatePrismaPhpAppInstalled, latestVersionOfCreatePrismaPhpApp) === -1) {
151
+ execSync("npm uninstall -g create-prisma-php-app", {
152
+ stdio: "inherit",
153
+ });
154
+ execSync("npm install -g create-prisma-php-app", {
155
+ stdio: "inherit",
156
+ });
157
+ }
366
158
  }
367
- updateUninstallNpmDependencies.push("chokidar-cli");
368
- updateUninstallComposerDependencies.push("cboden/ratchet");
369
- }
370
- if (!updateAnswer.prisma) {
371
- updateUninstallNpmDependencies.push(
372
- "prisma",
373
- "@prisma/client",
374
- "@prisma/internals"
375
- );
376
- }
377
- if (!updateAnswer.docker) {
378
- const dockerFiles = [
379
- ".dockerignore",
380
- "docker-compose.yml",
381
- "Dockerfile",
382
- "apache.conf",
159
+ else {
160
+ execSync("npm install -g create-prisma-php-app", { stdio: "inherit" });
161
+ }
162
+ // Create the project directory
163
+ if (!projectName)
164
+ fs.mkdirSync(answer.projectName);
165
+ const currentDir = process.cwd();
166
+ let projectPath = projectName
167
+ ? currentDir
168
+ : path.join(currentDir, answer.projectName);
169
+ if (!projectName)
170
+ process.chdir(answer.projectName);
171
+ let npmDependencies = [
172
+ npmPkg("typescript"),
173
+ npmPkg("@types/node"),
174
+ npmPkg("tsx"),
175
+ npmPkg("http-proxy-middleware"),
176
+ npmPkg("chalk"),
177
+ npmPkg("npm-run-all"),
178
+ npmPkg("browser-sync"),
179
+ npmPkg("@types/browser-sync"),
180
+ npmPkg("php-parser"),
383
181
  ];
384
- dockerFiles.forEach((file) => {
385
- const filePath = path.join(projectPath, file);
386
- if (fs.existsSync(filePath)) {
387
- fs.unlinkSync(filePath); // Delete each file if it exists
388
- console.log(`${file} was deleted successfully.`);
389
- } else {
390
- console.log(`${file} does not exist.`);
391
- }
392
- });
393
- }
394
- if (updateUninstallNpmDependencies.length > 0) {
395
- await uninstallNpmDependencies(
396
- projectPath,
397
- updateUninstallNpmDependencies,
398
- true
399
- );
400
- }
401
- if (updateUninstallComposerDependencies.length > 0) {
402
- await uninstallComposerDependencies(
403
- projectPath,
404
- updateUninstallComposerDependencies
405
- );
406
- }
407
- }
408
- const projectPathModified = projectPath.replace(/\\/g, "\\");
409
- const bsConfig = bsConfigUrls(projectPathModified);
410
- const prismaPhpConfig = {
411
- projectName: answer.projectName,
412
- projectRootPath: projectPathModified,
413
- phpEnvironment: "XAMPP",
414
- phpRootPathExe: "C:\\xampp\\php\\php.exe",
415
- phpGenerateClassPath: "src/Lib/Prisma/Classes",
416
- bsTarget: bsConfig.bsTarget,
417
- bsPathRewrite: bsConfig.bsPathRewrite,
418
- backendOnly: answer.backendOnly,
419
- swaggerDocs: answer.swaggerDocs,
420
- tailwindcss: answer.tailwindcss,
421
- websocket: answer.websocket,
422
- prisma: answer.prisma,
423
- docker: answer.docker,
424
- version: latestVersionOfCreatePrismaPhpApp,
425
- excludeFiles: updateAnswer?.excludeFiles ?? [],
426
- };
427
- fs.writeFileSync(
428
- path.join(projectPath, "prisma-php.json"),
429
- JSON.stringify(prismaPhpConfig, null, 2),
430
- { flag: "w" }
431
- );
432
- if (updateAnswer?.isUpdate) {
433
- execSync(
434
- "C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update",
435
- {
436
- stdio: "inherit",
182
+ let composerDependencies = [
183
+ composerPkg("vlucas/phpdotenv"),
184
+ composerPkg("firebase/php-jwt"),
185
+ composerPkg("phpmailer/phpmailer"),
186
+ composerPkg("guzzlehttp/guzzle"),
187
+ composerPkg("ezyang/htmlpurifier"),
188
+ composerPkg("symfony/uid"),
189
+ composerPkg("brick/math"),
190
+ composerPkg("tsnc/prisma-php"),
191
+ ];
192
+ if (answer.swaggerDocs) {
193
+ npmDependencies.push(npmPkg("swagger-jsdoc"), npmPkg("@types/swagger-jsdoc"));
194
+ }
195
+ if (answer.swaggerDocs && answer.prisma) {
196
+ npmDependencies.push(npmPkg("prompts"), npmPkg("@types/prompts"));
437
197
  }
438
- );
439
- } else {
440
- execSync(
441
- "C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install",
442
- {
443
- stdio: "inherit",
198
+ if (answer.tailwindcss) {
199
+ npmDependencies.push(npmPkg("tailwindcss"), npmPkg("postcss"), npmPkg("postcss-cli"), npmPkg("@tailwindcss/postcss"), npmPkg("cssnano"));
444
200
  }
445
- );
201
+ if (answer.websocket) {
202
+ npmDependencies.push(npmPkg("chokidar-cli"));
203
+ composerDependencies.push("cboden/ratchet");
204
+ }
205
+ if (answer.prisma) {
206
+ execSync("npm install -g prisma-client-php", { stdio: "inherit" });
207
+ }
208
+ await installNpmDependencies(projectPath, npmDependencies, true);
209
+ await installComposerDependencies(projectPath, composerDependencies);
210
+ if (!projectName) {
211
+ execSync("npx tsc --init", { stdio: "inherit" });
212
+ }
213
+ await createDirectoryStructure(projectPath, answer);
214
+ if (answer.prisma) {
215
+ execSync("npx ppo init --prisma-php", { stdio: "inherit" });
216
+ }
217
+ if (answer.swaggerDocs) {
218
+ const swaggerDocsPath = path.join(projectPath, "src", "app", "swagger-docs");
219
+ // Check if the directory exists
220
+ if (fs.existsSync(swaggerDocsPath)) {
221
+ // If it exists and is not empty, remove it before cloning
222
+ if (fs.readdirSync(swaggerDocsPath).length > 0) {
223
+ console.log("Removing existing swagger-docs directory...");
224
+ fs.rmSync(swaggerDocsPath, { recursive: true, force: true });
225
+ }
226
+ }
227
+ // Clone the Git repository into the swagger-docs directory
228
+ execSync(`git clone https://github.com/TheSteelNinjaCode/prisma-php-swagger-docs.git ${swaggerDocsPath}`, { stdio: "inherit" });
229
+ // delete the folder .git
230
+ fs.rmSync(path.join(swaggerDocsPath, ".git"), {
231
+ recursive: true,
232
+ force: true,
233
+ });
234
+ }
235
+ if (updateAnswer?.isUpdate) {
236
+ const updateUninstallNpmDependencies = [];
237
+ const updateUninstallComposerDependencies = [];
238
+ if (updateAnswer.backendOnly) {
239
+ nonBackendFiles.forEach((file) => {
240
+ const filePath = path.join(projectPath, "src", "app", file);
241
+ if (fs.existsSync(filePath)) {
242
+ fs.unlinkSync(filePath); // Delete each file if it exists
243
+ console.log(`${file} was deleted successfully.`);
244
+ }
245
+ else {
246
+ console.log(`${file} does not exist.`);
247
+ }
248
+ });
249
+ const backendOnlyFolders = ["js", "css"];
250
+ backendOnlyFolders.forEach((folder) => {
251
+ const folderPath = path.join(projectPath, "src", "app", folder);
252
+ if (fs.existsSync(folderPath)) {
253
+ fs.rmSync(folderPath, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
254
+ console.log(`${folder} was deleted successfully.`);
255
+ }
256
+ else {
257
+ console.log(`${folder} does not exist.`);
258
+ }
259
+ });
260
+ }
261
+ if (!updateAnswer.swaggerDocs) {
262
+ const swaggerDocsFolder = path.join(projectPath, "src", "app", "swagger-docs");
263
+ if (fs.existsSync(swaggerDocsFolder)) {
264
+ fs.rmSync(swaggerDocsFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
265
+ console.log(`swagger-docs was deleted successfully.`);
266
+ }
267
+ const swaggerFiles = ["swagger-config.ts"];
268
+ swaggerFiles.forEach((file) => {
269
+ const filePath = path.join(projectPath, "settings", file);
270
+ if (fs.existsSync(filePath)) {
271
+ fs.unlinkSync(filePath); // Delete each file if it exists
272
+ console.log(`${file} was deleted successfully.`);
273
+ }
274
+ else {
275
+ console.log(`${file} does not exist.`);
276
+ }
277
+ });
278
+ updateUninstallNpmDependencies.push("swagger-jsdoc", "@types/swagger-jsdoc", "prompts", "@types/prompts");
279
+ }
280
+ if (!updateAnswer.tailwindcss) {
281
+ const tailwindFiles = ["postcss.config.js"];
282
+ tailwindFiles.forEach((file) => {
283
+ const filePath = path.join(projectPath, file);
284
+ if (fs.existsSync(filePath)) {
285
+ fs.unlinkSync(filePath); // Delete each file if it exists
286
+ console.log(`${file} was deleted successfully.`);
287
+ }
288
+ else {
289
+ console.log(`${file} does not exist.`);
290
+ }
291
+ });
292
+ updateUninstallNpmDependencies.push("tailwindcss", "postcss", "postcss-cli", "@tailwindcss/postcss", "cssnano");
293
+ }
294
+ if (!updateAnswer.websocket) {
295
+ const websocketFiles = [
296
+ "restart-websocket.ts",
297
+ "restart-websocket.bat",
298
+ ];
299
+ websocketFiles.forEach((file) => {
300
+ const filePath = path.join(projectPath, "settings", file);
301
+ if (fs.existsSync(filePath)) {
302
+ fs.unlinkSync(filePath); // Delete each file if it exists
303
+ console.log(`${file} was deleted successfully.`);
304
+ }
305
+ else {
306
+ console.log(`${file} does not exist.`);
307
+ }
308
+ });
309
+ const websocketFolder = path.join(projectPath, "src", "Lib", "Websocket");
310
+ if (fs.existsSync(websocketFolder)) {
311
+ fs.rmSync(websocketFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
312
+ console.log(`Websocket folder was deleted successfully.`);
313
+ }
314
+ updateUninstallNpmDependencies.push("chokidar-cli");
315
+ updateUninstallComposerDependencies.push("cboden/ratchet");
316
+ }
317
+ if (!updateAnswer.prisma) {
318
+ updateUninstallNpmDependencies.push("prisma", "@prisma/client", "@prisma/internals");
319
+ }
320
+ if (!updateAnswer.docker) {
321
+ const dockerFiles = [
322
+ ".dockerignore",
323
+ "docker-compose.yml",
324
+ "Dockerfile",
325
+ "apache.conf",
326
+ ];
327
+ dockerFiles.forEach((file) => {
328
+ const filePath = path.join(projectPath, file);
329
+ if (fs.existsSync(filePath)) {
330
+ fs.unlinkSync(filePath); // Delete each file if it exists
331
+ console.log(`${file} was deleted successfully.`);
332
+ }
333
+ else {
334
+ console.log(`${file} does not exist.`);
335
+ }
336
+ });
337
+ }
338
+ if (updateUninstallNpmDependencies.length > 0) {
339
+ await uninstallNpmDependencies(projectPath, updateUninstallNpmDependencies, true);
340
+ }
341
+ if (updateUninstallComposerDependencies.length > 0) {
342
+ await uninstallComposerDependencies(projectPath, updateUninstallComposerDependencies);
343
+ }
344
+ }
345
+ const projectPathModified = projectPath.replace(/\\/g, "\\");
346
+ const bsConfig = bsConfigUrls(projectPathModified);
347
+ const prismaPhpConfig = {
348
+ projectName: answer.projectName,
349
+ projectRootPath: projectPathModified,
350
+ phpEnvironment: "XAMPP",
351
+ phpRootPathExe: "C:\\xampp\\php\\php.exe",
352
+ phpGenerateClassPath: "src/Lib/Prisma/Classes",
353
+ bsTarget: bsConfig.bsTarget,
354
+ bsPathRewrite: bsConfig.bsPathRewrite,
355
+ backendOnly: answer.backendOnly,
356
+ swaggerDocs: answer.swaggerDocs,
357
+ tailwindcss: answer.tailwindcss,
358
+ websocket: answer.websocket,
359
+ prisma: answer.prisma,
360
+ docker: answer.docker,
361
+ version: latestVersionOfCreatePrismaPhpApp,
362
+ excludeFiles: updateAnswer?.excludeFiles ?? [],
363
+ };
364
+ fs.writeFileSync(path.join(projectPath, "prisma-php.json"), JSON.stringify(prismaPhpConfig, null, 2), { flag: "w" });
365
+ if (updateAnswer?.isUpdate) {
366
+ execSync("C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update", {
367
+ stdio: "inherit",
368
+ });
369
+ }
370
+ else {
371
+ execSync("C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install", {
372
+ stdio: "inherit",
373
+ });
374
+ }
375
+ console.log("\n=========================\n");
376
+ console.log(`${chalk.green("Success!")} Prisma PHP project successfully created in ${chalk.green(`${currentDir.replace(/\\/g, "/")}/${answer.projectName}`)}!`);
377
+ console.log("\n=========================");
378
+ }
379
+ catch (error) {
380
+ console.error("Error while creating the project:", error);
381
+ process.exit(1);
446
382
  }
447
- console.log("\n=========================\n");
448
- console.log(
449
- `${chalk.green(
450
- "Success!"
451
- )} Prisma PHP project successfully created in ${chalk.green(
452
- `${currentDir.replace(/\\/g, "/")}/${answer.projectName}`
453
- )}!`
454
- );
455
- console.log("\n=========================");
456
- } catch (error) {
457
- console.error("Error while creating the project:", error);
458
- process.exit(1);
459
- }
460
383
  }
461
384
  main();