create-prisma-php-app 1.22.3 → 1.22.5

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.
@@ -188,29 +188,37 @@ function dynamicRoute($uri)
188
188
  $normalizedUri = ltrim(str_replace('\\', '/', $uri), './');
189
189
  $normalizedUriEdited = "src/app/$normalizedUri";
190
190
  $uriSegments = explode('/', $normalizedUriEdited);
191
+
191
192
  foreach ($_filesListRoutes as $route) {
192
193
  $normalizedRoute = trim(str_replace('\\', '/', $route), '.');
194
+
195
+ // Skip non-.php files to improve performance
196
+ if (pathinfo($normalizedRoute, PATHINFO_EXTENSION) !== 'php') {
197
+ continue;
198
+ }
199
+
193
200
  $routeSegments = explode('/', ltrim($normalizedRoute, '/'));
194
201
 
195
202
  $filteredRouteSegments = array_values(array_filter($routeSegments, function ($segment) {
196
203
  return !preg_match('/\(.+\)/', $segment); // Skip segments with parentheses (groups)
197
204
  }));
198
205
 
199
- $singleDynamic = preg_match_all('/\[[^\]]+\]/', $normalizedRoute, $matches) === 1 && !strpos($normalizedRoute, '[...');
206
+ $singleDynamic = preg_match_all('/\[[^\]]+\]/', $normalizedRoute, $matches) === 1 && strpos($normalizedRoute, '[...') === false;
207
+
200
208
  if ($singleDynamic) {
201
209
  $segmentMatch = singleDynamicRoute($uriSegments, $filteredRouteSegments);
202
210
  $index = array_search($segmentMatch, $filteredRouteSegments);
211
+
203
212
  if ($index !== false && isset($uriSegments[$index])) {
204
213
  $trimSegmentMatch = trim($segmentMatch, '[]');
205
214
  $dynamicRouteParams = new \ArrayObject([$trimSegmentMatch => $uriSegments[$index]], \ArrayObject::ARRAY_AS_PROPS);
215
+
206
216
  $dynamicRouteUri = str_replace($segmentMatch, $uriSegments[$index], $normalizedRoute);
207
217
  $dynamicRouteUri = preg_replace('/\(.+\)/', '', $dynamicRouteUri);
208
218
  $dynamicRouteUri = preg_replace('/\/+/', '/', $dynamicRouteUri);
209
- $dynamicRouteUriDirname = dirname($dynamicRouteUri);
210
- $dynamicRouteUriDirname = rtrim($dynamicRouteUriDirname, '/');
219
+ $dynamicRouteUriDirname = rtrim(dirname($dynamicRouteUri), '/');
211
220
 
212
- $expectedUri = '/src/app/' . $normalizedUri;
213
- $expectedUri = rtrim($expectedUri, '/');
221
+ $expectedUri = rtrim('/src/app/' . $normalizedUri, '/');
214
222
 
215
223
  if (strpos($normalizedRoute, 'route.php') !== false || strpos($normalizedRoute, 'index.php') !== false) {
216
224
  if ($expectedUri === $dynamicRouteUriDirname) {
@@ -221,9 +229,9 @@ function dynamicRoute($uri)
221
229
  }
222
230
  } elseif (strpos($normalizedRoute, '[...') !== false) {
223
231
  // Clean and normalize the route
224
- $cleanedNormalizedRoute = preg_replace('/\(.+\)/', '', $normalizedRoute); // Remove any public/private segment
225
- $cleanedNormalizedRoute = preg_replace('/\/+/', '/', $cleanedNormalizedRoute); // Replace multiple slashes
226
- $dynamicSegmentRoute = preg_replace('/\[\.\.\..*?\].*/', '', $cleanedNormalizedRoute); // Remove the dynamic segment
232
+ $cleanedNormalizedRoute = preg_replace('/\(.+\)/', '', $normalizedRoute);
233
+ $cleanedNormalizedRoute = preg_replace('/\/+/', '/', $cleanedNormalizedRoute);
234
+ $dynamicSegmentRoute = preg_replace('/\[\.\.\..*?\].*/', '', $cleanedNormalizedRoute);
227
235
 
228
236
  // Check if the normalized URI starts with the cleaned route
229
237
  if (strpos("/src/app/$normalizedUri", $dynamicSegmentRoute) === 0) {
@@ -364,7 +372,6 @@ function checkForDuplicateRoutes()
364
372
  }
365
373
  }
366
374
 
367
-
368
375
  function containsChildContent($filePath)
369
376
  {
370
377
  $fileContent = file_get_contents($filePath);
@@ -536,8 +543,6 @@ function getLoadingsFiles()
536
543
  return '';
537
544
  }
538
545
 
539
-
540
-
541
546
  function getPrismaSettings(): \ArrayObject
542
547
  {
543
548
  $_prismaPHPSettingsFile = DOCUMENT_PATH . '/prisma-php.json';
@@ -631,12 +636,13 @@ register_shutdown_function(function () {
631
636
  }
632
637
  });
633
638
 
639
+ $_prismaPHPSettings = getPrismaSettings();
640
+ $_filesListRoutes = getFilesListRoutes();
641
+
634
642
  require_once SETTINGS_PATH . '/public-functions.php';
635
643
  require_once SETTINGS_PATH . '/request-methods.php';
636
644
  $_metadataFile = APP_PATH . '/metadata.php';
637
645
  $_metadataArray = file_exists($_metadataFile) ? require_once $_metadataFile : [];
638
- $_filesListRoutes = getFilesListRoutes();
639
- $_prismaPHPSettings = getPrismaSettings();
640
646
  $_fileToInclude = '';
641
647
 
642
648
  function authenticateUserToken()
package/dist/index.js CHANGED
@@ -1,2 +1,370 @@
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 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,"/"),o=t.replace(/\/\/+/g,"/");return{bsTarget:`${c}/`,bsPathRewrite:{"^/":`/${o.startsWith("/")?o.substring(1):o}/`}}}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");\nconst chokidar = require("chokidar");\nconst { execSync } = require("child_process");\n\nconst jsonData = fs.readFileSync("prisma-php.json", "utf8");\nconst config = JSON.parse(jsonData);\n\n// Watch for file changes (create, delete, save)\nconst watcher = chokidar.watch("src/**/*", {\n ignored: /(^|[\\/\\\\])\\../,\n persistent: true,\n usePolling: true,\n interval: 1000,\n});\n\nwatcher\n .on("add", async (path) => {\n execSync("node settings/files-list-config.js");\n })\n .on("change", async (path) => {\n execSync("node settings/files-list-config.js");\n })\n .on("unlink", async (path) => {\n execSync("node settings/files-list-config.js");\n });\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 codeSync: true, // Disable synchronization of code changes across clients\n watchOptions: {\n usePolling: true,\n interval: 1000,\n },\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")),s.swaggerDocs&&(t.scripts=Object.assign(Object.assign({},t.scripts),{"create-swagger-docs":"node settings/swagger-setup.js"}),c.push("create-swagger-docs"));let o=Object.assign({},t.scripts);o.browserSync=i,o.npmRunAll=c.length>0?`npm-run-all -p ${c.join(" ")}`:'echo "No additional scripts to run"',o.dev="node settings/start-dev.js",t.scripts=o,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;if(!n.swaggerDocs&&i.includes("src\\app\\swagger-docs"))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&&dockerFiles.some((e=>s.includes(e))))return;if(n.backendOnly&&nonBackendFiles.some((e=>s.includes(e))))return;if(!n.backendOnly&&s.includes("route.php"))return;if(!n.swaggerDocs&&s.includes("swagger-setup.js"))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/**/*.{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"),t="";s.backendOnly||(t='\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"> ${t}`:` <script src="https://cdn.tailwindcss.com"><\/script> ${t}`);const c=i.length>0?"\n":"";e=e.replace("</head>",`${i}${c} \x3c!-- Dynamic Head --\x3e\n <?= implode("\\n", $mainLayoutHead); ?>\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.backendOnly&&s.swaggerDocs&&t.push({srcDir:"/swagger-docs-layout.php",destDir:"/src/app/layout.php"}),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),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# 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"\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,n,t,i,c,o,r,a,l,p,d,u,h;const g=[];e.projectName||g.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.backendOnly||g.push({type:"toggle",name:"backendOnly",message:"Would you like to create a backend-only project?",initial:!1,active:"Yes",inactive:"No"});const m=()=>{process.exit(0)},f=await prompts(g,{onCancel:m}),y=[];f.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:m});return{projectName:f.projectName?String(f.projectName).trim().replace(/ /g,"-"):null!==(s=e.projectName)&&void 0!==s?s:"my-app",backendOnly:null!==(t=null!==(n=f.backendOnly)&&void 0!==n?n:e.backendOnly)&&void 0!==t&&t,swaggerDocs:null!==(c=null!==(i=w.swaggerDocs)&&void 0!==i?i:e.swaggerDocs)&&void 0!==c&&c,tailwindcss:null!==(r=null!==(o=w.tailwindcss)&&void 0!==o?o:e.tailwindcss)&&void 0!==r&&r,websocket:null!==(l=null!==(a=w.websocket)&&void 0!==a?a: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!==(h=null!==(u=w.docker)&&void 0!==u?u:e.docker)&&void 0!==h&&h}}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,o,r,a;try{const l=process.argv.slice(2);let p=l[0],d=null;if(p){const a={projectName:p,backendOnly:l.includes("--backend-only"),swaggerDocs:l.includes("--swagger-docs"),tailwindcss:l.includes("--tailwindcss"),websocket:l.includes("--websocket"),prisma:l.includes("--prisma"),docker:l.includes("--docker")};if(d=await getAnswer(a),null===d)return;const u=process.cwd(),h=path.join(u,"prisma-php.json"),g=readJsonFile(h);let m=[];null===(e=g.excludeFiles)||void 0===e||e.map((e=>{const s=path.join(u,e);fs.existsSync(s)&&m.push(s.replace(/\\/g,"/"))})),updateAnswer={projectName:p,backendOnly:null!==(s=null==d?void 0:d.backendOnly)&&void 0!==s&&s,swaggerDocs:null!==(n=null==d?void 0:d.swaggerDocs)&&void 0!==n&&n,tailwindcss:null!==(t=null==d?void 0:d.tailwindcss)&&void 0!==t&&t,websocket:null!==(i=null==d?void 0:d.websocket)&&void 0!==i&&i,prisma:null!==(c=null==d?void 0:d.prisma)&&void 0!==c&&c,docker:null!==(o=null==d?void 0:d.docker)&&void 0!==o&&o,isUpdate:!0,excludeFiles:null!==(r=g.excludeFiles)&&void 0!==r?r:[],excludeFilePath:null!=m?m:[],filePath:u}}else d=await getAnswer();if(null===d)return;const u=await fetchPackageVersion("create-prisma-php-app"),h=getInstalledPackageVersion("create-prisma-php-app");h?-1===compareVersions(h,u)&&(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 g=await fetchPackageVersion("browser-sync"),m=getInstalledPackageVersion("browser-sync");m?-1===compareVersions(m,g)&&(execSync("npm uninstall -g browser-sync",{stdio:"inherit"}),execSync("npm install -g browser-sync",{stdio:"inherit"})):execSync("npm install -g browser-sync",{stdio:"inherit"}),p||fs.mkdirSync(d.projectName);const f=process.cwd();let y=p?f:path.join(f,d.projectName);p||process.chdir(d.projectName);const w=["typescript","@types/node","ts-node","http-proxy-middleware@^3.0.0","chalk","npm-run-all"];d.swaggerDocs&&w.push("swagger-jsdoc"),d.tailwindcss&&w.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano"),d.websocket&&w.push("chokidar-cli"),d.prisma&&w.push("prisma","@prisma/client"),await installDependencies(y,w,!0),p||execSync("npx tsc --init",{stdio:"inherit"}),d.tailwindcss&&execSync("npx tailwindcss init -p",{stdio:"inherit"}),d.prisma&&(fs.existsSync(path.join(y,"prisma"))||execSync("npx prisma init",{stdio:"inherit"})),await createDirectoryStructure(y,d);const k=path.join(y,"public");if(fs.existsSync(k)||fs.mkdirSync(k),d.swaggerDocs){const e=path.join(y,"src","app","swagger-docs");fs.existsSync(e)||fs.mkdirSync(e,{recursive:!0}),execSync(`git clone https://github.com/TheSteelNinjaCode/prisma-php-swagger-docs.git ${e}`,{stdio:"inherit"})}if(null==updateAnswer?void 0:updateAnswer.isUpdate){const e=[];if(updateAnswer.backendOnly){nonBackendFiles.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.swaggerDocs){const s=path.join(y,"src","app","swagger-docs");fs.existsSync(s)&&fs.rmSync(s,{recursive:!0,force:!0});["swagger-setup.js"].forEach((e=>{const s=path.join(y,"settings",e);fs.existsSync(s)&&fs.unlinkSync(s)})),e.push("swagger-jsdoc")}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 S=y.replace(/\\/g,"\\"),b=bsConfigUrls(S),j=d.prisma?"src/Lib/Prisma/Classes":"",v={projectName:d.projectName,projectRootPath:S,phpEnvironment:"XAMPP",phpRootPathExe:"C:\\xampp\\php\\php.exe",phpGenerateClassPath:j,bsTarget:b.bsTarget,bsPathRewrite:b.bsPathRewrite,backendOnly:d.backendOnly,swaggerDocs:d.swaggerDocs,tailwindcss:d.tailwindcss,websocket:d.websocket,prisma:d.prisma,docker:d.docker,version:u,excludeFiles:null!==(a=null==updateAnswer?void 0:updateAnswer.excludeFiles)&&void 0!==a?a:[]};fs.writeFileSync(path.join(y,"prisma-php.json"),JSON.stringify(v,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;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}}
3
+ async function main() {
4
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
5
+ try {
6
+ const args = process.argv.slice(2);
7
+ let projectName = args[0];
8
+ let answer = null;
9
+ if (projectName) {
10
+ let useBackendOnly = args.includes("--backend-only");
11
+ let useSwaggerDocs = args.includes("--swagger-docs");
12
+ let useTailwind = args.includes("--tailwindcss");
13
+ let useWebsocket = args.includes("--websocket");
14
+ let usePrisma = args.includes("--prisma");
15
+ let useDocker = args.includes("--docker");
16
+ const predefinedAnswers = {
17
+ projectName,
18
+ backendOnly: useBackendOnly,
19
+ swaggerDocs: useSwaggerDocs,
20
+ tailwindcss: useTailwind,
21
+ websocket: useWebsocket,
22
+ prisma: usePrisma,
23
+ docker: useDocker,
24
+ };
25
+ answer = await getAnswer(predefinedAnswers);
26
+ if (answer === null) {
27
+ console.log(chalk.red("Installation cancelled."));
28
+ return;
29
+ }
30
+ const currentDir = process.cwd();
31
+ const configPath = path.join(currentDir, "prisma-php.json");
32
+ const localSettings = readJsonFile(configPath);
33
+ 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
+ });
41
+ updateAnswer = {
42
+ 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,
83
+ isUpdate: true,
84
+ excludeFiles:
85
+ (_h = localSettings.excludeFiles) !== null && _h !== void 0 ? _h : [],
86
+ excludeFilePath:
87
+ excludeFiles !== null && excludeFiles !== void 0 ? excludeFiles : [],
88
+ filePath: currentDir,
89
+ };
90
+ } else {
91
+ answer = await getAnswer();
92
+ }
93
+ if (answer === null) {
94
+ console.warn(chalk.red("Installation cancelled."));
95
+ return;
96
+ }
97
+ const latestVersionOfCreatePrismaPhpApp = await fetchPackageVersion(
98
+ "create-prisma-php-app"
99
+ );
100
+ const isCreatePrismaPhpAppInstalled = getInstalledPackageVersion(
101
+ "create-prisma-php-app"
102
+ );
103
+ if (isCreatePrismaPhpAppInstalled) {
104
+ if (
105
+ compareVersions(
106
+ isCreatePrismaPhpAppInstalled,
107
+ latestVersionOfCreatePrismaPhpApp
108
+ ) === -1
109
+ ) {
110
+ execSync(`npm uninstall -g create-prisma-php-app`, {
111
+ stdio: "inherit",
112
+ });
113
+ execSync(`npm install -g create-prisma-php-app`, {
114
+ stdio: "inherit",
115
+ });
116
+ }
117
+ } else {
118
+ execSync("npm install -g create-prisma-php-app", { stdio: "inherit" });
119
+ }
120
+ // Create the project directory
121
+ if (!projectName) fs.mkdirSync(answer.projectName);
122
+ const currentDir = process.cwd();
123
+ let projectPath = projectName
124
+ ? currentDir
125
+ : path.join(currentDir, answer.projectName);
126
+ if (!projectName) process.chdir(answer.projectName);
127
+ const dependencies = [
128
+ "typescript",
129
+ "@types/node",
130
+ "ts-node",
131
+ "http-proxy-middleware",
132
+ "chalk",
133
+ "npm-run-all",
134
+ "browser-sync",
135
+ ];
136
+ if (answer.swaggerDocs) {
137
+ dependencies.push("swagger-jsdoc");
138
+ }
139
+ if (answer.tailwindcss) {
140
+ dependencies.push(
141
+ "tailwindcss",
142
+ "autoprefixer",
143
+ "postcss",
144
+ "postcss-cli",
145
+ "cssnano"
146
+ );
147
+ }
148
+ if (answer.websocket) {
149
+ dependencies.push("chokidar-cli");
150
+ }
151
+ if (answer.prisma) {
152
+ dependencies.push("prisma", "@prisma/client");
153
+ }
154
+ await installDependencies(projectPath, dependencies, true);
155
+ if (!projectName) {
156
+ execSync(`npx tsc --init`, { stdio: "inherit" });
157
+ }
158
+ if (answer.tailwindcss)
159
+ execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
160
+ if (answer.prisma) {
161
+ if (!fs.existsSync(path.join(projectPath, "prisma")))
162
+ execSync(`npx prisma init`, { stdio: "inherit" });
163
+ }
164
+ await createDirectoryStructure(projectPath, answer);
165
+ const publicDirPath = path.join(projectPath, "public");
166
+ if (!fs.existsSync(publicDirPath)) {
167
+ fs.mkdirSync(publicDirPath);
168
+ }
169
+ if (answer.swaggerDocs) {
170
+ const swaggerDocsPath = path.join(
171
+ projectPath,
172
+ "src",
173
+ "app",
174
+ "swagger-docs"
175
+ );
176
+ // Check if the directory exists, if not, create it
177
+ if (!fs.existsSync(swaggerDocsPath)) {
178
+ fs.mkdirSync(swaggerDocsPath, { recursive: true }); // 'recursive: true' creates parent directories if they don't exist
179
+ }
180
+ // Clone the Git repository into the swagger-docs directory
181
+ execSync(
182
+ `git clone https://github.com/TheSteelNinjaCode/prisma-php-swagger-docs.git ${swaggerDocsPath}`,
183
+ { stdio: "inherit" }
184
+ );
185
+ }
186
+ if (
187
+ updateAnswer === null || updateAnswer === void 0
188
+ ? void 0
189
+ : updateAnswer.isUpdate
190
+ ) {
191
+ const updateUninstallDependencies = [];
192
+ if (updateAnswer.backendOnly) {
193
+ nonBackendFiles.forEach((file) => {
194
+ const filePath = path.join(projectPath, "src", "app", file);
195
+ if (fs.existsSync(filePath)) {
196
+ fs.unlinkSync(filePath); // Delete each file if it exists
197
+ console.log(`${file} was deleted successfully.`);
198
+ } else {
199
+ console.log(`${file} does not exist.`);
200
+ }
201
+ });
202
+ const backendOnlyFolders = ["js", "css"];
203
+ backendOnlyFolders.forEach((folder) => {
204
+ const folderPath = path.join(projectPath, "src", "app", folder);
205
+ if (fs.existsSync(folderPath)) {
206
+ fs.rmSync(folderPath, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
207
+ console.log(`${folder} was deleted successfully.`);
208
+ } else {
209
+ console.log(`${folder} does not exist.`);
210
+ }
211
+ });
212
+ }
213
+ if (!updateAnswer.swaggerDocs) {
214
+ const swaggerDocsFolder = path.join(
215
+ projectPath,
216
+ "src",
217
+ "app",
218
+ "swagger-docs"
219
+ );
220
+ if (fs.existsSync(swaggerDocsFolder)) {
221
+ fs.rmSync(swaggerDocsFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
222
+ console.log(`swagger-docs was deleted successfully.`);
223
+ }
224
+ const swaggerFiles = ["swagger-setup.js"];
225
+ swaggerFiles.forEach((file) => {
226
+ const filePath = path.join(projectPath, "settings", file);
227
+ if (fs.existsSync(filePath)) {
228
+ fs.unlinkSync(filePath); // Delete each file if it exists
229
+ console.log(`${file} was deleted successfully.`);
230
+ } else {
231
+ console.log(`${file} does not exist.`);
232
+ }
233
+ });
234
+ updateUninstallDependencies.push("swagger-jsdoc");
235
+ }
236
+ if (!updateAnswer.tailwindcss) {
237
+ const tailwindFiles = ["postcss.config.js", "tailwind.config.js"];
238
+ tailwindFiles.forEach((file) => {
239
+ const filePath = path.join(projectPath, file);
240
+ if (fs.existsSync(filePath)) {
241
+ fs.unlinkSync(filePath); // Delete each file if it exists
242
+ console.log(`${file} was deleted successfully.`);
243
+ } else {
244
+ console.log(`${file} does not exist.`);
245
+ }
246
+ });
247
+ updateUninstallDependencies.push(
248
+ "tailwindcss",
249
+ "autoprefixer",
250
+ "postcss",
251
+ "postcss-cli",
252
+ "cssnano"
253
+ );
254
+ }
255
+ if (!updateAnswer.websocket) {
256
+ const websocketFiles = [
257
+ "restart-websocket.js",
258
+ "restart-websocket.bat",
259
+ ];
260
+ websocketFiles.forEach((file) => {
261
+ const filePath = path.join(projectPath, "settings", file);
262
+ if (fs.existsSync(filePath)) {
263
+ fs.unlinkSync(filePath); // Delete each file if it exists
264
+ console.log(`${file} was deleted successfully.`);
265
+ } else {
266
+ console.log(`${file} does not exist.`);
267
+ }
268
+ });
269
+ const websocketFolder = path.join(
270
+ projectPath,
271
+ "src",
272
+ "Lib",
273
+ "Websocket"
274
+ );
275
+ if (fs.existsSync(websocketFolder)) {
276
+ fs.rmSync(websocketFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
277
+ console.log(`Websocket folder was deleted successfully.`);
278
+ }
279
+ updateUninstallDependencies.push("chokidar-cli");
280
+ }
281
+ if (!updateAnswer.prisma) {
282
+ updateUninstallDependencies.push("prisma", "@prisma/client");
283
+ }
284
+ if (!updateAnswer.docker) {
285
+ const dockerFiles = [
286
+ ".dockerignore",
287
+ "docker-compose.yml",
288
+ "Dockerfile",
289
+ "apache.conf",
290
+ ];
291
+ dockerFiles.forEach((file) => {
292
+ const filePath = path.join(projectPath, file);
293
+ if (fs.existsSync(filePath)) {
294
+ fs.unlinkSync(filePath); // Delete each file if it exists
295
+ console.log(`${file} was deleted successfully.`);
296
+ } else {
297
+ console.log(`${file} does not exist.`);
298
+ }
299
+ });
300
+ }
301
+ if (updateUninstallDependencies.length > 0) {
302
+ await uninstallDependencies(
303
+ projectPath,
304
+ updateUninstallDependencies,
305
+ true
306
+ );
307
+ }
308
+ }
309
+ const projectPathModified = projectPath.replace(/\\/g, "\\");
310
+ const bsConfig = bsConfigUrls(projectPathModified);
311
+ const phpGenerateClassPath = answer.prisma ? "src/Lib/Prisma/Classes" : "";
312
+ const prismaPhpConfig = {
313
+ projectName: answer.projectName,
314
+ projectRootPath: projectPathModified,
315
+ phpEnvironment: "XAMPP",
316
+ phpRootPathExe: "C:\\xampp\\php\\php.exe",
317
+ phpGenerateClassPath,
318
+ bsTarget: bsConfig.bsTarget,
319
+ bsPathRewrite: bsConfig.bsPathRewrite,
320
+ backendOnly: answer.backendOnly,
321
+ swaggerDocs: answer.swaggerDocs,
322
+ tailwindcss: answer.tailwindcss,
323
+ websocket: answer.websocket,
324
+ prisma: answer.prisma,
325
+ docker: answer.docker,
326
+ ngrok: false,
327
+ 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
+ : [],
335
+ };
336
+ fs.writeFileSync(
337
+ path.join(projectPath, "prisma-php.json"),
338
+ JSON.stringify(prismaPhpConfig, null, 2),
339
+ { flag: "w" }
340
+ );
341
+ if (
342
+ updateAnswer === null || updateAnswer === void 0
343
+ ? void 0
344
+ : updateAnswer.isUpdate
345
+ ) {
346
+ execSync(
347
+ `C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update`,
348
+ {
349
+ stdio: "inherit",
350
+ }
351
+ );
352
+ } else {
353
+ execSync(
354
+ `C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install`,
355
+ {
356
+ stdio: "inherit",
357
+ }
358
+ );
359
+ }
360
+ console.log(
361
+ `${chalk.green("Success!")} Prisma PHP project successfully created in ${
362
+ answer.projectName
363
+ }!`
364
+ );
365
+ } catch (error) {
366
+ console.error("Error while creating the project:", error);
367
+ process.exit(1);
368
+ }
369
+ }
370
+ main();
@@ -0,0 +1,75 @@
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
+ });
@@ -0,0 +1,43 @@
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
+ };