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

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