create-prisma-php-app 1.19.4 → 1.19.502

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.
@@ -0,0 +1,4 @@
1
+ {
2
+ "pieces.cloudCapabilities": "Blended",
3
+ "pieces.telemetry": true
4
+ }
@@ -4,8 +4,8 @@ if (session_status() == PHP_SESSION_NONE) {
4
4
  session_start();
5
5
  }
6
6
 
7
- require_once __DIR__ . '/settings/paths.php';
8
7
  require_once __DIR__ . '/vendor/autoload.php';
8
+ require_once __DIR__ . '/settings/paths.php';
9
9
 
10
10
  use Lib\Middleware\AuthMiddleware;
11
11
  use Dotenv\Dotenv;
@@ -13,6 +13,8 @@ use Dotenv\Dotenv;
13
13
  $dotenv = Dotenv::createImmutable(\DOCUMENT_PATH);
14
14
  $dotenv->load();
15
15
 
16
+ date_default_timezone_set($_ENV['APP_TIMEZONE'] ?? 'UTC');
17
+
16
18
  function determineContentToInclude()
17
19
  {
18
20
  $scriptUrl = $_SERVER['REQUEST_URI'];
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{execSync}from"child_process";import fs from"fs";import{fileURLToPath}from"url";import path from"path";import chalk from"chalk";import prompts from"prompts";import https from"https";const __filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename);let updateAnswer=null;function bsConfigUrls(e){const s=e.indexOf("\\htdocs\\");if(-1===s)return{bsTarget:"",bsPathRewrite:{}};const n=e.substring(0,s+"\\htdocs\\".length).replace(/\\/g,"\\\\"),t=e.replace(new RegExp(`^${n}`),"").replace(/\\/g,"/");let i=`http://localhost/${t}`;i=i.endsWith("/")?i.slice(0,-1):i;const c=i.replace(/(?<!:)(\/\/+)/g,"/"),r=t.replace(/\/\/+/g,"/");return{bsTarget:`${c}/`,bsPathRewrite:{"^/":`/${r.startsWith("/")?r.substring(1):r}/`}}}function configureBrowserSyncCommand(e){const s=path.join(e,"settings","bs-config.cjs");return fs.writeFileSync(s,'const { createProxyMiddleware } = require("http-proxy-middleware");\nconst fs = require("fs");\n\nconst jsonData = fs.readFileSync("prisma-php.json", "utf8");\nconst config = JSON.parse(jsonData);\n\nmodule.exports = {\n proxy: "http://localhost:3000",\n middleware: [\n (req, res, next) => {\n res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");\n res.setHeader("Pragma", "no-cache");\n res.setHeader("Expires", "0");\n next();\n },\n createProxyMiddleware({\n target: config.bsTarget,\n changeOrigin: true,\n pathRewrite: config.bsPathRewrite,\n }),\n ],\n files: "src/**/*.*",\n notify: false,\n open: false,\n ghostMode: false,\n};',"utf8"),"browser-sync start --config settings/bs-config.cjs"}async function updatePackageJson(e,s){const n=path.join(e,"package.json");if(checkExcludeFiles(n))return;const t=JSON.parse(fs.readFileSync(n,"utf8")),i=configureBrowserSyncCommand(e);t.scripts=Object.assign(Object.assign({},t.scripts),{projectName:"node settings/project-name.cjs"});let c=[];s.tailwindcss&&(t.scripts=Object.assign(Object.assign({},t.scripts),{tailwind:"postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch"}),c.push("tailwind")),s.websocket&&(t.scripts=Object.assign(Object.assign({},t.scripts),{websocket:"node ./settings/restart-websocket.cjs"}),c.push("websocket")),s.docker&&(t.scripts=Object.assign(Object.assign({},t.scripts),{docker:"docker-compose up"}),c.push("docker"));const r=Object.assign({},t.scripts);r["browser-sync"]=i,r.dev=c.length>0?`npm-run-all --parallel projectName browser-sync ${c.join(" ")}`:"npm-run-all --parallel projectName browser-sync",t.scripts=r,t.type="module",s.prisma&&(t.prisma={seed:"node prisma/seed.js"}),fs.writeFileSync(n,JSON.stringify(t,null,2))}async function updateComposerJson(e,s){const n=path.join(e,"composer.json");if(checkExcludeFiles(n))return;let t;if(fs.existsSync(n)){{const e=fs.readFileSync(n,"utf8");t=JSON.parse(e)}s.websocket&&(t.require=Object.assign(Object.assign({},t.require),{"cboden/ratchet":"^0.4.4"})),s.prisma&&(t.require=Object.assign(Object.assign({},t.require),{"ramsey/uuid":"5.x-dev","hidehalo/nanoid-php":"1.x-dev"})),fs.writeFileSync(n,JSON.stringify(t,null,2))}}async function updateIndexJsForWebSocket(e,s){if(!s.websocket)return;const n=path.join(e,"src","app","js","index.js");if(checkExcludeFiles(n))return;let t=fs.readFileSync(n,"utf8");t+='\n// WebSocket initialization\nconst ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(n,t,"utf8")}async function createUpdateGitignoreFile(e,s){const n=path.join(e,".gitignore");if(checkExcludeFiles(n))return;let t="";s.forEach((e=>{t.includes(e)||(t+=`\n${e}`)})),t=t.trimStart(),fs.writeFileSync(n,t)}function copyRecursiveSync(e,s,n){var t;const i=fs.existsSync(e),c=i&&fs.statSync(e);if(i&&c&&c.isDirectory()){const i=s.toLowerCase();if(!n.websocket&&i.includes("src\\lib\\websocket"))return;if(!n.prisma&&i.includes("src\\lib\\prisma"))return;if(n.backendOnly&&i.includes("src\\app\\js")||n.backendOnly&&i.includes("src\\app\\css"))return;const c=s.replace(/\\/g,"/");if(null===(t=null==updateAnswer?void 0:updateAnswer.excludeFilePath)||void 0===t?void 0:t.includes(c))return;fs.existsSync(s)||fs.mkdirSync(s,{recursive:!0}),fs.readdirSync(e).forEach((t=>{copyRecursiveSync(path.join(e,t),path.join(s,t),n)}))}else{if(checkExcludeFiles(s))return;if(!n.tailwindcss&&(s.includes("tailwind.css")||s.includes("styles.css")))return;if(!n.websocket&&(s.includes("restart-websocket.cjs")||s.includes("restart-websocket.bat")))return;if(!n.docker&&(s.includes(".dockerignore")||s.includes("docker-compose.yml")||s.includes("Dockerfile")||s.includes("apache.conf")))return;if(n.backendOnly&&s.includes("favicon.ico")||n.backendOnly&&s.includes("index.php")||n.backendOnly&&s.includes("layout.php")||n.backendOnly&&s.includes("metadata.php")||n.backendOnly&&s.includes("not-found.php"))return;if(!n.backendOnly&&s.includes("route.php"))return;fs.copyFileSync(e,s,0)}}async function executeCopy(e,s,n){s.forEach((({srcDir:s,destDir:t})=>{copyRecursiveSync(path.join(__dirname,s),path.join(e,t),n)}))}function createOrUpdateTailwindConfig(e){const s=path.join(e,"tailwind.config.js");if(checkExcludeFiles(s))return;let n=fs.readFileSync(s,"utf8");const t=["./src/app/**/*.{html,js,php}"].map((e=>` "${e}"`)).join(",\n");n=n.replace(/content: \[\],/g,`content: [\n${t}\n],`),fs.writeFileSync(s,n,{flag:"w"})}function modifyPostcssConfig(e){const s=path.join(e,"postcss.config.js");if(checkExcludeFiles(s))return;fs.writeFileSync(s,"export default {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n cssnano: {},\n },\n};",{flag:"w"})}function modifyLayoutPHP(e,s){const n=path.join(e,"src","app","layout.php");if(!checkExcludeFiles(n))try{let e=fs.readFileSync(n,"utf8");const t='\n <link href="<?php echo $baseUrl; ?>css/index.css" rel="stylesheet">\n <script src="<?php echo $baseUrl; ?>js/index.js"><\/script>',i=s.tailwindcss?` <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet"> ${t}`:` <script src="https://cdn.tailwindcss.com"><\/script> ${t}`;e=e.replace("</head>",`${i}\n</head>`),fs.writeFileSync(n,e,{flag:"w"})}catch(e){}}async function createOrUpdateEnvFile(e,s){const n=path.join(e,".env");checkExcludeFiles(n)||fs.writeFileSync(n,s,{flag:"w"})}function checkExcludeFiles(e){var s,n;return!!(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(null!==(n=null===(s=null==updateAnswer?void 0:updateAnswer.excludeFilePath)||void 0===s?void 0:s.includes(e.replace(/\\/g,"/")))&&void 0!==n&&n)}async function createDirectoryStructure(e,s){const n=[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/../composer.json",dest:"/composer.json"}];(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(n.push({src:"/tsconfig.json",dest:"/tsconfig.json"}),updateAnswer.tailwindcss&&n.push({src:"/postcss.config.js",dest:"/postcss.config.js"},{src:"/tailwind.config.js",dest:"/tailwind.config.js"}));const t=[{srcDir:"/settings",destDir:"/settings"},{srcDir:"/src",destDir:"/src"}];s.prisma&&t.push({srcDir:"/prisma",destDir:"/prisma"}),s.docker&&t.push({srcDir:"/.dockerignore",destDir:"/.dockerignore"},{srcDir:"/docker-compose.yml",destDir:"/docker-compose.yml"},{srcDir:"/Dockerfile",destDir:"/Dockerfile"},{srcDir:"/apache.conf",destDir:"/apache.conf"}),n.forEach((({src:s,dest:n})=>{const t=path.join(__dirname,s),i=path.join(e,n);if(checkExcludeFiles(i))return;const c=fs.readFileSync(t,"utf8");fs.writeFileSync(i,c,{flag:"w"})})),await executeCopy(e,t,s),await updatePackageJson(e,s),await updateComposerJson(e,s),s.backendOnly||await updateIndexJsForWebSocket(e,s),s.tailwindcss?(createOrUpdateTailwindConfig(e),modifyLayoutPHP(e,s),modifyPostcssConfig(e)):s.backendOnly||modifyLayoutPHP(e,s);const i='# Prisma PHP Auth Secret Key For development only - Change this in production\nAUTH_SECRET=uxsjXVPHN038DEYls2Kw0QUgBcXKUyrjv416nIFWPY4= \n \n# PHPMailer\n# SMTP_HOST=smtp.gmail.com or your SMTP host\n# SMTP_USERNAME=john.doe@gmail.com or your SMTP username\n# SMTP_PASSWORD=123456\n# SMTP_PORT=587 for TLS, 465 for SSL or your SMTP port\n# SMTP_ENCRYPTION=ssl or tls\n# MAIL_FROM=john.doe@gmail.com\n# MAIL_FROM_NAME="John Doe"\n\n# SHOW ERRORS - Set to true to show errors in the browser for development only - Change this in production to false\nSHOW_ERRORS=true\n\n# ChatGPT API Key\n# CHATGPT_API_KEY=sk-your-api-key';if(s.prisma){const s=`${'# Environment variables declared in this file are automatically made available to Prisma.\n# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema\n\n# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.\n# See the documentation for all the connection string options: https://pris.ly/d/connection-strings\n\nDATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"'}\n\n${i}`;await createOrUpdateEnvFile(e,s)}else await createOrUpdateEnvFile(e,i);await createUpdateGitignoreFile(e,["vendor",".env","node_modules"])}async function getAnswer(e={}){var s,n,t,i,c,r,o,a,l,p,d;const u=[];e.projectName||u.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.backendOnly||u.push({type:"toggle",name:"backendOnly",message:"Would you like to create a backend-only project?",initial:!1,active:"Yes",inactive:"No"});const h=()=>{process.exit(0)},m=await prompts(u,{onCancel:h}),f=[];m.backendOnly||e.backendOnly?(e.websocket||f.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!0,active:"Yes",inactive:"No"}),e.prisma||f.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!0,active:"Yes",inactive:"No"}),e.docker||f.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"})):(e.tailwindcss||f.unshift({type:"toggle",name:"tailwindcss",message:`Would you like to use ${chalk.blue("Tailwind CSS")}?`,initial:!0,active:"Yes",inactive:"No"}),e.websocket||f.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!0,active:"Yes",inactive:"No"}),e.prisma||f.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!0,active:"Yes",inactive:"No"}),e.docker||f.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"}));const y=await prompts(f,{onCancel:h});return{projectName:m.projectName?String(m.projectName).trim().replace(/ /g,"-"):null!==(s=e.projectName)&&void 0!==s?s:"my-app",backendOnly:null!==(t=null!==(n=m.backendOnly)&&void 0!==n?n:e.backendOnly)&&void 0!==t&&t,tailwindcss:null!==(c=null!==(i=y.tailwindcss)&&void 0!==i?i:e.tailwindcss)&&void 0!==c&&c,websocket:null!==(o=null!==(r=y.websocket)&&void 0!==r?r:e.websocket)&&void 0!==o&&o,prisma:null!==(l=null!==(a=y.prisma)&&void 0!==a?a:e.prisma)&&void 0!==l&&l,docker:null!==(d=null!==(p=y.docker)&&void 0!==p?p:e.docker)&&void 0!==d&&d}}async function installDependencies(e,s,n=!1){fs.existsSync(path.join(e,"package.json"))||execSync("npm init -y",{stdio:"inherit",cwd:e}),s.forEach((e=>{}));const t=`npm install ${n?"--save-dev":""} ${s.join(" ")}`;execSync(t,{stdio:"inherit",cwd:e})}async function uninstallDependencies(e,s,n=!1){s.forEach((e=>{}));const t=`npm uninstall ${n?"--save-dev":"--save"} ${s.join(" ")}`;execSync(t,{stdio:"inherit",cwd:e})}function fetchPackageVersion(e){return new Promise(((s,n)=>{https.get(`https://registry.npmjs.org/${e}`,(e=>{let t="";e.on("data",(e=>t+=e)),e.on("end",(()=>{try{const e=JSON.parse(t);s(e["dist-tags"].latest)}catch(e){n(new Error("Failed to parse JSON response"))}}))})).on("error",(e=>n(e)))}))}const readJsonFile=e=>{const s=fs.readFileSync(e,"utf8");return JSON.parse(s)};function compareVersions(e,s){const n=e.split(".").map(Number),t=s.split(".").map(Number);for(let e=0;e<n.length;e++){if(n[e]>t[e])return 1;if(n[e]<t[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}}async function main(){var e,s,n,t,i,c,r,o;try{const a=process.argv.slice(2);let l=a[0],p=null;if(l){const o={projectName:l,backendOnly:a.includes("--backend-only"),tailwindcss:a.includes("--tailwindcss"),websocket:a.includes("--websocket"),prisma:a.includes("--prisma"),docker:a.includes("--docker")};if(p=await getAnswer(o),null===p)return;const d=process.cwd(),u=path.join(d,"prisma-php.json"),h=readJsonFile(u);let m=[];null===(e=h.excludeFiles)||void 0===e||e.map((e=>{const s=path.join(d,e);fs.existsSync(s)&&m.push(s.replace(/\\/g,"/"))})),updateAnswer={projectName:l,backendOnly:null!==(s=null==p?void 0:p.backendOnly)&&void 0!==s&&s,tailwindcss:null!==(n=null==p?void 0:p.tailwindcss)&&void 0!==n&&n,websocket:null!==(t=null==p?void 0:p.websocket)&&void 0!==t&&t,prisma:null!==(i=null==p?void 0:p.prisma)&&void 0!==i&&i,docker:null!==(c=null==p?void 0:p.docker)&&void 0!==c&&c,isUpdate:!0,excludeFiles:null!==(r=h.excludeFiles)&&void 0!==r?r:[],excludeFilePath:null!=m?m:[],filePath:d}}else p=await getAnswer();if(null===p)return;const d=await fetchPackageVersion("create-prisma-php-app"),u=getInstalledPackageVersion("create-prisma-php-app");u?-1===compareVersions(u,d)&&(execSync("npm uninstall -g create-prisma-php-app",{stdio:"inherit"}),execSync("npm install -g create-prisma-php-app",{stdio:"inherit"})):execSync("npm install -g create-prisma-php-app",{stdio:"inherit"});const h=await fetchPackageVersion("browser-sync"),m=getInstalledPackageVersion("browser-sync");m?-1===compareVersions(m,h)&&(execSync("npm uninstall -g browser-sync",{stdio:"inherit"}),execSync("npm install -g browser-sync",{stdio:"inherit"})):execSync("npm install -g browser-sync",{stdio:"inherit"}),l||fs.mkdirSync(p.projectName);const f=process.cwd();let y=l?f:path.join(f,p.projectName);l||process.chdir(p.projectName);const g=["typescript","@types/node","ts-node","http-proxy-middleware@^3.0.0","npm-run-all"];p.tailwindcss&&g.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano"),p.websocket&&g.push("chokidar-cli"),p.prisma&&g.push("prisma","@prisma/client"),await installDependencies(y,g,!0),l||execSync("npx tsc --init",{stdio:"inherit"}),p.tailwindcss&&execSync("npx tailwindcss init -p",{stdio:"inherit"}),p.prisma&&(fs.existsSync(path.join(y,"prisma"))||execSync("npx prisma init",{stdio:"inherit"})),await createDirectoryStructure(y,p);const w=path.join(y,"public");if(fs.existsSync(w)||fs.mkdirSync(w),null==updateAnswer?void 0:updateAnswer.isUpdate){const e=[];if(updateAnswer.backendOnly){["favicon.ico","index.php","layout.php","metadata.php","not-found.php"].forEach((e=>{const s=path.join(y,"src","app",e);fs.existsSync(s)&&fs.unlinkSync(s)}));["js","css"].forEach((e=>{const s=path.join(y,"src","app",e);fs.existsSync(s)&&fs.rmSync(s,{recursive:!0,force:!0})}))}if(!updateAnswer.tailwindcss){["postcss.config.js","tailwind.config.js"].forEach((e=>{const s=path.join(y,e);fs.existsSync(s)&&fs.unlinkSync(s)})),e.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano")}if(updateAnswer.websocket||e.push("chokidar-cli"),updateAnswer.prisma||e.push("prisma","@prisma/client"),!updateAnswer.docker){[".dockerignore","docker-compose.yml","Dockerfile","apache.conf"].forEach((e=>{const s=path.join(y,e);fs.existsSync(s)&&fs.unlinkSync(s)}))}e.length>0&&await uninstallDependencies(y,e,!0)}const k=y.replace(/\\/g,"\\"),b=bsConfigUrls(k),S=p.prisma?"src/Lib/Prisma/Classes":"",j={projectName:p.projectName,projectRootPath:k,phpEnvironment:"XAMPP",phpRootPathExe:"C:\\xampp\\php\\php.exe",phpGenerateClassPath:S,bsTarget:b.bsTarget,bsPathRewrite:b.bsPathRewrite,backendOnly:p.backendOnly,tailwindcss:p.tailwindcss,websocket:p.websocket,prisma:p.prisma,docker:p.docker,version:d,excludeFiles:null!==(o=null==updateAnswer?void 0:updateAnswer.excludeFiles)&&void 0!==o?o:[]};fs.writeFileSync(path.join(y,"prisma-php.json"),JSON.stringify(j,null,2),{flag:"w"}),(null==updateAnswer?void 0:updateAnswer.isUpdate)?execSync("C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update",{stdio:"inherit"}):execSync("C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install",{stdio:"inherit"})}catch(e){process.exit(1)}}main();
2
+ import{execSync}from"child_process";import fs from"fs";import{fileURLToPath}from"url";import path from"path";import chalk from"chalk";import prompts from"prompts";import https from"https";const __filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename);let updateAnswer=null;function bsConfigUrls(e){const s=e.indexOf("\\htdocs\\");if(-1===s)return{bsTarget:"",bsPathRewrite:{}};const n=e.substring(0,s+"\\htdocs\\".length).replace(/\\/g,"\\\\"),t=e.replace(new RegExp(`^${n}`),"").replace(/\\/g,"/");let i=`http://localhost/${t}`;i=i.endsWith("/")?i.slice(0,-1):i;const c=i.replace(/(?<!:)(\/\/+)/g,"/"),r=t.replace(/\/\/+/g,"/");return{bsTarget:`${c}/`,bsPathRewrite:{"^/":`/${r.startsWith("/")?r.substring(1):r}/`}}}function configureBrowserSyncCommand(e){const s=path.join(e,"settings","bs-config.cjs");return fs.writeFileSync(s,'const { createProxyMiddleware } = require("http-proxy-middleware");\nconst fs = require("fs");\n\nconst jsonData = fs.readFileSync("prisma-php.json", "utf8");\nconst config = JSON.parse(jsonData);\n\nmodule.exports = {\n proxy: "http://localhost:3000",\n middleware: [\n (req, res, next) => {\n res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");\n res.setHeader("Pragma", "no-cache");\n res.setHeader("Expires", "0");\n next();\n },\n createProxyMiddleware({\n target: config.bsTarget,\n changeOrigin: true,\n pathRewrite: config.bsPathRewrite,\n }),\n ],\n files: "src/**/*.*",\n notify: false,\n open: false,\n ghostMode: false,\n};',"utf8"),"browser-sync start --config settings/bs-config.cjs"}async function updatePackageJson(e,s){const n=path.join(e,"package.json");if(checkExcludeFiles(n))return;const t=JSON.parse(fs.readFileSync(n,"utf8")),i=configureBrowserSyncCommand(e);t.scripts=Object.assign(Object.assign({},t.scripts),{projectName:"node settings/project-name.cjs"});let c=[];s.tailwindcss&&(t.scripts=Object.assign(Object.assign({},t.scripts),{tailwind:"postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch"}),c.push("tailwind")),s.websocket&&(t.scripts=Object.assign(Object.assign({},t.scripts),{websocket:"node ./settings/restart-websocket.cjs"}),c.push("websocket")),s.docker&&(t.scripts=Object.assign(Object.assign({},t.scripts),{docker:"docker-compose up"}),c.push("docker"));const r=Object.assign({},t.scripts);r["browser-sync"]=i,r.dev=c.length>0?`npm-run-all --parallel projectName browser-sync ${c.join(" ")}`:"npm-run-all --parallel projectName browser-sync",t.scripts=r,t.type="module",s.prisma&&(t.prisma={seed:"node prisma/seed.js"}),fs.writeFileSync(n,JSON.stringify(t,null,2))}async function updateComposerJson(e,s){const n=path.join(e,"composer.json");if(checkExcludeFiles(n))return;let t;if(fs.existsSync(n)){{const e=fs.readFileSync(n,"utf8");t=JSON.parse(e)}s.websocket&&(t.require=Object.assign(Object.assign({},t.require),{"cboden/ratchet":"^0.4.4"})),s.prisma&&(t.require=Object.assign(Object.assign({},t.require),{"ramsey/uuid":"5.x-dev","hidehalo/nanoid-php":"1.x-dev"})),fs.writeFileSync(n,JSON.stringify(t,null,2))}}async function updateIndexJsForWebSocket(e,s){if(!s.websocket)return;const n=path.join(e,"src","app","js","index.js");if(checkExcludeFiles(n))return;let t=fs.readFileSync(n,"utf8");t+='\n// WebSocket initialization\nconst ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(n,t,"utf8")}async function createUpdateGitignoreFile(e,s){const n=path.join(e,".gitignore");if(checkExcludeFiles(n))return;let t="";s.forEach((e=>{t.includes(e)||(t+=`\n${e}`)})),t=t.trimStart(),fs.writeFileSync(n,t)}function copyRecursiveSync(e,s,n){var t;const i=fs.existsSync(e),c=i&&fs.statSync(e);if(i&&c&&c.isDirectory()){const i=s.toLowerCase();if(!n.websocket&&i.includes("src\\lib\\websocket"))return;if(!n.prisma&&i.includes("src\\lib\\prisma"))return;if(n.backendOnly&&i.includes("src\\app\\js")||n.backendOnly&&i.includes("src\\app\\css"))return;const c=s.replace(/\\/g,"/");if(null===(t=null==updateAnswer?void 0:updateAnswer.excludeFilePath)||void 0===t?void 0:t.includes(c))return;fs.existsSync(s)||fs.mkdirSync(s,{recursive:!0}),fs.readdirSync(e).forEach((t=>{copyRecursiveSync(path.join(e,t),path.join(s,t),n)}))}else{if(checkExcludeFiles(s))return;if(!n.tailwindcss&&(s.includes("tailwind.css")||s.includes("styles.css")))return;if(!n.websocket&&(s.includes("restart-websocket.cjs")||s.includes("restart-websocket.bat")))return;if(!n.docker&&(s.includes(".dockerignore")||s.includes("docker-compose.yml")||s.includes("Dockerfile")||s.includes("apache.conf")))return;if(n.backendOnly&&s.includes("favicon.ico")||n.backendOnly&&s.includes("index.php")||n.backendOnly&&s.includes("layout.php")||n.backendOnly&&s.includes("metadata.php")||n.backendOnly&&s.includes("not-found.php"))return;if(!n.backendOnly&&s.includes("route.php"))return;fs.copyFileSync(e,s,0)}}async function executeCopy(e,s,n){s.forEach((({srcDir:s,destDir:t})=>{copyRecursiveSync(path.join(__dirname,s),path.join(e,t),n)}))}function createOrUpdateTailwindConfig(e){const s=path.join(e,"tailwind.config.js");if(checkExcludeFiles(s))return;let n=fs.readFileSync(s,"utf8");const t=["./src/app/**/*.{html,js,php}"].map((e=>` "${e}"`)).join(",\n");n=n.replace(/content: \[\],/g,`content: [\n${t}\n],`),fs.writeFileSync(s,n,{flag:"w"})}function modifyPostcssConfig(e){const s=path.join(e,"postcss.config.js");if(checkExcludeFiles(s))return;fs.writeFileSync(s,"export default {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n cssnano: {},\n },\n};",{flag:"w"})}function modifyLayoutPHP(e,s){const n=path.join(e,"src","app","layout.php");if(!checkExcludeFiles(n))try{let e=fs.readFileSync(n,"utf8");const t='\n <link href="<?php echo $baseUrl; ?>css/index.css" rel="stylesheet">\n <script src="<?php echo $baseUrl; ?>js/index.js"><\/script>',i=s.tailwindcss?` <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet"> ${t}`:` <script src="https://cdn.tailwindcss.com"><\/script> ${t}`;e=e.replace("</head>",`${i}\n</head>`),fs.writeFileSync(n,e,{flag:"w"})}catch(e){}}async function createOrUpdateEnvFile(e,s){const n=path.join(e,".env");checkExcludeFiles(n)||fs.writeFileSync(n,s,{flag:"w"})}function checkExcludeFiles(e){var s,n;return!!(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(null!==(n=null===(s=null==updateAnswer?void 0:updateAnswer.excludeFilePath)||void 0===s?void 0:s.includes(e.replace(/\\/g,"/")))&&void 0!==n&&n)}async function createDirectoryStructure(e,s){const n=[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/../composer.json",dest:"/composer.json"}];(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(n.push({src:"/tsconfig.json",dest:"/tsconfig.json"}),updateAnswer.tailwindcss&&n.push({src:"/postcss.config.js",dest:"/postcss.config.js"},{src:"/tailwind.config.js",dest:"/tailwind.config.js"}));const t=[{srcDir:"/settings",destDir:"/settings"},{srcDir:"/src",destDir:"/src"}];s.prisma&&t.push({srcDir:"/prisma",destDir:"/prisma"}),s.docker&&t.push({srcDir:"/.dockerignore",destDir:"/.dockerignore"},{srcDir:"/docker-compose.yml",destDir:"/docker-compose.yml"},{srcDir:"/Dockerfile",destDir:"/Dockerfile"},{srcDir:"/apache.conf",destDir:"/apache.conf"}),n.forEach((({src:s,dest:n})=>{const t=path.join(__dirname,s),i=path.join(e,n);if(checkExcludeFiles(i))return;const c=fs.readFileSync(t,"utf8");fs.writeFileSync(i,c,{flag:"w"})})),await executeCopy(e,t,s),await updatePackageJson(e,s),await updateComposerJson(e,s),s.backendOnly||await updateIndexJsForWebSocket(e,s),s.tailwindcss?(createOrUpdateTailwindConfig(e),modifyLayoutPHP(e,s),modifyPostcssConfig(e)):s.backendOnly||modifyLayoutPHP(e,s);const i='# Prisma PHP Auth Secret Key For development only - Change this in production\nAUTH_SECRET=uxsjXVPHN038DEYls2Kw0QUgBcXKUyrjv416nIFWPY4= \n \n# PHPMailer\n# SMTP_HOST=smtp.gmail.com or your SMTP host\n# SMTP_USERNAME=john.doe@gmail.com or your SMTP username\n# SMTP_PASSWORD=123456\n# SMTP_PORT=587 for TLS, 465 for SSL or your SMTP port\n# SMTP_ENCRYPTION=ssl or tls\n# MAIL_FROM=john.doe@gmail.com\n# MAIL_FROM_NAME="John Doe"\n\n# SHOW ERRORS - Set to true to show errors in the browser for development only - Change this in production to false\nSHOW_ERRORS=true\n\n# ChatGPT API Key\n# CHATGPT_API_KEY=sk-your-api-key\n\n# APP TIMEZONE - Set your application timezone - Default is "UTC"\nAPP_TIMEZONE="UTC"';if(s.prisma){const s=`${'# Environment variables declared in this file are automatically made available to Prisma.\n# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema\n\n# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.\n# See the documentation for all the connection string options: https://pris.ly/d/connection-strings\n\nDATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"'}\n\n${i}`;await createOrUpdateEnvFile(e,s)}else await createOrUpdateEnvFile(e,i);await createUpdateGitignoreFile(e,["vendor",".env","node_modules"])}async function getAnswer(e={}){var s,n,t,i,c,r,o,a,l,p,d;const u=[];e.projectName||u.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.backendOnly||u.push({type:"toggle",name:"backendOnly",message:"Would you like to create a backend-only project?",initial:!1,active:"Yes",inactive:"No"});const h=()=>{process.exit(0)},m=await prompts(u,{onCancel:h}),f=[];m.backendOnly||e.backendOnly?(e.websocket||f.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!0,active:"Yes",inactive:"No"}),e.prisma||f.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!0,active:"Yes",inactive:"No"}),e.docker||f.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"})):(e.tailwindcss||f.unshift({type:"toggle",name:"tailwindcss",message:`Would you like to use ${chalk.blue("Tailwind CSS")}?`,initial:!0,active:"Yes",inactive:"No"}),e.websocket||f.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!0,active:"Yes",inactive:"No"}),e.prisma||f.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!0,active:"Yes",inactive:"No"}),e.docker||f.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"}));const y=await prompts(f,{onCancel:h});return{projectName:m.projectName?String(m.projectName).trim().replace(/ /g,"-"):null!==(s=e.projectName)&&void 0!==s?s:"my-app",backendOnly:null!==(t=null!==(n=m.backendOnly)&&void 0!==n?n:e.backendOnly)&&void 0!==t&&t,tailwindcss:null!==(c=null!==(i=y.tailwindcss)&&void 0!==i?i:e.tailwindcss)&&void 0!==c&&c,websocket:null!==(o=null!==(r=y.websocket)&&void 0!==r?r:e.websocket)&&void 0!==o&&o,prisma:null!==(l=null!==(a=y.prisma)&&void 0!==a?a:e.prisma)&&void 0!==l&&l,docker:null!==(d=null!==(p=y.docker)&&void 0!==p?p:e.docker)&&void 0!==d&&d}}async function installDependencies(e,s,n=!1){fs.existsSync(path.join(e,"package.json"))||execSync("npm init -y",{stdio:"inherit",cwd:e}),s.forEach((e=>{}));const t=`npm install ${n?"--save-dev":""} ${s.join(" ")}`;execSync(t,{stdio:"inherit",cwd:e})}async function uninstallDependencies(e,s,n=!1){s.forEach((e=>{}));const t=`npm uninstall ${n?"--save-dev":"--save"} ${s.join(" ")}`;execSync(t,{stdio:"inherit",cwd:e})}function fetchPackageVersion(e){return new Promise(((s,n)=>{https.get(`https://registry.npmjs.org/${e}`,(e=>{let t="";e.on("data",(e=>t+=e)),e.on("end",(()=>{try{const e=JSON.parse(t);s(e["dist-tags"].latest)}catch(e){n(new Error("Failed to parse JSON response"))}}))})).on("error",(e=>n(e)))}))}const readJsonFile=e=>{const s=fs.readFileSync(e,"utf8");return JSON.parse(s)};function compareVersions(e,s){const n=e.split(".").map(Number),t=s.split(".").map(Number);for(let e=0;e<n.length;e++){if(n[e]>t[e])return 1;if(n[e]<t[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}}async function main(){var e,s,n,t,i,c,r,o;try{const a=process.argv.slice(2);let l=a[0],p=null;if(l){const o={projectName:l,backendOnly:a.includes("--backend-only"),tailwindcss:a.includes("--tailwindcss"),websocket:a.includes("--websocket"),prisma:a.includes("--prisma"),docker:a.includes("--docker")};if(p=await getAnswer(o),null===p)return;const d=process.cwd(),u=path.join(d,"prisma-php.json"),h=readJsonFile(u);let m=[];null===(e=h.excludeFiles)||void 0===e||e.map((e=>{const s=path.join(d,e);fs.existsSync(s)&&m.push(s.replace(/\\/g,"/"))})),updateAnswer={projectName:l,backendOnly:null!==(s=null==p?void 0:p.backendOnly)&&void 0!==s&&s,tailwindcss:null!==(n=null==p?void 0:p.tailwindcss)&&void 0!==n&&n,websocket:null!==(t=null==p?void 0:p.websocket)&&void 0!==t&&t,prisma:null!==(i=null==p?void 0:p.prisma)&&void 0!==i&&i,docker:null!==(c=null==p?void 0:p.docker)&&void 0!==c&&c,isUpdate:!0,excludeFiles:null!==(r=h.excludeFiles)&&void 0!==r?r:[],excludeFilePath:null!=m?m:[],filePath:d}}else p=await getAnswer();if(null===p)return;const d=await fetchPackageVersion("create-prisma-php-app"),u=getInstalledPackageVersion("create-prisma-php-app");u?-1===compareVersions(u,d)&&(execSync("npm uninstall -g create-prisma-php-app",{stdio:"inherit"}),execSync("npm install -g create-prisma-php-app",{stdio:"inherit"})):execSync("npm install -g create-prisma-php-app",{stdio:"inherit"});const h=await fetchPackageVersion("browser-sync"),m=getInstalledPackageVersion("browser-sync");m?-1===compareVersions(m,h)&&(execSync("npm uninstall -g browser-sync",{stdio:"inherit"}),execSync("npm install -g browser-sync",{stdio:"inherit"})):execSync("npm install -g browser-sync",{stdio:"inherit"}),l||fs.mkdirSync(p.projectName);const f=process.cwd();let y=l?f:path.join(f,p.projectName);l||process.chdir(p.projectName);const g=["typescript","@types/node","ts-node","http-proxy-middleware@^3.0.0","npm-run-all"];p.tailwindcss&&g.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano"),p.websocket&&g.push("chokidar-cli"),p.prisma&&g.push("prisma","@prisma/client"),await installDependencies(y,g,!0),l||execSync("npx tsc --init",{stdio:"inherit"}),p.tailwindcss&&execSync("npx tailwindcss init -p",{stdio:"inherit"}),p.prisma&&(fs.existsSync(path.join(y,"prisma"))||execSync("npx prisma init",{stdio:"inherit"})),await createDirectoryStructure(y,p);const w=path.join(y,"public");if(fs.existsSync(w)||fs.mkdirSync(w),null==updateAnswer?void 0:updateAnswer.isUpdate){const e=[];if(updateAnswer.backendOnly){["favicon.ico","index.php","layout.php","metadata.php","not-found.php"].forEach((e=>{const s=path.join(y,"src","app",e);fs.existsSync(s)&&fs.unlinkSync(s)}));["js","css"].forEach((e=>{const s=path.join(y,"src","app",e);fs.existsSync(s)&&fs.rmSync(s,{recursive:!0,force:!0})}))}if(!updateAnswer.tailwindcss){["postcss.config.js","tailwind.config.js"].forEach((e=>{const s=path.join(y,e);fs.existsSync(s)&&fs.unlinkSync(s)})),e.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano")}if(updateAnswer.websocket||e.push("chokidar-cli"),updateAnswer.prisma||e.push("prisma","@prisma/client"),!updateAnswer.docker){[".dockerignore","docker-compose.yml","Dockerfile","apache.conf"].forEach((e=>{const s=path.join(y,e);fs.existsSync(s)&&fs.unlinkSync(s)}))}e.length>0&&await uninstallDependencies(y,e,!0)}const k=y.replace(/\\/g,"\\"),b=bsConfigUrls(k),S=p.prisma?"src/Lib/Prisma/Classes":"",j={projectName:p.projectName,projectRootPath:k,phpEnvironment:"XAMPP",phpRootPathExe:"C:\\xampp\\php\\php.exe",phpGenerateClassPath:S,bsTarget:b.bsTarget,bsPathRewrite:b.bsPathRewrite,backendOnly:p.backendOnly,tailwindcss:p.tailwindcss,websocket:p.websocket,prisma:p.prisma,docker:p.docker,version:d,excludeFiles:null!==(o=null==updateAnswer?void 0:updateAnswer.excludeFiles)&&void 0!==o?o:[]};fs.writeFileSync(path.join(y,"prisma-php.json"),JSON.stringify(j,null,2),{flag:"w"}),(null==updateAnswer?void 0:updateAnswer.isUpdate)?execSync("C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update",{stdio:"inherit"}):execSync("C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install",{stdio:"inherit"})}catch(e){process.exit(1)}}main();