create-prisma-php-app 4.0.0-alpha.11 → 4.0.0-alpha.12

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