create-prisma-php-app 1.22.508 → 1.23.0

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.
@@ -37,7 +37,7 @@ function determineContentToInclude()
37
37
  * ================================================
38
38
  */
39
39
 
40
- $isDirectAccessToPrivateRoute = preg_match('/\/_/', $uri);
40
+ $isDirectAccessToPrivateRoute = preg_match('/_/', $uri);
41
41
  if ($isDirectAccessToPrivateRoute) {
42
42
  $sameSiteFetch = false;
43
43
  $serverFetchSite = $_SERVER['HTTP_SEC_FETCH_SITE'] ?? '';
@@ -335,9 +335,7 @@ function singleDynamicRoute($uriSegments, $routeSegments)
335
335
 
336
336
  function checkForDuplicateRoutes()
337
337
  {
338
- if ($_ENV['APP_ENV'] !== 'development') {
339
- return;
340
- }
338
+ if ($_ENV['APP_ENV'] !== 'development') return;
341
339
 
342
340
  global $_filesListRoutes;
343
341
  $normalizedRoutesMap = [];
@@ -760,7 +758,7 @@ try {
760
758
  $_isContentIncluded = true;
761
759
  }
762
760
 
763
- if (!empty($_contentToInclude)) {
761
+ if (!empty($_contentToInclude) && !empty($_fileToInclude)) {
764
762
  if (!$_isParentLayout) {
765
763
  ob_start();
766
764
  require_once $_contentToInclude;
package/dist/index.js CHANGED
@@ -1,7 +1,37 @@
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;const nonBackendFiles=["favicon.ico","\\src\\app\\index.php","metadata.php","not-found.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 i=`http://localhost/${n}`;i=i.endsWith("/")?i.slice(0,-1):i;const c=i.replace(/(?<!:)(\/\/+)/g,"/"),o=n.replace(/\/\/+/g,"/");return{bsTarget:`${c}/`,bsPathRewrite:{"^/":`/${o.startsWith("/")?o.substring(1):o}/`}}}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=Object.assign(Object.assign({},n.scripts),{projectName:"node settings/project-name.js"});let i=[];s.tailwindcss&&(n.scripts=Object.assign(Object.assign({},n.scripts),{tailwind:"postcss src/app/css/tailwind.css -o src/app/css/styles.css --watch"}),i.push("tailwind")),s.websocket&&(n.scripts=Object.assign(Object.assign({},n.scripts),{websocket:"node settings/restart-websocket.js"}),i.push("websocket")),s.docker&&(n.scripts=Object.assign(Object.assign({},n.scripts),{docker:"docker-compose up"}),i.push("docker")),s.swaggerDocs&&(n.scripts=Object.assign(Object.assign({},n.scripts),{"create-swagger-docs":"node settings/swagger-config.js"}),i.push("create-swagger-docs"));let c=Object.assign({},n.scripts);c.browserSync="node settings/bs-config.js",c.dev=`npm-run-all -p projectName browserSync ${i.join(" ")}`,n.scripts=c,n.type="module",s.prisma&&(n.prisma={seed:"node prisma/seed.js"}),fs.writeFileSync(t,JSON.stringify(n,null,2))}async function updateComposerJson(e,s){const t=path.join(e,"composer.json");if(checkExcludeFiles(t))return;let n;if(fs.existsSync(t)){{const e=fs.readFileSync(t,"utf8");n=JSON.parse(e)}s.websocket&&(n.require=Object.assign(Object.assign({},n.require),{"cboden/ratchet":"^0.4.4"})),s.prisma&&(n.require=Object.assign(Object.assign({},n.require),{"ramsey/uuid":"5.x-dev","hidehalo/nanoid-php":"1.x-dev"})),fs.writeFileSync(t,JSON.stringify(n,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\nconst ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,n,"utf8")}async function createUpdateGitignoreFile(e,s){const t=path.join(e,".gitignore");if(checkExcludeFiles(t))return;let n="";s.forEach((e=>{n.includes(e)||(n+=`\n${e}`)})),n=n.trimStart(),fs.writeFileSync(t,n)}function copyRecursiveSync(e,s,t){var n;const i=fs.existsSync(e),c=i&&fs.statSync(e);if(i&&c&&c.isDirectory()){const i=s.toLowerCase();if(!t.websocket&&i.includes("src\\lib\\websocket"))return;if(!t.prisma&&i.includes("src\\lib\\prisma"))return;if(t.backendOnly&&i.includes("src\\app\\js")||t.backendOnly&&i.includes("src\\app\\css"))return;if(!t.swaggerDocs&&i.includes("src\\app\\swagger-docs"))return;const c=s.replace(/\\/g,"/");if(null===(n=null==updateAnswer?void 0:updateAnswer.excludeFilePath)||void 0===n?void 0:n.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.cjs")||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.swaggerDocs&&s.includes("swagger-config.js"))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 createOrUpdateTailwindConfig(e){const s=path.join(e,"tailwind.config.js");if(checkExcludeFiles(s))return;let t=fs.readFileSync(s,"utf8");const n=["./src/**/*.{html,js,php}"].map((e=>` "${e}"`)).join(",\n");t=t.replace(/content: \[\],/g,`content: [\n${n}\n],`),fs.writeFileSync(s,t,{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 t=path.join(e,"src","app","layout.php");if(!checkExcludeFiles(t))try{let e=fs.readFileSync(t,"utf8"),n="";s.backendOnly||(n='\n <link href="<?= $baseUrl; ?>/css/index.css" rel="stylesheet">\n <script src="<?= $baseUrl; ?>/js/index.js"><\/script>');let i="";s.backendOnly||(i=s.tailwindcss?` <link href="<?= $baseUrl; ?>/css/styles.css" rel="stylesheet"> ${n}`:` <script src="https://cdn.tailwindcss.com"><\/script> ${n}`);const c=i.length>0?"\n":"";e=e.replace("</head>",`${i}${c} \x3c!-- Dynamic Head --\x3e\n <?= implode("\\n", $mainLayoutHead); ?>\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){var s,t;return!!(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(null!==(t=null===(s=null==updateAnswer?void 0:updateAnswer.excludeFilePath)||void 0===s?void 0:s.includes(e.replace(/\\/g,"/")))&&void 0!==t&&t)}async function createDirectoryStructure(e,s){const t=[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/../composer.json",dest:"/composer.json"},{src:"/tsconfig.json",dest:"/tsconfig.json"}];s.tailwindcss&&t.push({src:"/postcss.config.js",dest:"/postcss.config.js"},{src:"/tailwind.config.js",dest:"/tailwind.config.js"});const n=[{src:"/settings",dest:"/settings"},{src:"/src",dest:"/src"}];s.backendOnly&&s.swaggerDocs&&n.push({src:"/swagger-docs-layout.php",dest:"/src/app/layout.php"}),s.prisma&&n.push({src:"/prisma",dest:"/prisma"}),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),i=path.join(e,t);if(checkExcludeFiles(i))return;const c=fs.readFileSync(n,"utf8");fs.writeFileSync(i,c,{flag:"w"})})),await executeCopy(e,n,s),await updatePackageJson(e,s),await updateComposerJson(e,s),s.backendOnly||await updateIndexJsForWebSocket(e,s),s.tailwindcss&&(createOrUpdateTailwindConfig(e),modifyPostcssConfig(e)),(s.tailwindcss||!s.backendOnly||s.swaggerDocs)&&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# APP TIMEZONE - Set your application timezone - Default is "UTC"\nAPP_TIMEZONE="UTC"\n\n# APP ENV - Set your application environment - Default is "development" - Change this in production to "production"\nAPP_ENV=development';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,t,n,i,c,o,a,r,l,p,d,u,g;const m=[];e.projectName||m.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.backendOnly||m.push({type:"toggle",name:"backendOnly",message:"Would you like to create a backend-only project?",initial:!1,active:"Yes",inactive:"No"});const f=()=>{process.exit(0)},h=await prompts(m,{onCancel:f}),y=[];h.backendOnly||e.backendOnly?(e.swaggerDocs||y.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),e.websocket||y.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!0,active:"Yes",inactive:"No"}),e.prisma||y.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!0,active:"Yes",inactive:"No"}),e.docker||y.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"})):(e.swaggerDocs||y.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),e.tailwindcss||y.push({type:"toggle",name:"tailwindcss",message:`Would you like to use ${chalk.blue("Tailwind CSS")}?`,initial:!0,active:"Yes",inactive:"No"}),e.websocket||y.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!0,active:"Yes",inactive:"No"}),e.prisma||y.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!0,active:"Yes",inactive:"No"}),e.docker||y.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"}));const w=await prompts(y,{onCancel:f});return{projectName:h.projectName?String(h.projectName).trim().replace(/ /g,"-"):null!==(s=e.projectName)&&void 0!==s?s:"my-app",backendOnly:null!==(n=null!==(t=h.backendOnly)&&void 0!==t?t:e.backendOnly)&&void 0!==n&&n,swaggerDocs:null!==(c=null!==(i=w.swaggerDocs)&&void 0!==i?i:e.swaggerDocs)&&void 0!==c&&c,tailwindcss:null!==(a=null!==(o=w.tailwindcss)&&void 0!==o?o:e.tailwindcss)&&void 0!==a&&a,websocket:null!==(l=null!==(r=w.websocket)&&void 0!==r?r:e.websocket)&&void 0!==l&&l,prisma:null!==(d=null!==(p=w.prisma)&&void 0!==p?p:e.prisma)&&void 0!==d&&d,docker:null!==(g=null!==(u=w.docker)&&void 0!==u?u:e.docker)&&void 0!==g&&g}}async function installDependencies(e,s,t=!1){fs.existsSync(path.join(e,"package.json"))||execSync("npm init -y",{stdio:"inherit",cwd:e}),s.forEach((e=>{}));const n=`npm install ${t?"--save-dev":""} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}async function uninstallDependencies(e,s,t=!1){s.forEach((e=>{}));const n=`npm uninstall ${t?"--save-dev":"--save"} ${s.join(" ")}`;execSync(n,{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";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"],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 i=c.replace(/(?<!:)(\/\/+)/g,"/"),o=n.replace(/\/\/+/g,"/");return{bsTarget:`${i}/`,bsPathRewrite:{"^/":`/${o.startsWith("/")?o.substring(1):o}/`}}}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=[];s.tailwindcss&&(n.scripts={...n.scripts,tailwind:"postcss src/app/css/tailwind.css -o src/app/css/styles.css --watch"},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&&(n.scripts={...n.scripts,"create-swagger-docs":"tsx settings/swagger-config.ts"},c.push("create-swagger-docs"));let i={...n.scripts};i.browserSync="tsx settings/bs-config.ts",i.dev=`npm-run-all -p projectName browserSync ${c.join(" ")}`,n.scripts=i,n.type="module",s.prisma&&(n.prisma={seed:"node prisma/seed.js"}),fs.writeFileSync(t,JSON.stringify(n,null,2))}async function updateComposerJson(e,s){const t=path.join(e,"composer.json");if(checkExcludeFiles(t))return;let n;if(fs.existsSync(t)){{const e=fs.readFileSync(t,"utf8");n=JSON.parse(e)}s.websocket&&(n.require={...n.require,"cboden/ratchet":"^0.4.4"}),s.prisma&&(n.require={...n.require,"ramsey/uuid":"5.x-dev","hidehalo/nanoid-php":"1.x-dev"}),fs.writeFileSync(t,JSON.stringify(n,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\nconst ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,n,"utf8")}async function createUpdateGitignoreFile(e,s){const t=path.join(e,".gitignore");if(checkExcludeFiles(t))return;let n="";s.forEach((e=>{n.includes(e)||(n+=`\n${e}`)})),n=n.trimStart(),fs.writeFileSync(t,n)}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.prisma&&n.includes("src\\lib\\prisma"))return;if(t.backendOnly&&n.includes("src\\app\\js")||t.backendOnly&&n.includes("src\\app\\css"))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.swaggerDocs&&s.includes("swagger-config.ts"))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 createOrUpdateTailwindConfig(e){const s=path.join(e,"tailwind.config.js");if(checkExcludeFiles(s))return;let t=fs.readFileSync(s,"utf8");const n=["./src/**/*.{html,js,php}"].map((e=>` "${e}"`)).join(",\n");t=t.replace(/content: \[\],/g,`content: [\n${n}\n],`),fs.writeFileSync(s,t,{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 t=path.join(e,"src","app","layout.php");if(!checkExcludeFiles(t))try{let e=fs.readFileSync(t,"utf8"),n="";s.backendOnly||(n='\n <link href="<?= $baseUrl; ?>/css/index.css" rel="stylesheet">\n <script src="<?= $baseUrl; ?>/js/index.js"><\/script>');let c="";s.backendOnly||(c=s.tailwindcss?` <link href="<?= $baseUrl; ?>/css/styles.css" rel="stylesheet"> ${n}`:` <script src="https://cdn.tailwindcss.com"><\/script> ${n}`);const i=c.length>0?"\n":"";e=e.replace("</head>",`${c}${i} \x3c!-- Dynamic Head --\x3e\n <?= implode("\\n", $mainLayoutHead); ?>\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:"/../composer.json",dest:"/composer.json"},{src:"/tsconfig.json",dest:"/tsconfig.json"}];s.tailwindcss&&t.push({src:"/postcss.config.js",dest:"/postcss.config.js"},{src:"/tailwind.config.js",dest:"/tailwind.config.js"});const n=[{src:"/settings",dest:"/settings"},{src:"/src",dest:"/src"}];s.backendOnly&&s.swaggerDocs&&n.push({src:"/swagger-docs-layout.php",dest:"/src/app/layout.php"}),s.prisma&&n.push({src:"/prisma",dest:"/prisma"}),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 i=fs.readFileSync(n,"utf8");fs.writeFileSync(c,i,{flag:"w"})})),await executeCopy(e,n,s),await updatePackageJson(e,s),await updateComposerJson(e,s),s.backendOnly||await updateIndexJsForWebSocket(e,s),s.tailwindcss&&(createOrUpdateTailwindConfig(e),modifyPostcssConfig(e)),(s.tailwindcss||!s.backendOnly||s.swaggerDocs)&&modifyLayoutPHP(e,s);const c='# 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# APP TIMEZONE - Set your application timezone - Default is "UTC"\nAPP_TIMEZONE="UTC"\n\n# APP ENV - Set your application environment - Default is "development" - Change this in production to "production"\nAPP_ENV=development';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${c}`;await createOrUpdateEnvFile(e,s)}else await createOrUpdateEnvFile(e,c);await createUpdateGitignoreFile(e,["vendor",".env","node_modules"])}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 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:!0,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"}));const i=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:i.swaggerDocs??e.swaggerDocs??!1,tailwindcss:i.tailwindcss??e.tailwindcss??!1,websocket:i.websocket??e.websocket??!1,prisma:i.prisma??e.prisma??!1,docker:i.docker??e.docker??!1}}async function uninstallDependencies(e,s,t=!1){s.forEach((e=>{}));const n=`npm uninstall ${t?"--save-dev":"--save"} ${s.join(" ")}`;execSync(n,{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
+ /**
4
+ * Install dependencies in the specified directory.
5
+ * @param {string} baseDir - The base directory where to install the dependencies.
6
+ * @param {string[]} dependencies - The list of dependencies to install.
7
+ * @param {boolean} [isDev=false] - Whether to install the dependencies as devDependencies.
8
+ */
9
+ async function installDependencies(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
+ // Log the dependencies being installed
18
+ console.log(
19
+ `${
20
+ isDev ? "Installing development dependencies" : "Installing dependencies"
21
+ }:`
22
+ );
23
+ dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
24
+ // Prepare the npm install command with the appropriate flag for dev dependencies
25
+ const npmInstallCommand = `npm install ${
26
+ isDev ? "--save-dev" : ""
27
+ } ${dependencies.join(" ")}`;
28
+ // Execute the npm install command
29
+ execSync(npmInstallCommand, {
30
+ stdio: "inherit",
31
+ cwd: baseDir,
32
+ });
33
+ }
3
34
  async function main() {
4
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
5
35
  try {
6
36
  const args = process.argv.slice(2);
7
37
  let projectName = args[0];
@@ -31,60 +61,22 @@ async function main() {
31
61
  const configPath = path.join(currentDir, "prisma-php.json");
32
62
  const localSettings = readJsonFile(configPath);
33
63
  let excludeFiles = [];
34
- (_a = localSettings.excludeFiles) === null || _a === void 0
35
- ? void 0
36
- : _a.map((file) => {
37
- const filePath = path.join(currentDir, file);
38
- if (fs.existsSync(filePath))
39
- excludeFiles.push(filePath.replace(/\\/g, "/"));
40
- });
64
+ localSettings.excludeFiles?.map((file) => {
65
+ const filePath = path.join(currentDir, file);
66
+ if (fs.existsSync(filePath))
67
+ excludeFiles.push(filePath.replace(/\\/g, "/"));
68
+ });
41
69
  updateAnswer = {
42
70
  projectName,
43
- backendOnly:
44
- (_b =
45
- answer === null || answer === void 0
46
- ? void 0
47
- : answer.backendOnly) !== null && _b !== void 0
48
- ? _b
49
- : false,
50
- swaggerDocs:
51
- (_c =
52
- answer === null || answer === void 0
53
- ? void 0
54
- : answer.swaggerDocs) !== null && _c !== void 0
55
- ? _c
56
- : false,
57
- tailwindcss:
58
- (_d =
59
- answer === null || answer === void 0
60
- ? void 0
61
- : answer.tailwindcss) !== null && _d !== void 0
62
- ? _d
63
- : false,
64
- websocket:
65
- (_e =
66
- answer === null || answer === void 0
67
- ? void 0
68
- : answer.websocket) !== null && _e !== void 0
69
- ? _e
70
- : false,
71
- prisma:
72
- (_f =
73
- answer === null || answer === void 0 ? void 0 : answer.prisma) !==
74
- null && _f !== void 0
75
- ? _f
76
- : false,
77
- docker:
78
- (_g =
79
- answer === null || answer === void 0 ? void 0 : answer.docker) !==
80
- null && _g !== void 0
81
- ? _g
82
- : false,
71
+ backendOnly: answer?.backendOnly ?? false,
72
+ swaggerDocs: answer?.swaggerDocs ?? false,
73
+ tailwindcss: answer?.tailwindcss ?? false,
74
+ websocket: answer?.websocket ?? false,
75
+ prisma: answer?.prisma ?? false,
76
+ docker: answer?.docker ?? false,
83
77
  isUpdate: true,
84
- excludeFiles:
85
- (_h = localSettings.excludeFiles) !== null && _h !== void 0 ? _h : [],
86
- excludeFilePath:
87
- excludeFiles !== null && excludeFiles !== void 0 ? excludeFiles : [],
78
+ excludeFiles: localSettings.excludeFiles ?? [],
79
+ excludeFilePath: excludeFiles ?? [],
88
80
  filePath: currentDir,
89
81
  };
90
82
  } else {
@@ -127,7 +119,7 @@ async function main() {
127
119
  const dependencies = [
128
120
  "typescript",
129
121
  "@types/node",
130
- "ts-node",
122
+ "tsx",
131
123
  "http-proxy-middleware",
132
124
  "chalk",
133
125
  "npm-run-all",
@@ -183,11 +175,7 @@ async function main() {
183
175
  { stdio: "inherit" }
184
176
  );
185
177
  }
186
- if (
187
- updateAnswer === null || updateAnswer === void 0
188
- ? void 0
189
- : updateAnswer.isUpdate
190
- ) {
178
+ if (updateAnswer?.isUpdate) {
191
179
  const updateUninstallDependencies = [];
192
180
  if (updateAnswer.backendOnly) {
193
181
  nonBackendFiles.forEach((file) => {
@@ -221,7 +209,7 @@ async function main() {
221
209
  fs.rmSync(swaggerDocsFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
222
210
  console.log(`swagger-docs was deleted successfully.`);
223
211
  }
224
- const swaggerFiles = ["swagger-setup.js"];
212
+ const swaggerFiles = ["swagger-config.ts"];
225
213
  swaggerFiles.forEach((file) => {
226
214
  const filePath = path.join(projectPath, "settings", file);
227
215
  if (fs.existsSync(filePath)) {
@@ -254,7 +242,7 @@ async function main() {
254
242
  }
255
243
  if (!updateAnswer.websocket) {
256
244
  const websocketFiles = [
257
- "restart-websocket.js",
245
+ "restart-websocket.ts",
258
246
  "restart-websocket.bat",
259
247
  ];
260
248
  websocketFiles.forEach((file) => {
@@ -323,26 +311,15 @@ async function main() {
323
311
  websocket: answer.websocket,
324
312
  prisma: answer.prisma,
325
313
  docker: answer.docker,
326
- ngrok: false,
327
314
  version: latestVersionOfCreatePrismaPhpApp,
328
- excludeFiles:
329
- (_j =
330
- updateAnswer === null || updateAnswer === void 0
331
- ? void 0
332
- : updateAnswer.excludeFiles) !== null && _j !== void 0
333
- ? _j
334
- : [],
315
+ excludeFiles: updateAnswer?.excludeFiles ?? [],
335
316
  };
336
317
  fs.writeFileSync(
337
318
  path.join(projectPath, "prisma-php.json"),
338
319
  JSON.stringify(prismaPhpConfig, null, 2),
339
320
  { flag: "w" }
340
321
  );
341
- if (
342
- updateAnswer === null || updateAnswer === void 0
343
- ? void 0
344
- : updateAnswer.isUpdate
345
- ) {
322
+ if (updateAnswer?.isUpdate) {
346
323
  execSync(
347
324
  `C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update`,
348
325
  {
@@ -357,11 +334,15 @@ async function main() {
357
334
  }
358
335
  );
359
336
  }
337
+ console.log("\n=========================\n");
360
338
  console.log(
361
- `${chalk.green("Success!")} Prisma PHP project successfully created in ${
339
+ `${chalk.green(
340
+ "Success!"
341
+ )} Prisma PHP project successfully created in ${chalk.green(
362
342
  answer.projectName
363
- }!`
343
+ )}!`
364
344
  );
345
+ console.log("\n=========================");
365
346
  } catch (error) {
366
347
  console.error("Error while creating the project:", error);
367
348
  process.exit(1);
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import chalk from"chalk";import{spawn}from"child_process";import fs from"fs";import path from"path";import prompts from"prompts";import{fileURLToPath}from"url";const __filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename),args=process.argv.slice(2),readJsonFile=e=>{const t=fs.readFileSync(e,"utf8");return JSON.parse(t)},executeCommand=(e,t=[],o={})=>new Promise(((r,a)=>{const s=spawn(e,t,Object.assign({stdio:"inherit",shell:!0},o));s.on("error",(e=>{a(e)})),s.on("close",(e=>{0===e?r():a(new Error(`Process exited with code ${e}`))}))}));async function getAnswer(){const e=[{type:"toggle",name:"shouldProceed",message:`This command will update the ${chalk.blue("create-prisma-php-app")} package and overwrite all default files. ${chalk.blue("Do you want to proceed")}?`,initial:!1,active:"Yes",inactive:"No"}],t=await prompts(e,{onCancel:()=>{process.exit(0)}});return 0===Object.keys(t).length?null:t}const commandsToExecute={generateClass:"npx php generate class",update:"npx php update project"};
2
+ import chalk from"chalk";import{spawn}from"child_process";import fs from"fs";import path from"path";import prompts from"prompts";import{fileURLToPath}from"url";const __filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename),args=process.argv.slice(2),readJsonFile=e=>{const t=fs.readFileSync(e,"utf8");return JSON.parse(t)},executeCommand=(e,t=[],o={})=>new Promise(((r,a)=>{const s=spawn(e,t,{stdio:"inherit",shell:!0,...o});s.on("error",(e=>{a(e)})),s.on("close",(e=>{0===e?r():a(new Error(`Process exited with code ${e}`))}))}));async function getAnswer(){const e=[{type:"toggle",name:"shouldProceed",message:`This command will update the ${chalk.blue("create-prisma-php-app")} package and overwrite all default files. ${chalk.blue("Do you want to proceed")}?`,initial:!1,active:"Yes",inactive:"No"}],t=await prompts(e,{onCancel:()=>{process.exit(0)}});return 0===Object.keys(t).length?null:t}const commandsToExecute={generateClass:"npx php generate class",update:"npx php update project"};
3
3
  const main = async () => {
4
4
  if (args.length === 0) {
5
5
  console.log("No command provided.");
@@ -14,9 +14,7 @@ const main = async () => {
14
14
  if (formattedCommand === commandsToExecute.update) {
15
15
  try {
16
16
  const answer = await getAnswer();
17
- if (
18
- !(answer === null || answer === void 0 ? void 0 : answer.shouldProceed)
19
- ) {
17
+ if (!answer?.shouldProceed) {
20
18
  console.log(chalk.red("Operation cancelled by the user."));
21
19
  return;
22
20
  }
@@ -0,0 +1,87 @@
1
+ import { createProxyMiddleware } from "http-proxy-middleware";
2
+ import { writeFileSync } from "fs";
3
+ import chokidar from "chokidar";
4
+ import browserSync, { BrowserSyncInstance } from "browser-sync";
5
+ import prismaPhpConfig from "../prisma-php.json";
6
+ import { generateFileListJson } from "./files-list.js";
7
+ import { join } from "path";
8
+ import { getFileMeta } from "./utils.js";
9
+
10
+ const { __dirname } = getFileMeta();
11
+
12
+ const bs: BrowserSyncInstance = browserSync.create();
13
+
14
+ // Watch for file changes (create, delete, save)
15
+ const watcher = chokidar.watch("src/app/**/*", {
16
+ ignored: /(^|[\/\\])\../, // Ignore dotfiles
17
+ persistent: true,
18
+ usePolling: true,
19
+ interval: 1000,
20
+ });
21
+
22
+ // Perform specific actions for file events
23
+ watcher
24
+ .on("add", () => {
25
+ generateFileListJson();
26
+ })
27
+ .on("change", () => {
28
+ generateFileListJson();
29
+ })
30
+ .on("unlink", () => {
31
+ generateFileListJson();
32
+ });
33
+
34
+ // BrowserSync initialization
35
+ bs.init(
36
+ {
37
+ proxy: "http://localhost:3000",
38
+ middleware: [
39
+ (_: any, res: any, next: any) => {
40
+ res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
41
+ res.setHeader("Pragma", "no-cache");
42
+ res.setHeader("Expires", "0");
43
+ next();
44
+ },
45
+ createProxyMiddleware({
46
+ target: prismaPhpConfig.bsTarget,
47
+ changeOrigin: true,
48
+ pathRewrite: {},
49
+ }),
50
+ ],
51
+ files: "src/**/*.*",
52
+ notify: false,
53
+ open: false,
54
+ ghostMode: false,
55
+ codeSync: true, // Disable synchronization of code changes across clients
56
+ watchOptions: {
57
+ usePolling: true,
58
+ interval: 1000,
59
+ },
60
+ },
61
+ (err, bsInstance) => {
62
+ if (err) {
63
+ console.error("BrowserSync failed to start:", err);
64
+ return;
65
+ }
66
+
67
+ // Retrieve the active URLs from the BrowserSync instance
68
+ const options = bsInstance.getOption("urls");
69
+ const localUrl = options.get("local");
70
+ const externalUrl = options.get("external");
71
+ const uiUrl = options.get("ui");
72
+ const uiExternalUrl = options.get("ui-external");
73
+
74
+ // Construct the URLs dynamically
75
+ const urls = {
76
+ local: localUrl,
77
+ external: externalUrl,
78
+ ui: uiUrl,
79
+ uiExternal: uiExternalUrl,
80
+ };
81
+
82
+ writeFileSync(
83
+ join(__dirname, "bs-config.json"),
84
+ JSON.stringify(urls, null, 2)
85
+ );
86
+ }
87
+ );
@@ -0,0 +1,51 @@
1
+ import { existsSync, readdirSync, statSync, writeFileSync } from "fs";
2
+ import { join, sep, relative } from "path";
3
+ import { getFileMeta } from "./utils.js";
4
+
5
+ const { __dirname } = getFileMeta();
6
+
7
+ // Define the directory and JSON file paths correctly
8
+ const dirPath = "src/app"; // Directory path
9
+ const jsonFilePath = "settings/files-list.json"; // Path to the JSON file
10
+
11
+ // Function to get all files in the directory
12
+ const getAllFiles = (dirPath: string): string[] => {
13
+ const files: string[] = [];
14
+
15
+ // Check if directory exists before reading
16
+ if (!existsSync(dirPath)) {
17
+ console.error(`Directory not found: ${dirPath}`);
18
+ return files; // Return an empty array if the directory doesn't exist
19
+ }
20
+
21
+ const items = readdirSync(dirPath);
22
+ items.forEach((item) => {
23
+ const fullPath = join(dirPath, item);
24
+ if (statSync(fullPath).isDirectory()) {
25
+ files.push(...getAllFiles(fullPath)); // Recursive call for subdirectories
26
+ } else {
27
+ // Generate the relative path and ensure it starts with ./src
28
+ const relativePath = `.${sep}${relative(
29
+ join(__dirname, ".."),
30
+ fullPath
31
+ )}`;
32
+ // Replace only the root backslashes with forward slashes and leave inner ones
33
+ files.push(relativePath.replace(/\\/g, "/").replace(/^\.\.\//, ""));
34
+ }
35
+ });
36
+
37
+ return files;
38
+ };
39
+
40
+ // Function to generate the files-list.json
41
+ export const generateFileListJson = async (): Promise<void> => {
42
+ const files = getAllFiles(dirPath);
43
+
44
+ // If files exist, generate JSON file
45
+ if (files.length > 0) {
46
+ writeFileSync(jsonFilePath, JSON.stringify(files, null, 2));
47
+ // console.log(`File list has been saved to: ${jsonFilePath}`);
48
+ } else {
49
+ console.error("No files found to save in the JSON file.");
50
+ }
51
+ };
@@ -0,0 +1,86 @@
1
+ import { writeFile } from "fs";
2
+ import { join, basename, dirname, normalize, sep } from "path";
3
+ import prismaPhpConfig from "../prisma-php.json";
4
+ import { getFileMeta } from "./utils.js";
5
+
6
+ const { __dirname } = getFileMeta();
7
+
8
+ const newProjectName = basename(join(__dirname, ".."));
9
+
10
+ // Function to update the project name and paths in the JSON config
11
+ function updateProjectNameInConfig(
12
+ filePath: string,
13
+ newProjectName: string
14
+ ): void {
15
+ const filePathDir = dirname(filePath);
16
+
17
+ // Update the projectName directly in the imported config
18
+ prismaPhpConfig.projectName = newProjectName;
19
+
20
+ // Update other paths
21
+ prismaPhpConfig.projectRootPath = filePathDir;
22
+
23
+ const targetPath = getTargetPath(filePathDir, prismaPhpConfig.phpEnvironment);
24
+
25
+ prismaPhpConfig.bsTarget = `http://localhost${targetPath}`;
26
+ prismaPhpConfig.bsPathRewrite["^/"] = targetPath;
27
+
28
+ // Save the updated config back to the JSON file
29
+ writeFile(
30
+ filePath,
31
+ JSON.stringify(prismaPhpConfig, null, 2),
32
+ "utf8",
33
+ (err) => {
34
+ if (err) {
35
+ console.error("Error writing the updated JSON file:", err);
36
+ return;
37
+ }
38
+ console.log(
39
+ "The project name, PHP path, and other paths have been updated successfully."
40
+ );
41
+ }
42
+ );
43
+ }
44
+
45
+ // Function to determine the target path for browser-sync
46
+ function getTargetPath(fullPath: string, environment: string): string {
47
+ const normalizedPath = normalize(fullPath);
48
+ const webDirectories: { [key: string]: string } = {
49
+ XAMPP: join("htdocs"),
50
+ WAMP: join("www"),
51
+ MAMP: join("htdocs"),
52
+ LAMP: join("var", "www", "html"),
53
+ LEMP: join("usr", "share", "nginx", "html"),
54
+ AMPPS: join("www"),
55
+ UniformServer: join("www"),
56
+ EasyPHP: join("data", "localweb"),
57
+ };
58
+
59
+ const webDir = webDirectories[environment.toUpperCase()];
60
+ if (!webDir) {
61
+ throw new Error(`Unsupported environment: ${environment}`);
62
+ }
63
+
64
+ const indexOfWebDir = normalizedPath
65
+ .toLowerCase()
66
+ .indexOf(normalize(webDir).toLowerCase());
67
+ if (indexOfWebDir === -1) {
68
+ throw new Error(`Web directory not found in path: ${webDir}`);
69
+ }
70
+
71
+ const startIndex = indexOfWebDir + webDir.length;
72
+ const subPath = normalizedPath.slice(startIndex);
73
+ const safeSeparatorRegex = new RegExp(
74
+ sep.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"),
75
+ "g"
76
+ );
77
+ const finalPath = subPath.replace(safeSeparatorRegex, "/") + "/";
78
+
79
+ return finalPath;
80
+ }
81
+
82
+ // Path to your JSON configuration file (for saving changes)
83
+ const configFilePath = join(__dirname, "..", "prisma-php.json");
84
+
85
+ // Run the function with your config file path and the new project name
86
+ updateProjectNameInConfig(configFilePath, newProjectName);
@@ -86,7 +86,7 @@ $scriptName = dirname($_SERVER['SCRIPT_NAME']);
86
86
  /**
87
87
  * @var string $baseUrl - The base URL of the request.
88
88
  */
89
- $baseUrl = $_prismaPHPSettings['ngrok'] ? 'src/app' : $protocol . $domainName . "$scriptName/src/app";
89
+ $baseUrl = '/src/app';
90
90
  /**
91
91
  * @var string $documentUrl - The document URL of the request.
92
92
  */
@@ -0,0 +1,57 @@
1
+ import { spawn, ChildProcess } from "child_process";
2
+ import { join } from "path";
3
+ import chokidar from "chokidar";
4
+ import { getFileMeta } from "./utils.js";
5
+
6
+ const { __dirname } = getFileMeta();
7
+
8
+ // Define paths
9
+ const phpPath = "php"; // Adjust if necessary to include the full path to PHP
10
+ const serverScriptPath = join(
11
+ __dirname,
12
+ "..",
13
+ "src",
14
+ "Lib",
15
+ "Websocket",
16
+ "server.php"
17
+ );
18
+
19
+ // Hold the server process
20
+ let serverProcess: ChildProcess | null = null;
21
+
22
+ const restartServer = (): void => {
23
+ // If a server process already exists, kill it
24
+ if (serverProcess) {
25
+ console.log("Stopping WebSocket server...");
26
+ serverProcess.kill("SIGINT"); // Adjust the signal as necessary for your environment
27
+ serverProcess = null;
28
+ }
29
+
30
+ // Start a new WebSocket server process
31
+ console.log("Starting WebSocket server...");
32
+ serverProcess = spawn(phpPath, [serverScriptPath]);
33
+
34
+ serverProcess.stdout?.on("data", (data: Buffer) => {
35
+ console.log(`WebSocket Server: ${data.toString()}`);
36
+ });
37
+
38
+ serverProcess.stderr?.on("data", (data: Buffer) => {
39
+ console.error(`WebSocket Server Error: ${data.toString()}`);
40
+ });
41
+
42
+ serverProcess.on("close", (code: number) => {
43
+ console.log(`WebSocket server process exited with code ${code}`);
44
+ });
45
+ };
46
+
47
+ // Initial start
48
+ restartServer();
49
+
50
+ // Watch for changes and restart the server
51
+ chokidar
52
+ .watch(join(__dirname, "..", "src", "Lib", "Websocket", "**", "*"))
53
+ .on("change", (path: string) => {
54
+ const fileChanged = path.split("\\").pop();
55
+ console.log(`File changed: src/Lib/Websocket/${fileChanged}`);
56
+ restartServer();
57
+ });
@@ -0,0 +1,66 @@
1
+ import swaggerJsdoc from "swagger-jsdoc";
2
+ import { writeFileSync } from "fs";
3
+ import { join } from "path";
4
+ import chalk from "chalk";
5
+ import { getFileMeta } from "./utils.js";
6
+ import bsConnectionInfo from "./bs-config.json";
7
+
8
+ const { __dirname } = getFileMeta();
9
+
10
+ export async function swaggerConfig(): Promise<void> {
11
+ const outputPath = join(
12
+ __dirname,
13
+ "../src/app/swagger-docs/apis/pphp-swagger.json"
14
+ );
15
+
16
+ const options = {
17
+ definition: {
18
+ openapi: "3.0.0",
19
+ info: {
20
+ title: "Prisma PHP API Documentation",
21
+ version: "1.0.0",
22
+ description: "API documentation for the Prisma PHP project",
23
+ },
24
+ servers: [
25
+ {
26
+ url: bsConnectionInfo.local, // For Development
27
+ description: "Development Server",
28
+ },
29
+ {
30
+ url: "your-production-domain", // For Production
31
+ description: "Production Server",
32
+ },
33
+ ],
34
+ components: {
35
+ securitySchemes: {
36
+ bearerAuth: {
37
+ type: "http",
38
+ scheme: "bearer",
39
+ bearerFormat: "JWT",
40
+ },
41
+ },
42
+ },
43
+ security: [
44
+ {
45
+ bearerAuth: [],
46
+ },
47
+ ],
48
+ },
49
+ apis: [join(__dirname, "../src/app/swagger-docs/apis/**/*.js")], // Adjust to match JavaScript file paths
50
+ };
51
+
52
+ // Generate the Swagger specification
53
+ const swaggerSpec = JSON.stringify(swaggerJsdoc(options), null, 2);
54
+
55
+ // Always generate the swagger.json file
56
+ try {
57
+ writeFileSync(outputPath, swaggerSpec, "utf-8");
58
+ console.log(
59
+ `Swagger JSON has been generated and saved to ${chalk.blue(
60
+ "src/app/swagger-docs/pphp-swagger.json"
61
+ )}`
62
+ );
63
+ } catch (error) {
64
+ console.error("Error saving Swagger JSON:", error);
65
+ }
66
+ }
@@ -0,0 +1,14 @@
1
+ import { fileURLToPath } from "url";
2
+ import { dirname } from "path";
3
+
4
+ /**
5
+ * Retrieves the file metadata including the filename and directory name.
6
+ *
7
+ * @param importMetaUrl - The URL of the module's import.meta.url.
8
+ * @returns An object containing the filename (`__filename`) and directory name (`__dirname`).
9
+ */
10
+ export function getFileMeta() {
11
+ const __filename = fileURLToPath(import.meta.url);
12
+ const __dirname = dirname(__filename);
13
+ return { __filename, __dirname };
14
+ }
@@ -25,9 +25,9 @@
25
25
  // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
26
 
27
27
  /* Modules */
28
- "module": "NodeNext" /* Specify what module code is generated. */,
28
+ "module": "ESNext" /* Specify what module code is generated. */,
29
29
  // "rootDir": "./", /* Specify the root folder within your source files. */
30
- // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
30
+ "moduleResolution": "Node", /* Specify how TypeScript looks up a file from a given module specifier. */
31
31
  // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
32
  // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
33
  // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
@@ -74,7 +74,7 @@
74
74
  // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
75
75
 
76
76
  /* Interop Constraints */
77
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
77
+ "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78
78
  // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79
79
  // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80
80
  "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
@@ -91,8 +91,8 @@
91
91
  // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
92
92
  // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
93
93
  // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
94
- // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95
- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
94
+ "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95
+ "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
96
96
  // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
97
97
  // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
98
98
  // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-prisma-php-app",
3
- "version": "1.22.508",
3
+ "version": "1.23.0",
4
4
  "description": "Prisma-PHP: A Revolutionary Library Bridging PHP with Prisma ORM",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -1,75 +0,0 @@
1
- import { createProxyMiddleware } from "http-proxy-middleware";
2
- import { readFileSync, writeFileSync } from "fs";
3
- import chokidar from "chokidar";
4
- import browserSync from "browser-sync";
5
- // import prismaPhpConfig from "../prisma-php.json" assert { type: "json" };
6
- import { generateFileListJson } from "./files-list.js";
7
- import { join, dirname } from "path";
8
- import { fileURLToPath } from "url";
9
- const __filename = fileURLToPath(import.meta.url);
10
- const __dirname = dirname(__filename);
11
- const bs = browserSync.create();
12
- const prismaPhpConfig = JSON.parse(readFileSync(join(__dirname, "..", "prisma-php.json")).toString("utf-8"));
13
- // Watch for file changes (create, delete, save)
14
- const watcher = chokidar.watch("src/app/**/*", {
15
- ignored: /(^|[\/\\])\../, // Ignore dotfiles
16
- persistent: true,
17
- usePolling: true,
18
- interval: 1000,
19
- });
20
- // Perform specific actions for file events
21
- watcher
22
- .on("add", (path) => {
23
- generateFileListJson();
24
- })
25
- .on("change", (path) => {
26
- generateFileListJson();
27
- })
28
- .on("unlink", (path) => {
29
- generateFileListJson();
30
- });
31
- // BrowserSync initialization
32
- bs.init({
33
- proxy: "http://localhost:3000",
34
- middleware: [
35
- (req, res, next) => {
36
- res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
37
- res.setHeader("Pragma", "no-cache");
38
- res.setHeader("Expires", "0");
39
- next();
40
- },
41
- createProxyMiddleware({
42
- target: prismaPhpConfig.bsTarget,
43
- changeOrigin: true,
44
- pathRewrite: prismaPhpConfig.ngrok ? {} : prismaPhpConfig.bsPathRewrite,
45
- }),
46
- ],
47
- files: "src/**/*.*",
48
- notify: false,
49
- open: false,
50
- ghostMode: false,
51
- codeSync: true, // Disable synchronization of code changes across clients
52
- watchOptions: {
53
- usePolling: true,
54
- interval: 1000,
55
- },
56
- }, (err, bsInstance) => {
57
- if (err) {
58
- console.error("BrowserSync failed to start:", err);
59
- return;
60
- }
61
- // Retrieve the active URLs from the BrowserSync instance
62
- const options = bsInstance.getOption("urls");
63
- const localUrl = options.get("local");
64
- const externalUrl = options.get("external");
65
- const uiUrl = options.get("ui");
66
- const uiExternalUrl = options.get("ui-external");
67
- // Construct the URLs dynamically
68
- const urls = {
69
- local: localUrl,
70
- external: externalUrl,
71
- ui: uiUrl,
72
- uiExternal: uiExternalUrl,
73
- };
74
- writeFileSync(join(__dirname, "bs-config.json"), JSON.stringify(urls, null, 2));
75
- });
@@ -1,43 +0,0 @@
1
- import fs from "fs";
2
- import { join, sep, relative, dirname } from "path";
3
- import { fileURLToPath } from "url";
4
- const __filename = fileURLToPath(import.meta.url);
5
- const __dirname = dirname(__filename);
6
- // Define the directory and JSON file paths correctly
7
- const dirPath = "src/app"; // Directory path
8
- const jsonFilePath = "settings/files-list.json"; // Path to the JSON file
9
- // Function to get all files in the directory
10
- const getAllFiles = (dirPath) => {
11
- const files = [];
12
- // Check if directory exists before reading
13
- if (!fs.existsSync(dirPath)) {
14
- console.error(`Directory not found: ${dirPath}`);
15
- return files; // Return an empty array if the directory doesn't exist
16
- }
17
- const items = fs.readdirSync(dirPath);
18
- items.forEach((item) => {
19
- const fullPath = join(dirPath, item);
20
- if (fs.statSync(fullPath).isDirectory()) {
21
- files.push(...getAllFiles(fullPath)); // Recursive call for subdirectories
22
- }
23
- else {
24
- // Generate the relative path and ensure it starts with ./src
25
- const relativePath = `.${sep}${relative(join(__dirname, ".."), fullPath)}`;
26
- // Replace only the root backslashes with forward slashes and leave inner ones
27
- files.push(relativePath.replace(/\\/g, "/").replace(/^\.\.\//, ""));
28
- }
29
- });
30
- return files;
31
- };
32
- // Function to generate the files-list.json
33
- export const generateFileListJson = () => {
34
- const files = getAllFiles(dirPath);
35
- // If files exist, generate JSON file
36
- if (files.length > 0) {
37
- fs.writeFileSync(jsonFilePath, JSON.stringify(files, null, 2));
38
- // console.log(`File list has been saved to: ${jsonFilePath}`);
39
- }
40
- else {
41
- console.error("No files found to save in the JSON file.");
42
- }
43
- };
@@ -1,60 +0,0 @@
1
- import fs, { readFileSync } from "fs";
2
- import { join, basename, dirname, normalize, sep } from "path";
3
- import { fileURLToPath } from "url";
4
- // import prismaPhpConfig from "../prisma-php.json" assert { type: "json" };
5
- const __filename = fileURLToPath(import.meta.url);
6
- const __dirname = dirname(__filename);
7
- const prismaPhpConfig = JSON.parse(readFileSync(join(__dirname, "..", "prisma-php.json")).toString("utf-8"));
8
- const newProjectName = basename(join(__dirname, ".."));
9
- // Function to update the project name and paths in the JSON config
10
- function updateProjectNameInConfig(filePath, newProjectName) {
11
- const filePathDir = dirname(filePath);
12
- // Update the projectName directly in the imported config
13
- prismaPhpConfig.projectName = newProjectName;
14
- // Update other paths
15
- prismaPhpConfig.projectRootPath = filePathDir;
16
- const targetPath = getTargetPath(filePathDir, prismaPhpConfig.phpEnvironment);
17
- prismaPhpConfig.bsTarget = `http://localhost${targetPath}`;
18
- prismaPhpConfig.bsPathRewrite["^/"] = targetPath;
19
- // Save the updated config back to the JSON file
20
- fs.writeFile(filePath, JSON.stringify(prismaPhpConfig, null, 2), "utf8", (err) => {
21
- if (err) {
22
- console.error("Error writing the updated JSON file:", err);
23
- return;
24
- }
25
- console.log("The project name, PHP path, and other paths have been updated successfully.");
26
- });
27
- }
28
- // Function to determine the target path for browser-sync
29
- function getTargetPath(fullPath, environment) {
30
- const normalizedPath = normalize(fullPath);
31
- const webDirectories = {
32
- XAMPP: join("htdocs"),
33
- WAMP: join("www"),
34
- MAMP: join("htdocs"),
35
- LAMP: join("var", "www", "html"),
36
- LEMP: join("usr", "share", "nginx", "html"),
37
- AMPPS: join("www"),
38
- UniformServer: join("www"),
39
- EasyPHP: join("data", "localweb"),
40
- };
41
- const webDir = webDirectories[environment.toUpperCase()];
42
- if (!webDir) {
43
- throw new Error(`Unsupported environment: ${environment}`);
44
- }
45
- const indexOfWebDir = normalizedPath
46
- .toLowerCase()
47
- .indexOf(normalize(webDir).toLowerCase());
48
- if (indexOfWebDir === -1) {
49
- throw new Error(`Web directory not found in path: ${webDir}`);
50
- }
51
- const startIndex = indexOfWebDir + webDir.length;
52
- const subPath = normalizedPath.slice(startIndex);
53
- const safeSeparatorRegex = new RegExp(sep.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"), "g");
54
- const finalPath = subPath.replace(safeSeparatorRegex, "/") + "/";
55
- return finalPath;
56
- }
57
- // Path to your JSON configuration file (for saving changes)
58
- const configFilePath = join(__dirname, "..", "prisma-php.json");
59
- // Run the function with your config file path and the new project name
60
- updateProjectNameInConfig(configFilePath, newProjectName);
@@ -1,40 +0,0 @@
1
- import { spawn } from "child_process";
2
- import path, { dirname } from "path";
3
- import chokidar from "chokidar";
4
- import { fileURLToPath } from "url";
5
- const __filename = fileURLToPath(import.meta.url);
6
- const __dirname = dirname(__filename);
7
- // Define paths
8
- const phpPath = "php"; // Adjust if necessary to include the full path to PHP
9
- const serverScriptPath = path.join(__dirname, "..", "src", "Lib", "Websocket", "server.php");
10
- // Hold the server process
11
- let serverProcess = null;
12
- const restartServer = () => {
13
- // If a server process already exists, kill it
14
- if (serverProcess) {
15
- console.log("Stopping WebSocket server...");
16
- serverProcess.kill("SIGINT"); // Adjust the signal as necessary for your environment
17
- serverProcess = null;
18
- }
19
- // Start a new WebSocket server process
20
- console.log("Starting WebSocket server...");
21
- serverProcess = spawn(phpPath, [serverScriptPath]);
22
- serverProcess.stdout?.on("data", (data) => {
23
- console.log(`WebSocket Server: ${data.toString()}`);
24
- });
25
- serverProcess.stderr?.on("data", (data) => {
26
- console.error(`WebSocket Server Error: ${data.toString()}`);
27
- });
28
- serverProcess.on("close", (code) => {
29
- console.log(`WebSocket server process exited with code ${code}`);
30
- });
31
- };
32
- // Initial start
33
- restartServer();
34
- // Watch for changes and restart the server
35
- chokidar
36
- .watch(path.join(__dirname, "..", "src", "Lib", "Websocket", "**", "*"))
37
- .on("change", (path) => {
38
- console.log(`File changed: ${path}`);
39
- restartServer();
40
- });
@@ -1,75 +0,0 @@
1
- import swaggerJsdoc from "swagger-jsdoc";
2
- import { writeFileSync, readFileSync, existsSync } from "fs";
3
- import { fileURLToPath } from "url";
4
- import { join, dirname } from "path";
5
- import chalk from "chalk";
6
- const __filename = fileURLToPath(import.meta.url);
7
- const __dirname = dirname(__filename);
8
- // Define the output path for the swagger.json file
9
- const outputPath = join(__dirname, "../src/app/swagger-docs/apis/pphp-swagger.json");
10
- const bsConnectionInfo = join(__dirname, "bs-config.json");
11
- // Default connection info
12
- const defaultConnectionInfo = {
13
- local: "http://localhost:3000",
14
- external: "http://192.168.1.5:3000",
15
- ui: "http://localhost:3001",
16
- uiExternal: "http://192.168.1.5:3001",
17
- };
18
- let jsonData = defaultConnectionInfo;
19
- if (existsSync(bsConnectionInfo)) {
20
- try {
21
- const data = readFileSync(bsConnectionInfo, "utf8");
22
- jsonData = JSON.parse(data);
23
- }
24
- catch (error) {
25
- console.error("Error parsing bs-output.json:", error);
26
- }
27
- }
28
- else {
29
- console.warn("bs-output.json not found, using default connection info.");
30
- }
31
- const options = {
32
- definition: {
33
- openapi: "3.0.0",
34
- info: {
35
- title: "Prisma PHP API Documentation",
36
- version: "1.0.0",
37
- description: "API documentation for the Prisma PHP project",
38
- },
39
- servers: [
40
- {
41
- url: jsonData.local, // For Development
42
- description: "Development Server",
43
- },
44
- {
45
- url: "your-production-domain", // For Production
46
- description: "Production Server",
47
- },
48
- ],
49
- components: {
50
- securitySchemes: {
51
- bearerAuth: {
52
- type: "http",
53
- scheme: "bearer",
54
- bearerFormat: "JWT",
55
- },
56
- },
57
- },
58
- security: [
59
- {
60
- bearerAuth: [],
61
- },
62
- ],
63
- },
64
- apis: [join(__dirname, "../src/app/swagger-docs/apis/**/*.ts")], // Adjust to match TypeScript file paths
65
- };
66
- // Generate the Swagger specification
67
- const swaggerSpec = JSON.stringify(swaggerJsdoc(options), null, 2);
68
- // Always generate the swagger.json file
69
- try {
70
- writeFileSync(outputPath, swaggerSpec, "utf-8");
71
- console.log(`Swagger JSON has been generated and saved to ${chalk.blue("src/app/swagger-docs/pphp-swagger.json")}`);
72
- }
73
- catch (error) {
74
- console.error("Error saving Swagger JSON:", error);
75
- }