create-prisma-php-app 2.3.31 β†’ 2.3.33

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.
@@ -27,3 +27,7 @@ composer.lock
27
27
 
28
28
  # Backup and temporary files
29
29
  *.swp
30
+
31
+ # Prisma PHP settings files
32
+ .pphp/
33
+ caches/
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{execSync}from"child_process";import fs from"fs";import{fileURLToPath}from"url";import path from"path";import chalk from"chalk";import prompts from"prompts";import https from"https";import{randomBytes}from"crypto";const __filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename);let updateAnswer=null;const nonBackendFiles=["favicon.ico","\\src\\app\\index.php","metadata.php","not-found.php","error.php"],dockerFiles=[".dockerignore","docker-compose.yml","Dockerfile","apache.conf"];function bsConfigUrls(e){const s=e.indexOf("\\htdocs\\");if(-1===s)return{bsTarget:"",bsPathRewrite:{}};const t=e.substring(0,s+"\\htdocs\\".length).replace(/\\/g,"\\\\"),n=e.replace(new RegExp(`^${t}`),"").replace(/\\/g,"/");let c=`http://localhost/${n}`;c=c.endsWith("/")?c.slice(0,-1):c;const o=c.replace(/(?<!:)(\/\/+)/g,"/"),i=n.replace(/\/\/+/g,"/");return{bsTarget:`${o}/`,bsPathRewrite:{"^/":`/${i.startsWith("/")?i.substring(1):i}/`}}}async function updatePackageJson(e,s){const t=path.join(e,"package.json");if(checkExcludeFiles(t))return;const n=JSON.parse(fs.readFileSync(t,"utf8"));n.scripts={...n.scripts,projectName:"tsx settings/project-name.ts"};let c=[];if(s.tailwindcss&&(n.scripts={...n.scripts,tailwind:"postcss src/app/css/tailwind.css -o src/app/css/styles.css --watch"},c.push("tailwind")),s.websocket&&(n.scripts={...n.scripts,websocket:"tsx settings/restart-websocket.ts"},c.push("websocket")),s.docker&&(n.scripts={...n.scripts,docker:"docker-compose up"},c.push("docker")),s.swaggerDocs){const e=s.prisma?"tsx settings/auto-swagger-docs.ts":"tsx settings/swagger-config.ts";n.scripts={...n.scripts,"create-swagger-docs":e}}let o={...n.scripts};o.browserSync="tsx settings/bs-config.ts",o.dev=`npm-run-all projectName -p browserSync ${c.join(" ")}`,n.scripts=o,n.type="module",fs.writeFileSync(t,JSON.stringify(n,null,2))}async function updateComposerJson(e){const s=path.join(e,"composer.json");if(checkExcludeFiles(s))return;let t;if(fs.existsSync(s)){{const e=fs.readFileSync(s,"utf8");t=JSON.parse(e)}t.autoload={"psr-4":{"":"src/"}},t.version="1.0.0",fs.writeFileSync(s,JSON.stringify(t,null,2))}}async function updateIndexJsForWebSocket(e,s){if(!s.websocket)return;const t=path.join(e,"src","app","js","index.js");if(checkExcludeFiles(t))return;let n=fs.readFileSync(t,"utf8");n+='\n// WebSocket initialization\nvar ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,n,"utf8")}function generateAuthSecret(){return randomBytes(33).toString("base64")}function generateHexEncodedKey(e=16){return randomBytes(e).toString("hex")}function copyRecursiveSync(e,s,t){const n=fs.existsSync(e),c=n&&fs.statSync(e);if(n&&c&&c.isDirectory()){const n=s.toLowerCase();if(!t.websocket&&n.includes("src\\lib\\websocket"))return;if(t.backendOnly&&n.includes("src\\app\\js")||t.backendOnly&&n.includes("src\\app\\css")||t.backendOnly&&n.includes("src\\app\\assets"))return;if(!t.swaggerDocs&&n.includes("src\\app\\swagger-docs"))return;const c=s.replace(/\\/g,"/");if(updateAnswer?.excludeFilePath?.includes(c))return;fs.existsSync(s)||fs.mkdirSync(s,{recursive:!0}),fs.readdirSync(e).forEach((n=>{copyRecursiveSync(path.join(e,n),path.join(s,n),t)}))}else{if(checkExcludeFiles(s))return;if(!t.tailwindcss&&(s.includes("tailwind.css")||s.includes("styles.css")))return;if(!t.websocket&&(s.includes("restart-websocket.ts")||s.includes("restart-websocket.bat")))return;if(!t.docker&&dockerFiles.some((e=>s.includes(e))))return;if(t.backendOnly&&nonBackendFiles.some((e=>s.includes(e))))return;if(!t.backendOnly&&s.includes("route.php"))return;if(t.backendOnly&&!t.swaggerDocs&&s.includes("layout.php"))return;if(!t.swaggerDocs&&s.includes("swagger-config.ts"))return;if(t.tailwindcss&&s.includes("index.css"))return;if((!t.swaggerDocs||!t.prisma)&&(s.includes("auto-swagger-docs.ts")||s.includes("prisma-schema-config.json")))return;fs.copyFileSync(e,s,0)}}async function executeCopy(e,s,t){s.forEach((({src:s,dest:n})=>{copyRecursiveSync(path.join(__dirname,s),path.join(e,n),t)}))}function modifyPostcssConfig(e){const s=path.join(e,"postcss.config.js");if(checkExcludeFiles(s))return;fs.writeFileSync(s,'export default {\n plugins: {\n "@tailwindcss/postcss": {},\n cssnano: {},\n },\n};',{flag:"w"})}function modifyLayoutPHP(e,s){const t=path.join(e,"src","app","layout.php");if(!checkExcludeFiles(t))try{let e=fs.readFileSync(t,"utf8"),n="";s.backendOnly||(s.tailwindcss||(n='\n <link href="<?= Request::baseUrl; ?>/css/index.css" rel="stylesheet" />'),n+='\n <script src="<?= Request::baseUrl; ?>/js/morphdom-umd.min.js"><\/script>\n <script src="<?= Request::baseUrl; ?>/js/json5.min.js"><\/script>\n <script src="<?= Request::baseUrl; ?>/js/index.js"><\/script>');let c="";s.backendOnly||(c=s.tailwindcss?` <link href="<?= Request::baseUrl; ?>/css/styles.css" rel="stylesheet" /> ${n}`:n),e=e.replace("</head>",`${c}\n</head>`),fs.writeFileSync(t,e,{flag:"w"})}catch(e){}}async function createOrUpdateEnvFile(e,s){const t=path.join(e,".env");checkExcludeFiles(t)||fs.writeFileSync(t,s,{flag:"w"})}function checkExcludeFiles(e){return!!updateAnswer?.isUpdate&&(updateAnswer?.excludeFilePath?.includes(e.replace(/\\/g,"/"))??!1)}async function createDirectoryStructure(e,s){const t=[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/tsconfig.json",dest:"/tsconfig.json"},{src:"/app-gitignore",dest:"/.gitignore"}];s.tailwindcss&&t.push({src:"/postcss.config.js",dest:"/postcss.config.js"});const n=[{src:"/settings",dest:"/settings"},{src:"/src",dest:"/src"}];s.docker&&n.push({src:"/.dockerignore",dest:"/.dockerignore"},{src:"/docker-compose.yml",dest:"/docker-compose.yml"},{src:"/Dockerfile",dest:"/Dockerfile"},{src:"/apache.conf",dest:"/apache.conf"}),t.forEach((({src:s,dest:t})=>{const n=path.join(__dirname,s),c=path.join(e,t);if(checkExcludeFiles(c))return;const o=fs.readFileSync(n,"utf8");fs.writeFileSync(c,o,{flag:"w"})})),await executeCopy(e,n,s),await updatePackageJson(e,s),await updateComposerJson(e),s.backendOnly||await updateIndexJsForWebSocket(e,s),s.tailwindcss&&modifyPostcssConfig(e),(s.tailwindcss||!s.backendOnly||s.swaggerDocs)&&modifyLayoutPHP(e,s);const c=generateAuthSecret(),o=generateHexEncodedKey(),i=`# Prisma PHP Auth Secret Key\nAUTH_SECRET="${c}"\nAUTH_COOKIE_NAME="${generateHexEncodedKey(8)}"\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"\n\n# APP CACHE ENABLED - Set to true to enable caching - Default is false\nCACHE_ENABLED="false"\n# APP CACHE TTL - Set the cache time to live in seconds - Default is 600 seconds (10 minutes)\nCACHE_TTL="600"\n\n# LOCAL STORAGE KEY - Define a custom key for local storage.\n# If not set, it defaults to "pphp_local_store_59e13".\n# Spaces in the value will be replaced with underscores, and the key will be converted to lowercase automatically.\nLOCALSTORE_KEY="${o}"`;if(s.prisma){const s=`${'# Environment variables declared in this file are automatically made available to Prisma.\n# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema\n\n# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.\n# See the documentation for all the connection string options: https://pris.ly/d/connection-strings\n\nDATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"'}\n\n${i}`;await createOrUpdateEnvFile(e,s)}else await createOrUpdateEnvFile(e,i)}async function getAnswer(e={}){const s=[];e.projectName||s.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.backendOnly||s.push({type:"toggle",name:"backendOnly",message:`Would you like to create a ${chalk.blue("backend-only project")}?`,initial:!1,active:"Yes",inactive:"No"});const t=()=>{process.exit(0)},n=await prompts(s,{onCancel:t}),c=[];n.backendOnly||e.backendOnly?(e.swaggerDocs||c.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),e.websocket||c.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!0,active:"Yes",inactive:"No"}),e.prisma||c.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!0,active:"Yes",inactive:"No"}),e.docker||c.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"})):(e.swaggerDocs||c.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),e.tailwindcss||c.push({type:"toggle",name:"tailwindcss",message:`Would you like to use ${chalk.blue("Tailwind CSS")}?`,initial:!1,active:"Yes",inactive:"No"}),e.websocket||c.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!1,active:"Yes",inactive:"No"}),e.prisma||c.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!1,active:"Yes",inactive:"No"}),e.docker||c.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"}));const o=await prompts(c,{onCancel:t});return{projectName:n.projectName?String(n.projectName).trim().replace(/ /g,"-"):e.projectName??"my-app",backendOnly:n.backendOnly??e.backendOnly??!1,swaggerDocs:o.swaggerDocs??e.swaggerDocs??!1,tailwindcss:o.tailwindcss??e.tailwindcss??!1,websocket:o.websocket??e.websocket??!1,prisma:o.prisma??e.prisma??!1,docker:o.docker??e.docker??!1}}async function uninstallNpmDependencies(e,s,t=!1){s.forEach((e=>{}));const n=`npm uninstall ${t?"--save-dev":"--save"} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}async function uninstallComposerDependencies(e,s){s.forEach((e=>{}));const t=`C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar remove ${s.join(" ")}`;execSync(t,{stdio:"inherit",cwd:e})}function fetchPackageVersion(e){return new Promise(((s,t)=>{https.get(`https://registry.npmjs.org/${e}`,(e=>{let n="";e.on("data",(e=>n+=e)),e.on("end",(()=>{try{const e=JSON.parse(n);s(e["dist-tags"].latest)}catch(e){t(new Error("Failed to parse JSON response"))}}))})).on("error",(e=>t(e)))}))}const readJsonFile=e=>{const s=fs.readFileSync(e,"utf8");return JSON.parse(s)};function compareVersions(e,s){const t=e.split(".").map(Number),n=s.split(".").map(Number);for(let e=0;e<t.length;e++){if(t[e]>n[e])return 1;if(t[e]<n[e])return-1}return 0}function getInstalledPackageVersion(e){try{const s=execSync(`npm list -g ${e} --depth=0`).toString().match(new RegExp(`${e}@(\\d+\\.\\d+\\.\\d+)`));return s?s[1]:null}catch(e){return null}}
2
+ import{execSync}from"child_process";import fs from"fs";import{fileURLToPath}from"url";import path from"path";import chalk from"chalk";import prompts from"prompts";import https from"https";import{randomBytes}from"crypto";const __filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename);let updateAnswer=null;const nonBackendFiles=["favicon.ico","\\src\\app\\index.php","metadata.php","not-found.php","error.php"],dockerFiles=[".dockerignore","docker-compose.yml","Dockerfile","apache.conf"];function bsConfigUrls(e){const s=e.indexOf("\\htdocs\\");if(-1===s)return{bsTarget:"",bsPathRewrite:{}};const t=e.substring(0,s+"\\htdocs\\".length).replace(/\\/g,"\\\\"),n=e.replace(new RegExp(`^${t}`),"").replace(/\\/g,"/");let c=`http://localhost/${n}`;c=c.endsWith("/")?c.slice(0,-1):c;const 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=[];if(s.tailwindcss&&(n.scripts={...n.scripts,tailwind:"postcss src/app/css/tailwind.css -o src/app/css/styles.css --watch","tailwind:build":"postcss src/app/css/tailwind.css -o src/app/css/styles.css"},c.push("tailwind")),s.websocket&&(n.scripts={...n.scripts,websocket:"tsx settings/restart-websocket.ts"},c.push("websocket")),s.docker&&(n.scripts={...n.scripts,docker:"docker-compose up"},c.push("docker")),s.swaggerDocs){const e=s.prisma?"tsx settings/auto-swagger-docs.ts":"tsx settings/swagger-config.ts";n.scripts={...n.scripts,"create-swagger-docs":e}}let i={...n.scripts};i.browserSync="tsx settings/bs-config.ts",i["browserSync:build"]="tsx settings/build.ts",i.dev=`npm-run-all projectName -p browserSync ${c.join(" ")}`,i.build=`npm-run-all projectName -p${s.tailwindcss?" tailwind:build":""} browserSync:build`,n.scripts=i,n.type="module",fs.writeFileSync(t,JSON.stringify(n,null,2))}async function updateComposerJson(e){const s=path.join(e,"composer.json");if(checkExcludeFiles(s))return;let t;if(fs.existsSync(s)){{const e=fs.readFileSync(s,"utf8");t=JSON.parse(e)}t.autoload={"psr-4":{"":"src/"}},t.version="1.0.0",fs.writeFileSync(s,JSON.stringify(t,null,2))}}async function updateIndexJsForWebSocket(e,s){if(!s.websocket)return;const t=path.join(e,"src","app","js","index.js");if(checkExcludeFiles(t))return;let n=fs.readFileSync(t,"utf8");n+='\n// WebSocket initialization\nvar ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,n,"utf8")}function generateAuthSecret(){return randomBytes(33).toString("base64")}function generateHexEncodedKey(e=16){return randomBytes(e).toString("hex")}function copyRecursiveSync(e,s,t){const n=fs.existsSync(e),c=n&&fs.statSync(e);if(n&&c&&c.isDirectory()){const n=s.toLowerCase();if(!t.websocket&&n.includes("src\\lib\\websocket"))return;if(t.backendOnly&&n.includes("src\\app\\js")||t.backendOnly&&n.includes("src\\app\\css")||t.backendOnly&&n.includes("src\\app\\assets"))return;if(!t.swaggerDocs&&n.includes("src\\app\\swagger-docs"))return;const c=s.replace(/\\/g,"/");if(updateAnswer?.excludeFilePath?.includes(c))return;fs.existsSync(s)||fs.mkdirSync(s,{recursive:!0}),fs.readdirSync(e).forEach((n=>{copyRecursiveSync(path.join(e,n),path.join(s,n),t)}))}else{if(checkExcludeFiles(s))return;if(!t.tailwindcss&&(s.includes("tailwind.css")||s.includes("styles.css")))return;if(!t.websocket&&(s.includes("restart-websocket.ts")||s.includes("restart-websocket.bat")))return;if(!t.docker&&dockerFiles.some((e=>s.includes(e))))return;if(t.backendOnly&&nonBackendFiles.some((e=>s.includes(e))))return;if(!t.backendOnly&&s.includes("route.php"))return;if(t.backendOnly&&!t.swaggerDocs&&s.includes("layout.php"))return;if(!t.swaggerDocs&&s.includes("swagger-config.ts"))return;if(t.tailwindcss&&s.includes("index.css"))return;if((!t.swaggerDocs||!t.prisma)&&(s.includes("auto-swagger-docs.ts")||s.includes("prisma-schema-config.json")))return;fs.copyFileSync(e,s,0)}}async function executeCopy(e,s,t){s.forEach((({src:s,dest:n})=>{copyRecursiveSync(path.join(__dirname,s),path.join(e,n),t)}))}function modifyPostcssConfig(e){const s=path.join(e,"postcss.config.js");if(checkExcludeFiles(s))return;fs.writeFileSync(s,'export default {\n plugins: {\n "@tailwindcss/postcss": {},\n cssnano: {},\n },\n};',{flag:"w"})}function modifyLayoutPHP(e,s){const t=path.join(e,"src","app","layout.php");if(!checkExcludeFiles(t))try{let e=fs.readFileSync(t,"utf8"),n="";s.backendOnly||(s.tailwindcss||(n='\n <link href="<?= Request::baseUrl; ?>/css/index.css" rel="stylesheet" />'),n+='\n <script src="<?= Request::baseUrl; ?>/js/morphdom-umd.min.js"><\/script>\n <script src="<?= Request::baseUrl; ?>/js/json5.min.js"><\/script>\n <script src="<?= Request::baseUrl; ?>/js/index.js"><\/script>');let c="";s.backendOnly||(c=s.tailwindcss?` <link href="<?= Request::baseUrl; ?>/css/styles.css" rel="stylesheet" /> ${n}`:n),e=e.replace("</head>",`${c}\n</head>`),fs.writeFileSync(t,e,{flag:"w"})}catch(e){}}async function createOrUpdateEnvFile(e,s){const t=path.join(e,".env");checkExcludeFiles(t)||fs.writeFileSync(t,s,{flag:"w"})}function checkExcludeFiles(e){return!!updateAnswer?.isUpdate&&(updateAnswer?.excludeFilePath?.includes(e.replace(/\\/g,"/"))??!1)}async function createDirectoryStructure(e,s){const t=[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/tsconfig.json",dest:"/tsconfig.json"},{src:"/app-gitignore",dest:"/.gitignore"}];s.tailwindcss&&t.push({src:"/postcss.config.js",dest:"/postcss.config.js"});const n=[{src:"/settings",dest:"/settings"},{src:"/src",dest:"/src"}];s.docker&&n.push({src:"/.dockerignore",dest:"/.dockerignore"},{src:"/docker-compose.yml",dest:"/docker-compose.yml"},{src:"/Dockerfile",dest:"/Dockerfile"},{src:"/apache.conf",dest:"/apache.conf"}),t.forEach((({src:s,dest:t})=>{const n=path.join(__dirname,s),c=path.join(e,t);if(checkExcludeFiles(c))return;const i=fs.readFileSync(n,"utf8");fs.writeFileSync(c,i,{flag:"w"})})),await executeCopy(e,n,s),await updatePackageJson(e,s),await updateComposerJson(e),s.backendOnly||await updateIndexJsForWebSocket(e,s),s.tailwindcss&&modifyPostcssConfig(e),(s.tailwindcss||!s.backendOnly||s.swaggerDocs)&&modifyLayoutPHP(e,s);const c=generateAuthSecret(),i=generateHexEncodedKey(),o=`# Prisma PHP Auth Secret Key\nAUTH_SECRET="${c}"\nAUTH_COOKIE_NAME="${generateHexEncodedKey(8)}"\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"\n\n# APP CACHE ENABLED - Set to true to enable caching - Default is false\nCACHE_ENABLED="false"\n# APP CACHE TTL - Set the cache time to live in seconds - Default is 600 seconds (10 minutes)\nCACHE_TTL="600"\n\n# LOCAL STORAGE KEY - Define a custom key for local storage.\n# If not set, it defaults to "pphp_local_store_59e13".\n# Spaces in the value will be replaced with underscores, and the key will be converted to lowercase automatically.\nLOCALSTORE_KEY="${i}"`;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${o}`;await createOrUpdateEnvFile(e,s)}else await createOrUpdateEnvFile(e,o)}async function getAnswer(e={}){const s=[];e.projectName||s.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.backendOnly||s.push({type:"toggle",name:"backendOnly",message:`Would you like to create a ${chalk.blue("backend-only project")}?`,initial:!1,active:"Yes",inactive:"No"});const t=()=>{process.exit(0)},n=await prompts(s,{onCancel:t}),c=[];n.backendOnly||e.backendOnly?(e.swaggerDocs||c.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),e.websocket||c.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!0,active:"Yes",inactive:"No"}),e.prisma||c.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!0,active:"Yes",inactive:"No"}),e.docker||c.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"})):(e.swaggerDocs||c.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),e.tailwindcss||c.push({type:"toggle",name:"tailwindcss",message:`Would you like to use ${chalk.blue("Tailwind CSS")}?`,initial:!1,active:"Yes",inactive:"No"}),e.websocket||c.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!1,active:"Yes",inactive:"No"}),e.prisma||c.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!1,active:"Yes",inactive:"No"}),e.docker||c.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"}));const 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 uninstallNpmDependencies(e,s,t=!1){s.forEach((e=>{}));const n=`npm uninstall ${t?"--save-dev":"--save"} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}async function uninstallComposerDependencies(e,s){s.forEach((e=>{}));const t=`C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar remove ${s.join(" ")}`;execSync(t,{stdio:"inherit",cwd:e})}function fetchPackageVersion(e){return new Promise(((s,t)=>{https.get(`https://registry.npmjs.org/${e}`,(e=>{let n="";e.on("data",(e=>n+=e)),e.on("end",(()=>{try{const e=JSON.parse(n);s(e["dist-tags"].latest)}catch(e){t(new Error("Failed to parse JSON response"))}}))})).on("error",(e=>t(e)))}))}const readJsonFile=e=>{const s=fs.readFileSync(e,"utf8");return JSON.parse(s)};function compareVersions(e,s){const t=e.split(".").map(Number),n=s.split(".").map(Number);for(let e=0;e<t.length;e++){if(t[e]>n[e])return 1;if(t[e]<n[e])return-1}return 0}function getInstalledPackageVersion(e){try{const s=execSync(`npm list -g ${e} --depth=0`).toString().match(new RegExp(`${e}@(\\d+\\.\\d+\\.\\d+)`));return s?s[1]:null}catch(e){return null}}
3
3
  /**
4
4
  * Install dependencies in the specified directory.
5
5
  * @param {string} baseDir - The base directory where to install the dependencies.
@@ -0,0 +1,69 @@
1
+ import { writeFileSync } from "fs";
2
+ import browserSync from "browser-sync";
3
+ import { getFileMeta } from "./utils.js";
4
+ import { join } from "path";
5
+ import { generateFileListJson } from "./files-list.js";
6
+ import { updateAllClassLogs } from "./class-log.js";
7
+ import {
8
+ analyzeImportsInFile,
9
+ getAllPhpFiles,
10
+ SRC_DIR,
11
+ updateComponentImports,
12
+ } from "./class-imports";
13
+ import { checkComponentImports } from "./component-import-checker";
14
+
15
+ const { __dirname } = getFileMeta();
16
+
17
+ (async () => {
18
+ console.log("πŸ“¦ Generating files for production...");
19
+
20
+ // Run all watchers logic ONCE
21
+ await generateFileListJson();
22
+ await updateAllClassLogs();
23
+ await updateComponentImports();
24
+
25
+ const phpFiles = await getAllPhpFiles(SRC_DIR + "/app");
26
+ for (const file of phpFiles) {
27
+ const fileImports = await analyzeImportsInFile(file);
28
+ await checkComponentImports(file, fileImports);
29
+ }
30
+
31
+ // Start BrowserSync just to extract URLs (and shut down immediately)
32
+ const bs = browserSync.create();
33
+ bs.init(
34
+ {
35
+ proxy: "http://localhost:3000",
36
+ middleware: [],
37
+ notify: false,
38
+ open: false,
39
+ ghostMode: false,
40
+ codeSync: false,
41
+ watchOptions: {
42
+ usePolling: true,
43
+ interval: 1000,
44
+ },
45
+ },
46
+ (err, bsInstance) => {
47
+ if (err) {
48
+ console.error("❌ BrowserSync failed:", err);
49
+ process.exit(1);
50
+ }
51
+
52
+ const options = bsInstance.getOption("urls");
53
+ const urls = {
54
+ local: options.get("local"),
55
+ external: options.get("external"),
56
+ ui: options.get("ui"),
57
+ uiExternal: options.get("ui-external"),
58
+ };
59
+
60
+ writeFileSync(
61
+ join(__dirname, "bs-config.json"),
62
+ JSON.stringify(urls, null, 2)
63
+ );
64
+
65
+ console.log("βœ… Generating files for production completed.");
66
+ bs.exit(); // Shut down immediately
67
+ }
68
+ );
69
+ })();
@@ -30,6 +30,7 @@ export async function checkComponentImports(
30
30
  string,
31
31
  | Array<{ className: string; filePath: string; importer?: string }>
32
32
  | { className: string; filePath: string; importer?: string }
33
+ | string
33
34
  >
34
35
  ) {
35
36
  const code = await fs.readFile(filePath, "utf-8");
@@ -51,7 +52,12 @@ export async function checkComponentImports(
51
52
  }> = [];
52
53
  if (Array.isArray(rawMapping)) {
53
54
  mappings = rawMapping;
54
- } else if (rawMapping) {
55
+ } else if (
56
+ rawMapping &&
57
+ typeof rawMapping === "object" &&
58
+ "className" in rawMapping &&
59
+ "filePath" in rawMapping
60
+ ) {
55
61
  mappings = [rawMapping];
56
62
  }
57
63
 
@@ -1 +1 @@
1
- (()=>{const e=EventTarget.prototype.addEventListener,t=EventTarget.prototype.removeEventListener,n=new Map;EventTarget.prototype.addEventListener=function(t,s,r){n.has(this)||n.set(this,new Map);const i=n.get(this).get(t)||new Set;i.add(s),n.get(this).set(t,i),e.call(this,t,s,r)},EventTarget.prototype.removeEventListener=function(e,s,r){if(n.has(this)&&n.get(this).has(e)){const t=n.get(this).get(e);t&&(t.delete(s),0===t.size&&n.get(this).delete(e))}t.call(this,e,s,r)},EventTarget.prototype.removeAllEventListeners=function(e){if(n.has(this)&&n.get(this).has(e)){const s=n.get(this).get(e);s&&(s.forEach((n=>{t.call(this,e,n)})),n.get(this).delete(e))}};const s=Symbol("pphp_remove_all");EventTarget.prototype[s]||Object.defineProperty(EventTarget.prototype,s,{value(e){const s=n.get(this);if(!s)return;const r=e?[e]:[...s.keys()];for(const e of r){const n=s.get(e);n&&(n.forEach((n=>t.call(this,e,n))),s.delete(e))}},writable:!1,enumerable:!1,configurable:!0})})();class PPHP{props={};static _instance;_isNavigating=!1;_responseData=null;_activeAbortController=null;_rawProps={};_elementState={checkedElements:new Set};_reservedWords;_bindings=[];_pendingBindings=new Set;_updateScheduled=!1;_templateStore=new WeakMap;_proxyCache=new WeakMap;_scopedKeys=new Map;_processedPhpSections=new Set;_processedPhpScripts=new WeakSet;_effects=new Set;_pendingEffects=new Set;_refs=new Map;_declaredStateRoots=new Set;_eventHandlers;_redirectRegex=/redirect_7F834\s*=\s*(\/[^\s]*)/;_mustacheRe=/\{\{\s*([\s\S]+?)\s*\}\}/gu;_assignmentRe=/^\s*[\w.]+\s*=(?!=)/;_htmlEntitiesRe=/&quot;|&#039;|&amp;/g;_mutators;_arrayMethodCache=new WeakMap;static _mustacheTest=/\{\{\s*[\s\S]+?\s*\}\}/;static _mustachePattern=/\{\{\s*([\s\S]+?)\s*\}\}/g;constructor(){const e=["focus","blur","click","scrollIntoView","select","setSelectionRange","show","showModal","requestFullscreen"];for(const t of e){const e=HTMLElement.prototype;if("function"==typeof e[t]&&!e[`__pphp_${t}_patched`]){const n=e[t];e[t]=function(...e){requestAnimationFrame((()=>n.apply(this,e)))},e[`__pphp_${t}_patched`]=!0}}const t=Object.getOwnPropertyNames(HTMLElement.prototype).filter((e=>e.startsWith("on"))),n=Object.getOwnPropertyNames(Document.prototype).filter((e=>e.startsWith("on"))),s=Object.getOwnPropertyNames(Window.prototype).filter((e=>e.startsWith("on")));this._eventHandlers=new Set([...t,...n,...s].map((e=>e.toLowerCase()))),this._reservedWords=new Set(["null","undefined","true","false","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","let","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","async","await","implements","interface","event","NaN","Infinity","Number","String","Boolean","Object","Array","Function","Date","RegExp","Error","JSON","Math","Map","Set"]),this._mutators=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]),this.handlePopState(),this.props=this.makeReactive(this._rawProps),this.scheduleInitialHydration()}static get instance(){return PPHP._instance||(PPHP._instance=new PPHP),PPHP._instance}scheduleInitialHydration(){const e=async()=>{this.initRefs(),await this.processInlineModuleScripts(),this.initializeAllReferencedProps(),this.initBindings(),this.initLoopBindings(),this.attachWireFunctionEvents(),this._bindings.forEach((e=>e.update())),requestAnimationFrame((()=>{document.documentElement.setAttribute("data-initial-hydrated",""),this.handlerAutofocusAttribute()}))};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>e()),{once:!0}):e()}static _isBuiltIn=(()=>{const e=new Map,t=[Object.prototype,Function.prototype,Array.prototype,String.prototype,Number.prototype,Boolean.prototype,Date.prototype,RegExp.prototype,Map.prototype,Set.prototype,WeakMap.prototype,WeakSet.prototype,Error.prototype,Promise.prototype];return n=>{const s=e.get(n);if(void 0!==s)return s;const r=n in globalThis||t.some((e=>n in e));return e.set(n,r),r}})();initRefs(){document.querySelectorAll("[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),n=this._refs.get(t)||[];n.push(e),this._refs.set(t,n),e.removeAttribute("pp-ref")}))}ref(e,t){const n=this._refs.get(e)||[];if(null!=t){const s=n[t];if(!s)throw new Error(`pphp.ref('${e}', ${t}) β€” no element at that index`);return s}if(0===n.length)throw new Error(`pphp.ref('${e}') failed β€” no element was found`);return 1===n.length?n[0]:n}_currentSectionId(){const e=document.currentScript;return e?.closest("[pp-section-id]")?.getAttribute("pp-section-id")||null}getNested(e,t){return t.split(".").reduce(((e,t)=>e?e[t]:void 0),e)}setNested(e,t,n){const s=t.split("."),r=s.pop();s.reduce(((e,t)=>e[t]??={}),e)[r]=n}hasNested(e,t){return void 0!==this.getNested(e,t)}scopeKey(e){const t=this._currentSectionId();return t?e.startsWith(`${t}_`)?e:e.includes(".")?e.replace(/^([^\.]+)/,`${t}_$1`):`${t}_${e}`:e}alreadyScoped(e,t){const n=`${t}_${e}`;return this._scopedKeys.get(t)?.has(n)??!1}scheduleFlush(){this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this._updateScheduled=!1,this.flushBindings()})))}effect(e,t){const n=this._currentSectionId(),s=Array.isArray(t),r=s?t:[],i=s&&0===r.length,o=r.map((e=>{if("function"==typeof e&&e.__pphp_key)return e.__pphp_key;if("string"!=typeof e)return"";if(e.includes("_"))return e;for(const[t,n]of this._scopedKeys)if(n.has(e))return`${t}_${e}`;return n?`${n}_${e}`:e})).filter(Boolean);if(e.__deps=new Set(o),i){try{e()}catch(e){console.error("effect error:",e)}return()=>{}}const a=(window.__PPHP_INLINE_DEPTH__??0)>0?this._pendingEffects:this._effects;return a.delete(e),a.add(e),()=>{this._effects.delete(e),this._pendingEffects.delete(e)}}state(e,t){const n=this._currentSectionId(),s=e;if(this._reservedWords.has(s))throw new Error(`'${s}' is reserved (native object) – choose another state key.`);e=this.scopeKey(e),this._declaredStateRoots.add(e),n&&(this._scopedKeys.has(n)||this._scopedKeys.set(n,new Set),this._scopedKeys.get(n).add(s)),this.hasNested(pphp.props,e)||this.setNested(pphp.props,e,t);const r=()=>this.getNested(pphp.props,e),i=()=>r();return Object.defineProperties(i,{valueOf:{value:()=>r()},toString:{value:()=>String(r())}}),[i,t=>{const n="function"==typeof t?t(r()):t;this.setNested(pphp.props,e,n),this.scheduleFlush()}]}extractDependencies(e){let t=e.replace(/\?\./g,".");const n=new Set,s=/(?:^|[^\w$])(?:\(\s*([^)]*?)\s*\)|([A-Za-z_$][\w$]*))\s*=>/g;for(let e;e=s.exec(t);){(e[1]??e[2]??"").split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>n.add(e)))}t=t.replace(/`([^`\\]|\\.)*`/g,(e=>[...e.matchAll(/\$\{([^}]*)\}/g)].map((e=>e[1])).join(" "))),t=t.replace(/(['"])(?:\\.|[^\\])*?\1/g,""),t=t.replace(/\/(?:\\.|[^\/\\])+\/[gimsuy]*/g,"");const r=new Set,i=/\b[A-Za-z_$]\w*(?:\.[A-Za-z_$]\w*)*\b/g;for(const e of t.match(i)??[]){const t=e.split(".")[0];n.has(t)||PPHP._isBuiltIn(t)||r.add(e)}return r}formatValue(e){return"function"==typeof e?"":"boolean"==typeof e?e?"true":"false":Array.isArray(e)?e.map((e=>"object"==typeof e?JSON.stringify(e):String(e))).join(", "):e&&"object"==typeof e?Object.keys(e).length?JSON.stringify(e,null,2):"":e?.toString()??""}registerBinding(e,t,n="text",s){if(this._assignmentRe.test(t))return;const r=e.parentElement?.closest("[pp-section-id]"),i=r?.getAttribute("pp-section-id");let o=t;if(i){const e=this._scopedKeys.get(i),n=e instanceof Set?e:new Set(Array.isArray(e)?e:[]);o=t.replace(/\b([A-Za-z_$][\w$]*)\b/g,((e,t,s,r)=>{const o=n.has(t),a=n.has(`${i}_${t}`);return o||a?"."===r[s-1]||this._reservedWords.has(t)||e.startsWith(`${i}_`)?e:`${i}_${t}`:e}))}const a=new Set([...this.extractDependencies(o)].map((e=>e.split(".")[0])).filter((e=>e in this.props&&!this._reservedWords.has(e)))),c=this.makeSafeEvaluator(o);if("value"===s||"checked"===s){const t=this.makePrimitiveUpdater(e,s,c);return void this._bindings.push({dependencies:a,update:t})}if(s){const t=e.getAttribute(s)??"";if(this._mustacheRe.test(o)||this._mustacheRe.test(t)){const n=t.replace(this._mustacheRe,((e,t)=>{let n=t;if(i){const e=this._scopedKeys.get(i),s=e instanceof Set?e:new Set(Array.isArray(e)?e:[]);n=t.replace(/\b([A-Za-z_$][\w$]*)\b/g,((e,t,n,r)=>{const o=s.has(t),a=s.has(`${i}_${t}`);return o||a?"."===r[n-1]||this._reservedWords.has(t)||e.startsWith(`${i}_`)?e:`${i}_${t}`:e}))}return`{{ ${n} }}`})),r=this.makeAttrTemplateUpdater(e,s,a,n);return void this._bindings.push({dependencies:a,update:r})}const n=()=>{try{const t=c(this.props),n=this.formatValue(t);s in e&&(e[s]=n),e.setAttribute(s,n)}catch(e){console.error(`Error evaluating "${s}"="${o}"`,e)}};return void this._bindings.push({dependencies:a,update:n})}const l={text:(e,t)=>{e.textContent!==t&&(e.textContent=t)},value:(e,t)=>{e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement?e.value!==t&&(e.value=t):e.setAttribute("value",t)},checked:(e,t)=>{e instanceof HTMLInputElement?e.checked="true"===t:e.setAttribute("checked",t)},attr:(e,t)=>{e.setAttribute("attr",t)}};this._bindings.push({dependencies:a,update:()=>{try{const t=c(this.props),s=this.formatValue(t);l[n](e,s)}catch(e){console.error(`Error evaluating expression "${o}".`,e)}}})}makePrimitiveUpdater(e,t,n){const s={};return this._eventHandlers.forEach((e=>{if(e.startsWith("on")){const t=e.slice(2);s[t]=t}})),s.value="input",s.checked="change",()=>{try{const r=n(this.props),i=this.formatValue(r);let o=!1;if("value"===t){const t=e;"value"in e&&t.value!==i?(t.value=i,o=!0):"value"in e||(e.setAttribute("value",i),o=!0)}else{const t=e,n="true"===i;"checked"in e&&t.checked!==n?(t.checked=n,o=!0):"checked"in e||(e.setAttribute("checked",i),o=!0)}if(!o||e instanceof HTMLInputElement&&("hidden"===e.type||e.disabled||e.readOnly))return;const a=e.getAttribute("pp-dispatch-event")||s[t]||t,c="click"===a?new MouseEvent(a,{bubbles:!0,cancelable:!0}):new Event(a,{bubbles:!0});e.dispatchEvent(c)}catch(e){console.error(`Error evaluating attribute "${t}":`,e)}}}makeAttrTemplateUpdater(e,t,n,s){let r=this._templateStore.get(e);r||(r=new Map,this._templateStore.set(e,r)),r.has(t)||r.set(t,e.getAttribute(t)||"");const i=s??r.get(t)??"";return(i.match(this._mustacheRe)||[]).forEach((e=>{this.extractDependencies(e).forEach((e=>n.add(e)))})),()=>{try{const n=i.replace(this._mustacheRe,((e,t)=>{try{const e=this.makeSafeEvaluator(t);return this.formatValue(e(this.props))}catch(e){return console.error("Error token:",t,e),""}}));e.getAttribute(t)!==n&&e.setAttribute(t,n)}catch(e){console.error(`Error evaluating the template for attribute "${t}". Please check the template syntax and dependencies.`,e)}}}initBindings(){this._bindings=[];const e=new WeakSet;document.body.querySelectorAll("[pp-if]").forEach((t=>{if(e.has(t))return;const n=[];let s=t;for(;s;){if(s.hasAttribute("pp-if"))n.push({el:s,expr:s.getAttribute("pp-if")});else if(s.hasAttribute("pp-elseif"))n.push({el:s,expr:s.getAttribute("pp-elseif")});else{if(!s.hasAttribute("pp-else"))break;n.push({el:s,expr:null})}e.add(s),s=s.nextElementSibling}n.forEach((e=>{if(null!==e.expr){const t=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractDependencies(t);const n=this.makeSafeEvaluator(t);e.evaluate=()=>!!n(this.props)}}));const r=new Set;n.forEach((e=>e.deps?.forEach((e=>r.add(e)))));this._bindings.push({dependencies:r,update:()=>{let e=!1;for(const{el:t,expr:s,evaluate:r}of n)!e&&null!==s&&r()?(t.removeAttribute("hidden"),e=!0):e||null!==s?t.setAttribute("hidden",""):(t.removeAttribute("hidden"),e=!0)}})})),document.body.querySelectorAll("*").forEach((e=>{["pp-bind","pp-bind-expr"].forEach((t=>{const n=e.getAttribute(t);n&&this.registerBinding(e,n,"text")})),Array.from(e.attributes).forEach((t=>{if(!t.name.startsWith("pp-bind-"))return;if("pp-bind"===t.name||"pp-bind-expr"===t.name||"pp-bind-spread"===t.name)return;const n=t.value.replace(this._htmlEntitiesRe,(e=>"&quot;"===e?'"':"&#039;"===e?"'":"&")).replace(/^{{\s*|\s*}}$/g,"");let s=t.name.replace(/^(pp-bind-)+/,"");const r=s.toLowerCase();"html"!==r&&"innerhtml"!==r||(s="innerHTML");const i="value"===s?"value":"checked"===s?"checked":"text";this.registerBinding(e,n,i,s)})),Array.from(e.attributes).forEach((t=>{if("pp-bind-spread"!==t.name)return;const n=t.value.split(",").map((e=>e.trim())).filter(Boolean),s=new Set;n.forEach((e=>s.add(e.split(".")[0])));const r=new Set;this._bindings.push({dependencies:s,update:()=>{try{const t={};n.forEach((e=>{const n=this.getNested(this.props,e)??{};Object.assign(t,n)})),r.forEach((n=>{n in t||e.hasAttribute(n)||(e.removeAttribute(n),r.delete(n))})),Object.entries(t).forEach((([t,n])=>{if(!r.has(t)&&e.hasAttribute(t))return;if(!1===n||null==n)return void(r.has(t)&&(e.removeAttribute(t),r.delete(t)));const s="object"==typeof n?JSON.stringify(n):String(n);e.getAttribute(t)!==s&&e.setAttribute(t,s),r.add(t)}))}catch(e){console.error("pp-spread error:",e)}}})}))}))}safeNull=new Proxy({},{get:(e,t)=>t===Symbol.toPrimitive?()=>{}:PPHP._isBuiltIn(t.toString())?(console.warn(`PPHP Warning: The property or method name "${t.toString()}" conflicts with a JavaScript built-in object or function. Please choose a unique name to avoid unexpected behavior.`),()=>""):this.safeNull,apply:()=>""});safeTag=(e,...t)=>e.reduce(((e,n,s)=>{const r=t[s];return e+n+(null==r||"object"==typeof r?"":r)}),"");makeSafeEvaluator(e){let t=e.trim();const n=t.replace(/\?\./g,".");if(/^\(\s*\)\s*=>/.test(t)&&(t=`(${t})()`),t.startsWith("`")&&t.endsWith("`")){const e=new Function("props","safeTag",`\n try {\n with (props) {\n return safeTag${t};\n }\n } catch (e) {\n console.error("PPHP template eval error for:", ${JSON.stringify(t)}, e);\n return "";\n }\n `);return t=>e(t,this.safeTag.bind(this))}const s=n.replace(/(["'])(?:(?=(\\?))\2.)*?\1/g,"").match(/\b[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*\b/g)||[],r=new Set(s.map((e=>e.split(".")[0])).filter((e=>/^[A-Za-z_$][\w$]*$/.test(e)&&!this._reservedWords.has(e)&&"safeTag"!==e))),i=Array.from(r).map((e=>`\n const ${e} = ctx["${e}"] !== undefined\n ? ctx["${e}"]\n : (typeof window !== "undefined" && window["${e}"] !== undefined\n ? window["${e}"]\n : ${new RegExp(`\\b${e}\\.`).test(n)?"{}":"void 0"});\n if (typeof window !== "undefined" && window["${e}"] !== ${e}) {\n window["${e}"] = ${e};\n }\n `)).join("\n"),o=/^\s*[\w\.]+\s*=(?!=)/.test(t),a=new Function("ctx","safeTag",`\n "use strict";\n ${i}\n try {\n ${o?t+"; return '';":"const result = "+t+"; return result === undefined || result === null ? '' : result;"}\n } catch (e) {\n return "";\n }\n `);return e=>a(e,this.safeTag.bind(this))}setNestedProperty(e,t,n){const s=t.split(".");let r=e;for(let e=0;e<s.length-1;e++)s[e]in r||(r[s[e]]={}),r=r[s[e]];r[s[s.length-1]]=n}resetProps(){Object.keys(this._rawProps).forEach((e=>{if(window.hasOwnProperty(e)){const t=Object.getOwnPropertyDescriptor(window,e);t&&t.configurable&&delete window[e]}})),this._rawProps={},this._proxyCache=new WeakMap,this._templateStore=new WeakMap,this._processedPhpSections=new Set,this._processedPhpScripts=new WeakSet,this._scopedKeys=new Map,this._effects=new Set,this._pendingEffects=new Set,this._bindings=[],this.props=this.makeReactive(this._rawProps)}initializeAllReferencedProps(){const e=PPHP._mustachePattern,t=PPHP._mustacheTest,n=this.props,s=new Set,r=(e,t)=>{const n=e.getAttribute("pp-section-id"),s=e.parentElement?.closest("[pp-section-id]")?.getAttribute("pp-section-id")??null,r=n??s;return r?`${r}_${t}`:t},i=(()=>{const e=new Set([...Object.getOwnPropertyNames(String.prototype),...Object.getOwnPropertyNames(Array.prototype),...Object.getOwnPropertyNames(Number.prototype),...Object.getOwnPropertyNames(Boolean.prototype),...Object.getOwnPropertyNames(Object.prototype),...Object.getOwnPropertyNames(Date.prototype),...Object.getOwnPropertyNames(RegExp.prototype)]);return t=>e.has(t)})(),o=(e,t)=>{const[n,o,...a]=t.split(".");if(PPHP._isBuiltIn(n)||this._reservedWords.has(n))return void console.warn(`Invalid path β€œ${t}” while initialising props – the root identifier is reserved or built‑in.`);if(o&&i(o))return void s.add(r(e,n));const c=r(e,n);s.add(o?`${c}.${[o,...a].join(".")}`:c)};for(const n of document.body.getElementsByTagName("*"))for(const{name:s,value:r}of Array.from(n.attributes))if(r){if(t.test(r))for(const t of r.matchAll(e))this.extractDependencies(t[1]).forEach((e=>o(n,e)));"pp-if"!==s&&"pp-elseif"!==s||this.extractDependencies(r).forEach((e=>o(n,e))),s.startsWith("pp-bind")&&this.extractDependencies(r).forEach((e=>o(n,e)))}const a=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT,{acceptNode:e=>e.parentElement?.closest("pre,code,[pp-ignore='true']")?NodeFilter.FILTER_REJECT:t.test(e.nodeValue||"")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});for(let t;t=a.nextNode();){const n=t.parentElement;for(const s of t.nodeValue.matchAll(e))this.extractDependencies(s[1]).forEach((e=>o(n,e)))}const c=Array.from(s).sort(((e,t)=>t.split(".").length-e.split(".").length));for(const e of c){const t=e.split(".");let s=n;for(let n=0;n<t.length;n++){const r=t[n],i=n===t.length-1;if(0===n&&PPHP._isBuiltIn(r)){console.warn(`Skipping root β€œ${r}” inside path β€œ${e}” – collides with a JS built‑in.`);break}r in s&&(i||null!=s[r]&&"object"==typeof s[r])||(s[r]=i?void 0:{}),s=s[r]}}const l=new Set(c.map((e=>e.split(".")[0])));for(const e of this._declaredStateRoots)l.add(e);for(const e of l)e in globalThis||Object.defineProperty(globalThis,e,{configurable:!0,enumerable:!0,get:()=>n[e],set:t=>n[e]=t})}scheduleBindingUpdate(e){this._pendingBindings.add(e),this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this.flushBindings()})))}flushBindings(){const e=new Set;this._pendingBindings.forEach((t=>{t.dependencies.forEach((t=>e.add(t))),t.update()})),this._pendingBindings.clear(),this._updateScheduled=!1,this._effects.forEach((t=>{const n=t.__deps||new Set;if(0===n.size||[...n].some((t=>e.has(t))))try{t()}catch(e){console.error("effect error:",e)}}))}initMakeReactive(){this.initializeAllReferencedProps(),this.initBindings(),this.initLoopBindings(),this.attachWireFunctionEvents(),this._bindings.forEach((e=>e.update()))}getProxiedProps(e){let t=this._proxyCache.get(e);if(t)return t;return t=new Proxy(e,{get:(e,t)=>t in e?e[t]:void 0,set:(e,t,n)=>(e[t]=n,!0)}),this._proxyCache.set(e,t),t}async invokeHandler(e,t,n){try{const s=t.trim(),r=s.replace(/(["'`])(?:\\.|(?!\1).)*\1/g,"").replace(/\/(?:\\.|[^\/])+\/[gimsuy]*/g,"");if(/^\(?\s*[^=]*?\)?\s*=>/.test(r.trim())){const t=new Function("event","proxy","props",`\n with (proxy) {\n const val = (${s});\n return (typeof val === "function")\n ? val.call(this, event, props)\n : val;\n }\n `),r=this.getProxiedProps(pphp.props);return void await t.call(e,n,r,pphp.props)}const i=t.match(/^(\w+(\.\w+)*)\((.*)\)$/);if(i){const s=i[1],r=i[3],o=s.split("."),{context:a,methodName:c}=this.resolveContext(o);if("function"==typeof a[c])if(this.isJsonLike(r)){const t=this.parseJson(r);t.element=e,t.event=n;const s=[t];await a[c](...s)}else new Function("event",t).call(e,n);else await this.handleParsedCallback(e,t)}else if(t.includes("=")){const s=t.match(/^\s*([\w\.]+)\s*=/);if(s){const e=s[1];if(e.includes(".")){const t=e.split(".");let n=pphp.props;for(let e=0;e<t.length-1;e++){const s=t[e];s in n&&null!=n[s]&&"object"==typeof n[s]||(n[s]={}),n=n[s]}}else e in pphp.props||(pphp.props[e]=void 0)}new Function("event","props",`\n with (new Proxy(props, {\n get(target, key) {\n return key in target ? target[key] : undefined;\n },\n set(target, key, value) {\n target[key] = value;\n return true;\n }\n })) {\n ${t}\n }\n `).call(e,n,pphp.props)}else await this.handleParsedCallback(e,t)}catch(e){console.error(`Error executing handler "${t}". Please ensure the handler is defined and valid.`,e)}finally{this.scheduleFlush()}}registerLoop(e){const t=e.getAttribute("pp-for").trim(),[n,s]=t.split(/\s+in\s+/),[r,i]=n.replace(/^\(|\)$/g,"").split(",").map((e=>e.trim())),o=e.parentNode,a=document.createComment("pp-for");o.insertBefore(a,e),o.removeChild(e);const c=this.makeSafeEvaluator(s),l=this.extractDependencies(s);this._bindings.push({dependencies:l,update:()=>{let t=a.nextSibling;for(;t&&t.nodeType!==Node.COMMENT_NODE;){const e=t.nextSibling;o.removeChild(t),t=e}(c(this.props)||[]).forEach(((t,n)=>{this.props[r]=t,i&&(this.props[i]=n);const s=e.content.cloneNode(!0),c=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null);let l;for(;l=c.nextNode();)l.nodeValue=(l.nodeValue||"").replace(PPHP._mustachePattern,((e,t)=>{try{const e=this.makeSafeEvaluator(t)(this.props);return this.formatValue(e)}catch{return""}}));s.querySelectorAll("*").forEach((e=>{Array.from(e.attributes).forEach((e=>{PPHP._mustacheTest.test(e.value)&&(e.value=e.value.replace(PPHP._mustachePattern,((e,t)=>{try{const e=this.makeSafeEvaluator(t)(this.props);return this.formatValue(e)}catch{return""}})))}))})),s.querySelectorAll("[pp-bind]").forEach((e=>{const t=e.getAttribute("pp-bind"),n=this.makeSafeEvaluator(t)(this.props);e.textContent=this.formatValue(n)})),s.querySelectorAll("[pp-bind-expr]").forEach((e=>{const t=e.getAttribute("pp-bind-expr"),n=this.makeSafeEvaluator(t)(this.props);e.textContent=this.formatValue(n)})),s.querySelectorAll("[pp-bind-class]").forEach((e=>{const t=e.getAttribute("pp-bind-class"),n=this.makeSafeEvaluator(t)(this.props);e.setAttribute("class",String(n))})),s.querySelectorAll("*").forEach((e=>{Array.from(e.attributes).forEach((t=>{if(t.name.startsWith("on")&&/\bidx?\b/.test(t.value)){const s=t.value.replace(/\bi\b/g,String(n)).replace(/\bidx\b/g,String(n));e.setAttribute(t.name,s)}}))})),o.insertBefore(s,a.nextSibling)})),this.attachWireFunctionEvents()}})}initLoopBindings(){document.querySelectorAll("[pp-for]").forEach((e=>this.registerLoop(e)))}makeReactive(e,t=[]){const n=this._proxyCache.get(e);if(n)return n;const s=this;if(e instanceof Map||e instanceof Set)return e;const r=new Proxy(e,{get(e,n,r){const i=Reflect.get(e,n,r);if(Array.isArray(e)&&s._mutators.has(n)){let o=s._arrayMethodCache.get(e);if(o||(o=new Map,s._arrayMethodCache.set(e,o)),!o.has(n)){const e=i,a=t.join("."),c=function(...t){const n=Reflect.apply(e,r,t);return queueMicrotask((()=>{s._bindings.forEach((e=>{e.dependencies.has(a)&&s.scheduleBindingUpdate(e)}))})),n};o.set(n,c)}return o.get(n)}return"object"==typeof i&&null!==i?s.makeReactive(i,[...t,n]):i},set(e,n,r){if(r&&"object"==typeof r&&(r=s.makeReactive(r,[...t,n.toString()])),e[n]=r,0===t.length){const e=n;s._reservedWords.has(e)||PPHP._isBuiltIn(e)||e in globalThis||Object.defineProperty(globalThis,e,{configurable:!0,enumerable:!0,get:()=>s.props[e],set(t){s.props[e]=t}})}const i=[...t,n].join(".");return s._bindings.forEach((e=>{for(const t of e.dependencies)if(i===t||i.startsWith(t+".")||t.startsWith(i+".")){s.scheduleBindingUpdate(e);break}})),!0}});return this._proxyCache.set(e,r),r}handlePopState(){window.addEventListener("popstate",(async()=>{await this.handleNavigation()}))}prefixFunctionCalls(e,t){return e.replace(/\b([A-Za-z_$][\w$]*)\s*\(/g,((e,n)=>this._reservedWords.has(n)||n.startsWith(`${t}_`)?e:this.alreadyScoped(n,t)?`${t}_${n}(`:e))}prefixIds(e,t){let n="",s=0,r=(e=this.prefixFunctionCalls(e,t)).length,i=!1,o=!1,a=!1;for(;s<r;){const c=e[s];if("'"!==c||o||a||"\\"===e[s-1])if('"'!==c||i||a||"\\"===e[s-1])if("`"!==c||i||o||"\\"===e[s-1])if(i||o||a)n+=c,s++;else if(/[A-Za-z_$]/.test(c)){let i=s+1;for(;i<r&&/[\w$]/.test(e[i]);)i++;const o=e.slice(s,i),a=e[s-1]??"",c=this._reservedWords.has(o),l="."===a;n+=!o.startsWith(`${t}_`)&&!l&&!c?`${t}_${o}`:o,s=i}else n+=c,s++;else a=!a,n+=c,s++;else o=!o,n+=c,s++;else i=!i,n+=c,s++}return n}attachWireFunctionEvents(){this.handleHiddenAttribute(),this.handleAnchorTag();const e=Array.from(this._eventHandlers).map((e=>`[${e}]`)).join(", ");document.body.querySelectorAll(e).forEach((e=>{const t=e.closest("[pp-section-id]")?.getAttribute("pp-section-id");if(Array.from(e.attributes).filter((e=>this._eventHandlers.has(e.name))).forEach((n=>{const s=n.name.slice(2);e.removeAllEventListeners(s);let r=n.value.trim();if(t){const e=r.indexOf("=>");if(-1!==e){const n=r.slice(0,e+2),s=r.slice(e+2);r=n+this.prefixIds(s,t)}else r=this.prefixIds(r,t)}e instanceof HTMLInputElement&&this.handleInputAppendParams(e,s),e.removeAttribute(n.name),this.handleDebounce(e,s,r)})),e instanceof HTMLFormElement){const n=e.getAttribute("onsubmit")?.trim();if(n){let s=n;t&&(s=s.replace(/^([A-Za-z_$][\w$]*)\s*\(/,((e,n)=>`${t}_${n}(`))),e.removeAttribute("onsubmit"),this.handleDebounce(e,"submit",s)}}}))}async handleDebounce(e,t,n){const s=e.getAttribute("pp-debounce")||"",r=e.getAttribute("pp-before-request")||"",i=e.getAttribute("pp-after-request")||"",o=async t=>{t.preventDefault();try{r&&await this.invokeHandler(e,r,t),await this.invokeHandler(e,n,t),i&&"@close"!==i&&await this.invokeHandler(e,i,t),this.handlerAutofocusAttribute()}catch(e){console.error("Error in debounced handler. Please check the handler logic and ensure it is functioning correctly.",e)}};if(s){const n=this.parseTime(s),r=this.debounce(o,n);e instanceof HTMLFormElement&&"submit"===t?e.addEventListener(t,(e=>{e.preventDefault(),r(e)})):e.addEventListener(t,r)}else e.addEventListener(t,o)}debounce(e,t=300,n=!1){let s;return function(...r){const i=this;s&&clearTimeout(s),s=setTimeout((()=>{s=null,n||e.apply(i,r)}),t),n&&!s&&e.apply(i,r)}}handlerAutofocusAttribute(){const e=document.querySelector("dialog[open]");let t=null;if(e&&(t=e.querySelector("[pp-autofocus]")),t||(t=document.querySelector("[pp-autofocus]")),!t)return;const n=t.getAttribute("pp-autofocus");if(!this.isJsonLike(n))return;const s=this.parseJson(n);requestAnimationFrame((()=>{t.focus(),(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&"function"==typeof this.setCursorPosition&&(t instanceof HTMLInputElement&&"number"===t.type?(t.type="text",this.setCursorPosition(t,s),t.type="number"):this.setCursorPosition(t,s))}))}async handleParsedCallback(e,t){const{funcName:n,data:s}=this.parseCallback(e,t);if(!n)return;const r=this[n],i=window[n];let o;if("function"==typeof r?o=r:"function"==typeof i&&(o=i),"function"==typeof o){const t=e.hasAttribute("pp-after-request"),n=Array.isArray(s.args)?s.args:[],r=this._responseData?this.parseJson(this._responseData):{response:this._responseData};let i={args:n,element:e,data:s};t&&(i={...i,...r}),await o.call(this,i)}else this._responseData=null,this._responseData=await this.handleUndefinedFunction(e,n,s)}async handleUndefinedFunction(e,t,n){const s={callback:t,...n},r=this.createFetchOptions(s),i=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});try{this.saveElementOriginalState(e),this.handleSuspenseElement(e);const s=new URL(window.location.href);let o="",a="",c={success:!1};const l=e.querySelector("input[type='file']");if(l){if(o=await this.fetchFileWithData(s.href,t,l,n),a=this.extractJson(o)||"",a)try{c=this.parseJson(a)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}else{const e=await this.fetch(s.href,r);if(o=await e.text(),this.getRedirectUrl(o))return void await this.redirect(this.getRedirectUrl(o)||"");if(a=this.extractJson(o)||"",a)try{c=this.parseJson(a)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}const p=e.getAttribute("pp-before-request")||"",h=e.getAttribute("pp-after-request")||"";if((p||h&&c.success)&&this.restoreSuspenseElement(e),p||h){let e="";if(c.success){e=o.replace(a,"")}else e=o;if(this.appendAfterbegin(e),!h&&!c.success)return}if(h&&c.success){this.handleAfterRequest(h,a);const e=o.replace(a,"");return this.appendAfterbegin(e),a}if("@close"===h)return c.success?a:void 0;const d=await this.fetch(s.href,i),u=await d.text();if(this.getRedirectUrl(u))return void await this.redirect(this.getRedirectUrl(u)||"");await this.handleResponseRedirectOrUpdate(o,u,a,c)}catch(e){console.error(`Error handling undefined function "${t}". Please ensure the function is defined and accessible.`,e)}}handleAfterRequest(e,t){if(!this.isJsonLike(e))return;const n=this.parseJson(e),s=t?this.parseJson(t):null,r=n.targets;Array.isArray(r)&&r.forEach((e=>{const{id:t,...n}=e,r=document.querySelector(t);let i={};if(s){for(const t in n)if(n.hasOwnProperty(t))switch(t){case"innerHTML":case"outerHTML":case"textContent":case"innerText":"response"===n[t]&&(i[t]=e.responseKey?s[e.responseKey]:s.response);break;default:i[t]=n[t]}}else i=n;r&&this.updateElementAttributes(r,i)}))}async handleResponseRedirectOrUpdate(e,t,n,s){const r=this.getUpdatedHTMLContent(e,n,s),i=(new DOMParser).parseFromString(t,"text/html");r&&i.body.insertAdjacentElement("afterbegin",r),this.updateBodyContent(i.body.outerHTML)}getUpdatedHTMLContent(e,t,n){const s=document.createElement("div");if(s.id="afterbegin-8D95D",n&&t?.success){const t=e.replace(n,"");s.innerHTML=t}else s.innerHTML=e;return s.innerHTML?s:null}async updateBodyContent(e){const t=this.saveScrollPositions();this.saveElementState();const n=(new DOMParser).parseFromString(e,"text/html");await this.appendCallbackResponse(n),this.restoreElementState(),this.restoreScrollPositions(t),await this.processInlineModuleScripts(),this.initMakeReactive()}restoreElementState(){if(this._elementState.focusId){const e=document.getElementById(this._elementState.focusId)||document.querySelector(`[name="${this._elementState.focusId}"]`);if(e instanceof HTMLInputElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&("checkbox"===e.type||"radio"===e.type?e.checked=!!this._elementState.focusChecked:"number"===e.type||"email"===e.type?(e.type="text",e.setSelectionRange(t,t),e.type="number"===e.type?"number":"email"):"date"===e.type||"month"===e.type||"week"===e.type||"time"===e.type||"datetime-local"===e.type||"color"===e.type||"file"===e.type||""!==e.value&&(e.value=this._elementState.focusValue)),e.focus()}else if(e instanceof HTMLTextAreaElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus()}else e instanceof HTMLSelectElement&&(this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus())}this._elementState.checkedElements.forEach((e=>{const t=document.getElementById(e);t&&(t.checked=!0)}))}async appendCallbackResponse(e){const t=e.getElementById("afterbegin-8D95D");if(t){const e=document.getElementById("afterbegin-8D95D");e?e.innerHTML=t.innerHTML:document.body.insertAdjacentHTML("afterbegin",t.outerHTML)}await this.populateDocumentBody(e)}saveElementState(){const e=document.activeElement;this._elementState.focusId=e?.id||e?.name,this._elementState.focusValue=e?.value,this._elementState.focusChecked=e?.checked,this._elementState.focusType=e?.type,this._elementState.focusSelectionStart=e?.selectionStart,this._elementState.focusSelectionEnd=e?.selectionEnd,this._elementState.isSuspense=e.hasAttribute("pp-suspense"),this._elementState.checkedElements.clear(),document.querySelectorAll('input[type="checkbox"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)})),document.querySelectorAll('input[type="radio"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)}))}updateElementAttributes(e,t){for(const n in t)if(t.hasOwnProperty(n))switch(n){case"innerHTML":case"outerHTML":case"textContent":case"innerText":e[n]=this.decodeHTML(t[n]);break;case"insertAdjacentHTML":e.insertAdjacentHTML(t.position||"beforeend",this.decodeHTML(t[n].html));break;case"insertAdjacentText":e.insertAdjacentText(t.position||"beforeend",this.decodeHTML(t[n].text));break;case"setAttribute":e.setAttribute(t.attrName,this.decodeHTML(t[n]));break;case"removeAttribute":e.removeAttribute(t[n]);break;case"className":e.className=this.decodeHTML(t[n]);break;case"classList.add":e.classList.add(...this.decodeHTML(t[n]).split(","));break;case"classList.remove":e.classList.remove(...this.decodeHTML(t[n]).split(","));break;case"classList.toggle":e.classList.toggle(this.decodeHTML(t[n]));break;case"classList.replace":const[s,r]=this.decodeHTML(t[n]).split(",");e.classList.replace(s,r);break;case"dataset":e.dataset[t.attrName]=this.decodeHTML(t[n]);break;case"style":Object.assign(e.style,t[n]);break;case"value":e.value=this.decodeHTML(t[n]);break;case"checked":e.checked=t[n];break;default:e.setAttribute(n,this.decodeHTML(t[n]))}}decodeHTML(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}appendAfterbegin(e){if(!e)return;const t="afterbegin-8D95D";let n=document.getElementById(t);n?(n.innerHTML=e,document.body.insertAdjacentElement("afterbegin",n)):(n=document.createElement("div"),n.id=t,n.innerHTML=e,document.body.insertAdjacentElement("afterbegin",n))}restoreSuspenseElement(e){const t=e.getAttribute("pp-original-state");if(e.hasAttribute("pp-suspense")&&t){const n=(e,t)=>{for(const n in t)t.hasOwnProperty(n)&&("textContent"===n?e.textContent=t[n]:"innerHTML"===n?e.innerHTML=t[n]:"disabled"===n?!0===t[n]?e.setAttribute("disabled","true"):e.removeAttribute("disabled"):e.setAttribute(n,t[n]));for(const n of Array.from(e.attributes))t.hasOwnProperty(n.name)||e.removeAttribute(n.name)},s=(e,t)=>{for(const s in t)if(t.hasOwnProperty(s))for(const t of Array.from(e.elements))if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-original-state")||"";if(e){if(this.isJsonLike(e)){const s=this.parseJson(e);n(t,s)}else r(t,e);t.removeAttribute("pp-original-state")}}},r=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},i=(e,t)=>{e instanceof HTMLFormElement?s(e,t):n(e,t)};try{const r=this.parseJson(t);if(r)if(e instanceof HTMLFormElement){const t=e.id;if(t){const e=document.querySelector(`[form="${t}"]`);if(e){const t=e.getAttribute("pp-original-state");if(t&&this.isJsonLike(t)){const s=this.parseJson(t);n(e,s)}}}const r=new FormData(e),i={};if(r.forEach(((e,t)=>{i[t]=e})),s(e,i),e.hasAttribute("pp-suspense")){const t=e.getAttribute("pp-suspense")||"";if(this.parseJson(t).disabled)for(const t of Array.from(e.elements))(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&t.removeAttribute("disabled")}}else if(r.targets){r.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&i(s,n)}));const{targets:t,...s}=r;n(e,s)}else{const{empty:t,...s}=r;n(e,s)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}e.querySelectorAll("[pp-suspense]").forEach((e=>this.restoreSuspenseElement(e))),e.removeAttribute("pp-original-state")}extractJson(e){const t=e?.match(/\{[\s\S]*\}/);return t?t[0]:null}getRedirectUrl(e){const t=e.match(this._redirectRegex);return t?t[1]:null}async fetchFileWithData(e,t,n,s={}){const r=new FormData,i=n.files;if(i)for(let e=0;e<i.length;e++)r.append("file[]",i[e]);r.append("callback",t);for(const e in s)s.hasOwnProperty(e)&&r.append(e,s[e]);const o=await this.fetch(e,{method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:r});return await o.text()}async handleSuspenseElement(e){let t=e.getAttribute("pp-suspense")||"";const n=(e,t)=>{for(const n in t)if(t.hasOwnProperty(n))for(const t of e.elements)if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-suspense")||"";if(e)if(this.isJsonLike(e)){const n=this.parseJson(e);"disabled"!==n.onsubmit&&this.updateElementAttributes(t,n),n.targets&&n.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&r(s,n)}))}else s(t,e)}},s=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},r=(e,t)=>{e instanceof HTMLFormElement?n(e,t):this.updateElementAttributes(e,t)};try{if(t&&this.isJsonLike(t)){const s=this.parseJson(t);if(s)if(e instanceof HTMLFormElement){const t=new FormData(e),r={};t.forEach(((e,t)=>{r[t]=e})),s.disabled&&this.toggleFormElements(e,!0);const{disabled:i,...o}=s;this.updateElementAttributes(e,o),n(e,r)}else if(s.targets){s.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&r(s,n)}));const{targets:t,...n}=s;this.updateElementAttributes(e,n)}else{if("disabled"===s.empty&&""===e.value)return;const{empty:t,...n}=s;this.updateElementAttributes(e,n)}}else if(t)s(e,t);else if(e instanceof HTMLFormElement){const t=new FormData(e),s={};t.forEach(((e,t)=>{s[t]=e})),n(e,s)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}toggleFormElements(e,t){Array.from(e.elements).forEach((e=>{(e instanceof HTMLInputElement||e instanceof HTMLButtonElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(e.disabled=t)}))}saveElementOriginalState(e){if(e.hasAttribute("pp-suspense")&&!e.hasAttribute("pp-original-state")){const t={};e.textContent&&(t.textContent=e.textContent.trim()),e.innerHTML&&(t.innerHTML=e.innerHTML.trim()),(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(t.value=e.value);for(let n=0;n<e.attributes.length;n++){const s=e.attributes[n];t[s.name]=s.value}e.setAttribute("pp-original-state",JSON.stringify(t))}if(e instanceof HTMLFormElement){let t=null;const n=e.id;n&&(t=document.querySelector(`[form="${n}"]`)),n&&t||(t=Array.from(e.elements).find((e=>e instanceof HTMLButtonElement||e instanceof HTMLInputElement))),t?t.hasAttribute("pp-original-state")||this.saveElementOriginalState(t):console.warn("Warning: No invoker detected for the form. Ensure the form has an associated invoker or an ID for proper handling.")}e.querySelectorAll("[pp-suspense]").forEach((e=>this.saveElementOriginalState(e)))}getUrlParams(){const e={};return new URLSearchParams(window.location.search).forEach(((t,n)=>{e[n]=t})),e}createFetchOptions(e){return{method:"POST",headers:{"Content-Type":"application/json",HTTP_PPHP_WIRE_REQUEST:"true"},body:JSON.stringify(e)}}parseCallback(e,t){let n={};const s=e.closest("form");if(s){new FormData(s).forEach(((e,t)=>{n[t]?Array.isArray(n[t])?n[t].push(e):n[t]=[n[t],e]:n[t]=e}))}else e instanceof HTMLInputElement?n=this.handleInputElement(e):(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(n[e.name]=e.value);const r=t.match(/(\w+)\((.*)\)/);if(r){const e=r[1];let t=r[2].trim();if(t.startsWith("{")&&t.endsWith("}"))try{const e=this.parseJson(t);"object"==typeof e&&null!==e&&(n={...n,...e})}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}else{const e=t.split(/,(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/).map((e=>e.trim().replace(/^['"]|['"]$/g,"")));n.args=e}return{funcName:e,data:n}}return{funcName:t,data:n}}handleInputElement(e){let t={};if(e.name)if("checkbox"===e.type)t[e.name]={value:e.value,checked:e.checked};else if("radio"===e.type){const n=document.querySelector(`input[name="${e.name}"]:checked`);t[e.name]=n?n.value:null}else t[e.name]=e.value;else"checkbox"===e.type||"radio"===e.type?t.value=e.checked:t.value=e.value;return t}resolveContext(e){let t=window;for(let n=0;n<e.length-1;n++)if(t=t[e[n]],!t)throw new Error(`Cannot find object ${e[n]} in the context.`);return{context:t,methodName:e[e.length-1]}}setCursorPosition(e,t){if(t.start)e.setSelectionRange(0,0);else if(t.end){const t=e.value.length||0;e.setSelectionRange(t,t)}else if(t.length){const n=parseInt(t.length,10)||0;e.setSelectionRange(n,n)}}handleInputAppendParams(e,t){const n=e.getAttribute("pp-append-params"),s=e.getAttribute("pp-append-params-sync");if("true"===n){if("true"===s){const t=e.name||e.id;if(t){const n=new URL(window.location.href),s=new URLSearchParams(n.search);s.has(t)&&(e.value=s.get(t)||"")}}e.addEventListener(t,(e=>{const t=e.currentTarget,n=t.value,s=new URL(window.location.href),r=new URLSearchParams(s.search),i=t.name||t.id;if(i){n?r.set(i,n):r.delete(i);const e=r.toString()?`${s.pathname}?${r.toString()}`:s.pathname;history.replaceState(null,"",e)}}))}}handleHiddenAttribute(){const e=document.querySelectorAll("[pp-visibility]"),t=document.querySelectorAll("[pp-display]"),n=this.handleElementVisibility.bind(this),s=this.handleElementDisplay.bind(this);e.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-visibility",n))),t.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-display",s)))}handleVisibilityElementAttribute(e,t,n){const s=e.getAttribute(t);if(s)if(this.isJsonLike(s)){n(e,this.parseJson(s))}else{const n=this.parseTime(s);if(n>0){const s="pp-visibility"===t?"visibility":"display",r="visibility"===s?"hidden":"none";this.scheduleChange(e,n,s,r)}}}handleElementVisibility(e,t){this.handleElementChange(e,t,"visibility","hidden","visible")}handleElementDisplay(e,t){this.handleElementChange(e,t,"display","none","block")}handleElementChange(e,t,n,s,r){const i=t.start?this.parseTime(t.start):0,o=t.end?this.parseTime(t.end):0;i>0?(e.style[n]=s,this.scheduleChange(e,i,n,r),o>0&&this.scheduleChange(e,i+o,n,s)):o>0&&this.scheduleChange(e,o,n,s)}handleAnchorTag(){document.querySelectorAll("a").forEach((e=>{e.addEventListener("click",(async e=>{const t=e.currentTarget,n=t.getAttribute("href"),s=t.getAttribute("target");if(n&&"_blank"!==s&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),!this._isNavigating)){this._isNavigating=!0;try{if(/^(https?:)?\/\//i.test(n)&&!n.startsWith(window.location.origin))window.location.href=n;else{const e=t.getAttribute("pp-append-params");if(n.startsWith("?")&&"true"===e){const e=new URL(window.location.href),t=new URLSearchParams(e.search);let s="";const[r,i]=n.split("#");i&&(s=`#${i}`);new URLSearchParams(r.split("?")[1]).forEach(((e,n)=>{t.set(n,e)}));const o=`${e.pathname}?${t.toString()}${s}`;history.pushState(null,"",o)}else{const[e,t]=n.split("#"),s=`${e}${t?`#${t}`:""}`;history.pushState(null,"",s)}const s=n.indexOf("#");if(-1!==s){const e=n.slice(s+1),t=document.getElementById(e);if(t)t.scrollIntoView({behavior:"smooth"});else{await this.handleNavigation();const t=document.getElementById(e);t&&t.scrollIntoView({behavior:"smooth"})}}else await this.handleNavigation()}}catch(e){console.error("Anchor click error:",e)}finally{this._isNavigating=!1}}}))}))}async handleNavigation(){try{const e=document.getElementById("loading-file-1B87E");if(e){const t=this.findLoadingElement(e,window.location.pathname);t&&await this.updateContentWithTransition(t)}const t=await this.fetch(window.location.href);if(!t.ok){console.error(`Navigation error: ${t.status} ${t.statusText}`);const e=await t.text();return void await this.updateDocumentContent(e)}const n=await t.text(),s=n.match(this._redirectRegex);if(s&&s[1])return void await this.redirect(s[1]);await this.updateDocumentContent(n)}catch(e){console.error("Navigation error:",e)}}findLoadingElement(e,t){let n=t;for(;;){const t=e.querySelector(`div[pp-loading-url='${n}']`);if(t)return t;if("/"===n)break;const s=n.lastIndexOf("/");n=s<=0?"/":n.substring(0,s)}return e.querySelector("div[pp-loading-url='/' ]")}async updateContentWithTransition(e){const t=document.querySelector("[pp-loading-content='true']")||document.body;if(!t)return;const{fadeIn:n,fadeOut:s}=this.parseTransition(e);await this.fadeOut(t,s),t.innerHTML=e.innerHTML,this.fadeIn(t,n)}parseTransition(e){let t=250,n=250;const s=e.querySelector("[pp-loading-transition]"),r=s?.getAttribute("pp-loading-transition");if(r){const e=this.parseJson(r);e&&"object"==typeof e?(t=this.parseTime(e.fadeIn??t),n=this.parseTime(e.fadeOut??n)):console.warn("pp-loading-transition is not valid JSON β†’ default values (250β€―ms) will be used. String:",r)}return{fadeIn:t,fadeOut:n}}fadeOut(e,t){return new Promise((n=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout((()=>{e.style.transition="",n()}),t)}))}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,e.style.opacity="1",setTimeout((()=>{e.style.transition=""}),t)}async updateDocumentContent(e){const t=this.saveScrollPositions(),n=(new DOMParser).parseFromString(e,"text/html"),s="pp-dynamic-script",r="pp-dynamic-link";document.head.querySelectorAll("[pp-dynamic-meta]").forEach((e=>e.remove()));document.head.querySelectorAll(`[${r}]`).forEach((e=>e.remove()));document.head.querySelectorAll(`[${s}]`).forEach((e=>e.remove()));await(async e=>{Array.from(e.head.children).forEach((e=>{const t=e.tagName;if("SCRIPT"===t&&e.hasAttribute(s)){const t=document.createElement("script");Array.from(e.attributes).forEach((e=>t.setAttribute(e.name,e.value))),e.textContent&&(t.textContent=e.textContent),document.head.appendChild(t)}else if("META"===t){if(e.getAttribute("charset")||"viewport"===e.getAttribute("name"))return;const t=e.name,n=e.getAttribute("property"),s=document.head.querySelector(t?`meta[name="${t}"]`:`meta[property="${n}"]`),r=document.head.querySelector("title");s?document.head.replaceChild(e.cloneNode(!0),s):r?.nextSibling?document.head.insertBefore(e.cloneNode(!0),r.nextSibling):document.head.appendChild(e.cloneNode(!0))}else if("TITLE"===t){const t=document.head.querySelector("title");t?document.head.replaceChild(e.cloneNode(!0),t):document.head.appendChild(e.cloneNode(!0))}else if("LINK"===t){const t=t=>{const n=document.head.querySelector('link[rel="icon"]');if(n)document.head.replaceChild(e.cloneNode(!0),n);else{const e=document.createElement("link");e.rel="icon",e.href=t,document.head.appendChild(e)}};if("icon"===e.getAttribute("rel")){t(e.href)}else if(e.hasAttribute(r)){const t=e.cloneNode(!0);document.head.appendChild(t)}}})),await this.populateDocumentBody(e)})(n),this.restoreScrollPositions(t),this.resetProps(),await this.processInlineModuleScripts(),this.initMakeReactive(),this.handlerAutofocusAttribute()}restoreScrollPositions(e){requestAnimationFrame((()=>{const t=e.window;t&&window.scrollTo(t.scrollLeft,t.scrollTop),document.querySelectorAll("*").forEach((t=>{const n=this.getElementKey(t);e[n]&&(t.scrollTop=e[n].scrollTop,t.scrollLeft=e[n].scrollLeft)}))}))}async populateDocumentBody(e){try{const t={DETAILS:(e,t)=>(t.open=e.open,!0),INPUT:(e,t)=>document.activeElement!==e||(t.value=e.value,"checked"in e&&(t.checked=e.checked),e.type.match(/^(text|search|url|email)$/)&&(t.selectionStart=e.selectionStart,t.selectionEnd=e.selectionEnd),!1),TEXTAREA:(e,n)=>t.INPUT(e,n),SELECT:(e,t)=>document.activeElement!==e||(t.selectedIndex=e.selectedIndex,!1),VIDEO:(e,t)=>(t.currentTime=e.currentTime,e.paused?t.pause():t.play(),!0),AUDIO:(e,n)=>t.VIDEO(e,n),CANVAS:()=>!1};morphdom(document.body,e.body,{getNodeKey(e){if(1===e.nodeType){const t=e;if(t.hasAttribute("pp-sync-script"))return`pp-sync-script:${t.getAttribute("pp-sync-script")}`;if(t.hasAttribute("key"))return t.getAttribute("key")}},onBeforeElUpdated(e,n){if("SCRIPT"===e.tagName)return!1;if(e.hasAttribute("data-nomorph"))return!1;const s=t[e.tagName];return!s||s(e,n)},onBeforeNodeDiscarded(e){if(e instanceof HTMLElement){const{timerId:t}=e.dataset;t&&clearTimeout(Number(t))}return!0}})}catch(e){console.error("Error populating document body:",e)}}saveScrollPositions(){const e={window:{scrollTop:window.scrollY||document.documentElement.scrollTop,scrollLeft:window.scrollX||document.documentElement.scrollLeft}};return document.querySelectorAll("*").forEach((t=>{(t.scrollTop||t.scrollLeft)&&(e[this.getElementKey(t)]={scrollTop:t.scrollTop,scrollLeft:t.scrollLeft})})),e}getElementKey(e){return e.id||e.className||e.tagName}async redirect(e){if(e)try{const t=new URL(e,window.location.origin);t.origin!==window.location.origin?window.location.href=e:(history.pushState(null,"",e),await this.handleNavigation())}catch(e){console.error("Redirect error:",e)}}abortActiveRequest(){this._activeAbortController&&this._activeAbortController.abort()}async fetch(e,t,n=!1){let s;return n?(this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=new AbortController,s=this._activeAbortController):s=new AbortController,fetch(e,{...t,signal:s.signal,headers:{...t?.headers,"X-Requested-With":"XMLHttpRequest"}})}isJsonLike(e){return"string"==typeof e&&((e=e.trim()).startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]"))}parseJson(e){try{return JSON5.parse(e)}catch(e){return console.error(`Error parsing JSON: ${e.message}. Please ensure the JSON string is valid.`,e),{}}}parseTime(e){if("number"==typeof e)return e;const t=e.match(/^(\d+)(ms|s|m)?$/);if(t){const e=parseInt(t[1],10);switch(t[2]||"ms"){case"ms":default:return e;case"s":return 1e3*e;case"m":return 60*e*1e3}}return 0}scheduleChange(e,t,n,s){setTimeout((()=>{requestAnimationFrame((()=>{e.style[n]=s}))}),t)}async processInlineModuleScripts(){const e=window;e.__PPHP_INLINE_DEPTH__=(e.__PPHP_INLINE_DEPTH__??0)+1;try{const e=Array.from(document.body.querySelectorAll('script[type="text/php"]:not([src])')).filter((e=>{const t=e.getAttribute("pp-section-id")??e.closest("[pp-section-id]")?.getAttribute("pp-section-id")??null;return t?!this._processedPhpSections.has(t):!this._processedPhpScripts.has(e)}));if(0===e.length)return;const t={};for(const n of e){const e=n.getAttribute("pp-section-id")??n.closest("[pp-section-id]")?.getAttribute("pp-section-id")??null;if(!e)continue;const s=n.textContent||"";for(const[,n]of s.matchAll(/export\s+const\s+([A-Za-z_$]\w*)/g))t[n]=e}for(const n of e){const e=n.getAttribute("pp-section-id")??n.closest("[pp-section-id]")?.getAttribute("pp-section-id")??null;let s=(n.textContent||"").trim();e&&(s=s.replace(/(\bpphp\.state\(\s*['"])([^'"]+)(['"])/g,((t,n,s,r)=>n+(s.startsWith(`${e}_`)?s:`${e}_${s}`)+r))),s=s.replace(/\b([A-Za-z_$]\w*)\s*\(/g,((e,n)=>{const s=t[n];return s?`${s}_${n}(`:e}));const r=new Blob([s],{type:"application/javascript"}),i=URL.createObjectURL(r),o=PPHP.prototype._currentSectionId;e&&(PPHP.prototype._currentSectionId=()=>e);try{const t=await import(i);for(const[n,s]of Object.entries(t))if("function"==typeof s){const t=e?`${e}_${n}`:n;window[t]=s}}catch(e){console.error("Inline module import failed:",e)}finally{PPHP.prototype._currentSectionId=o,URL.revokeObjectURL(i),e?this._processedPhpSections.add(e):this._processedPhpScripts.add(n)}}}finally{e.__PPHP_INLINE_DEPTH__--,0===e.__PPHP_INLINE_DEPTH__&&requestAnimationFrame((()=>{this._pendingEffects.forEach((e=>{try{e()}catch(e){console.error("effect error:",e)}this._effects.add(e)})),this._pendingEffects.clear()}))}}async fetchFunction(e,t={},n=!1){try{const s={callback:e,...t},r=window.location.href;let i;if(Object.keys(s).some((e=>{const t=s[e];return t instanceof File||t instanceof FileList&&t.length>0}))){const e=new FormData;Object.keys(s).forEach((t=>{const n=s[t];n instanceof File?e.append(t,n):n instanceof FileList?Array.from(n).forEach((n=>e.append(t,n))):e.append(t,n)})),i={method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:e}}else i=this.createFetchOptions(s);const o=await this.fetch(r,i,n);if(!o.ok)throw new Error(`Fetch failed with status: ${o.status} ${o.statusText}`);const a=await o.text();try{return JSON.parse(a)}catch{return a}}catch(e){throw console.error("Error in fetchFunction:",e),new Error("Failed to fetch data.")}}processSyncScripts(e){e.forEach((e=>{const t=`script[pp-sync-script="${CSS.escape(e)}"]`,n=document.querySelector(t);if(n){n.remove();const e=document.createElement("script");Array.from(n.attributes).forEach((t=>{e.setAttribute(t.name,t.value)})),n.src?e.src=n.src:e.textContent=n.textContent,e.type=n.type||"module",document.body.appendChild(e)}}))}async sync(...e){try{const t=this.saveScrollPositions();this.saveElementState();const n=e.length>0?e.map((e=>`pp-sync="${e}"`)):['pp-sync="true"'],s=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()}),r=await this.fetch(window.location.href,s),i=await r.text(),o=(new DOMParser).parseFromString(i,"text/html"),a=new Set;n.forEach((e=>{const t=document.querySelectorAll(`[${e}]`),n=o.body.querySelectorAll(`[${e}]`);t.forEach(((e,t)=>{const s=n[t];if(s){if(s.hasAttribute("pp-sync-script")){const e=s.getAttribute("pp-sync-script")||"";e&&a.add(e)}s.querySelectorAll("[pp-sync-script]").forEach((e=>{const t=e.getAttribute("pp-sync-script")||"";t&&a.add(t)})),e.innerHTML=s.innerHTML,this.reRunScripts(e)}}))})),this.processSyncScripts(a),this.restoreElementState(),this.restoreScrollPositions(t),this.attachWireFunctionEvents()}catch(e){console.error("Error in pphpSync:",e)}}async fetchAndUpdateBodyContent(){const e=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});this.abortActiveRequest();const t=await this.fetch(window.location.href,e,!0),n=await t.text();await this.updateBodyContent(n)}reRunScripts(e){e.querySelectorAll("script").forEach((e=>{const t=document.createElement("script");Array.from(e.attributes).forEach((e=>{t.setAttribute(e.name,e.value)})),e.hasAttribute("src")||(t.textContent=e.textContent),e.parentNode?.replaceChild(t,e)}))}copyCode(e,t,n,s,r="img",i=2e3){if(!(e instanceof HTMLElement))return;const o=e.closest(`.${t}`)?.querySelector("pre code"),a=o?.textContent?.trim()||"";a?navigator.clipboard.writeText(a).then((()=>{const t=e.querySelector(r);if(t)for(const[e,n]of Object.entries(s))e in t?t[e]=n:t.setAttribute(e,n);setTimeout((()=>{if(t)for(const[e,s]of Object.entries(n))e in t?t[e]=s:t.setAttribute(e,s)}),i)}),(()=>{alert("Failed to copy command to clipboard")})):alert("Failed to find the code block to copy")}getCookie(e){return document.cookie.split("; ").find((t=>t.startsWith(e+"=")))?.split("=")[1]||null}}class PPHPLocalStore{state;static instance=null;listeners;pphp;STORAGE_KEY;constructor(e={}){this.state=e,this.listeners=[],this.pphp=PPHP.instance,this.STORAGE_KEY=this.pphp.getCookie("pphp_local_store_key")||"pphp_local_store_59e13",this.loadState()}static getInstance(e={}){return PPHPLocalStore.instance||(PPHPLocalStore.instance=new PPHPLocalStore(e)),PPHPLocalStore.instance}setState(e,t=!1){if(this.state={...this.state,...e},this.listeners.forEach((e=>e(this.state))),this.saveState(),t){const e=localStorage.getItem(this.STORAGE_KEY);e&&this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:e})}}saveState(){localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.state))}loadState(){const e=localStorage.getItem(this.STORAGE_KEY);e&&(this.state=this.pphp.parseJson(e),this.listeners.forEach((e=>e(this.state))))}resetState(e,t=!1){if(e?(delete this.state[e],this.saveState()):(this.state={},localStorage.removeItem(this.STORAGE_KEY)),this.listeners.forEach((e=>e(this.state))),t){const t=e?localStorage.getItem(this.STORAGE_KEY):null;this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:t})}}}class SearchParamsManager{static instance=null;listeners=[];constructor(){}static getInstance(){return SearchParamsManager.instance||(SearchParamsManager.instance=new SearchParamsManager),SearchParamsManager.instance}get params(){return new URLSearchParams(window.location.search)}get(e){return this.params.get(e)}set(e,t){const n=this.params;n.set(e,t),this.updateURL(n)}delete(e){const t=this.params;t.delete(e),this.updateURL(t)}replace(e){const t=new URLSearchParams;for(const n in e){const s=e[n];null!==s&&t.set(n,s)}this.updateURL(t,!0)}updateURL(e,t=!1){const n=`${window.location.pathname}?${e.toString()}`;t?history.replaceState(null,"",n):history.pushState(null,"",n),this.notifyListeners(e)}listen(e){this.listeners.push(e)}notifyListeners(e){for(const t of this.listeners)t(e)}enablePopStateListener(){window.addEventListener("popstate",(()=>{this.notifyListeners(this.params)}))}}var pphp=PPHP.instance,store=PPHPLocalStore.getInstance(),searchParams=SearchParamsManager.getInstance();
1
+ (()=>{const e=EventTarget.prototype.addEventListener,t=EventTarget.prototype.removeEventListener,n=new Map;EventTarget.prototype.addEventListener=function(t,s,r){n.has(this)||n.set(this,new Map);const i=n.get(this).get(t)||new Set;i.add(s),n.get(this).set(t,i),e.call(this,t,s,r)},EventTarget.prototype.removeEventListener=function(e,s,r){if(n.has(this)&&n.get(this).has(e)){const t=n.get(this).get(e);t&&(t.delete(s),0===t.size&&n.get(this).delete(e))}t.call(this,e,s,r)},EventTarget.prototype.removeAllEventListeners=function(e){if(n.has(this)&&n.get(this).has(e)){const s=n.get(this).get(e);s&&(s.forEach((n=>{t.call(this,e,n)})),n.get(this).delete(e))}};const s=Symbol("pphp_remove_all");EventTarget.prototype[s]||Object.defineProperty(EventTarget.prototype,s,{value(e){const s=n.get(this);if(!s)return;const r=e?[e]:[...s.keys()];for(const e of r){const n=s.get(e);n&&(n.forEach((n=>t.call(this,e,n))),s.delete(e))}},writable:!1,enumerable:!1,configurable:!0})})();class PPHP{props={};static _instance;_isNavigating=!1;_responseData=null;_activeAbortController=null;_rawProps={};_elementState={checkedElements:new Set};_reservedWords;_bindings=[];_pendingBindings=new Set;_updateScheduled=!1;_templateStore=new WeakMap;_proxyCache=new WeakMap;_scopedKeys=new Map;_processedPhpSections=new Set;_processedPhpScripts=new WeakSet;_effects=new Set;_pendingEffects=new Set;_refs=new Map;_declaredStateRoots=new Set;_eventHandlers;_redirectRegex=/redirect_7F834\s*=\s*(\/[^\s]*)/;_mustacheRe=/\{\{\s*([\s\S]+?)\s*\}\}/gu;_assignmentRe=/^\s*[\w.]+\s*=(?!=)/;_htmlEntitiesRe=/&quot;|&#039;|&amp;/g;_mutators;_arrayMethodCache=new WeakMap;static _mustacheTest=/\{\{\s*[\s\S]+?\s*\}\}/;static _mustachePattern=/\{\{\s*([\s\S]+?)\s*\}\}/g;constructor(){const e=["focus","blur","click","scrollIntoView","select","setSelectionRange","show","showModal","requestFullscreen"];for(const t of e){const e=HTMLElement.prototype;if("function"==typeof e[t]&&!e[`__pphp_${t}_patched`]){const n=e[t];e[t]=function(...e){requestAnimationFrame((()=>n.apply(this,e)))},e[`__pphp_${t}_patched`]=!0}}const t=Object.getOwnPropertyNames(HTMLElement.prototype).filter((e=>e.startsWith("on"))),n=Object.getOwnPropertyNames(Document.prototype).filter((e=>e.startsWith("on"))),s=Object.getOwnPropertyNames(Window.prototype).filter((e=>e.startsWith("on")));this._eventHandlers=new Set([...t,...n,...s].map((e=>e.toLowerCase()))),this._reservedWords=new Set(["null","undefined","true","false","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","let","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","async","await","implements","interface","event","NaN","Infinity","Number","String","Boolean","Object","Array","Function","Date","RegExp","Error","JSON","Math","Map","Set"]),this._mutators=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]),this.handlePopState(),this.props=this.makeReactive(this._rawProps),this.scheduleInitialHydration()}static get instance(){return PPHP._instance||(PPHP._instance=new PPHP),PPHP._instance}scheduleInitialHydration(){const e=async()=>{this.initRefs(),await this.processInlineModuleScripts(),this.initializeAllReferencedProps(),this.initBindings(),this.initLoopBindings(),this.attachWireFunctionEvents(),this._bindings.forEach((e=>e.update())),requestAnimationFrame((()=>{document.documentElement.setAttribute("data-initial-hydrated",""),this.handlerAutofocusAttribute()}))};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>e()),{once:!0}):e()}static _isBuiltIn=(()=>{const e=new Map,t=[Object.prototype,Function.prototype,Array.prototype,String.prototype,Number.prototype,Boolean.prototype,Date.prototype,RegExp.prototype,Map.prototype,Set.prototype,WeakMap.prototype,WeakSet.prototype,Error.prototype,Promise.prototype];return n=>{const s=e.get(n);if(void 0!==s)return s;const r=n in globalThis||t.some((e=>n in e));return e.set(n,r),r}})();initRefs(){document.querySelectorAll("[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),n=this._refs.get(t)||[];n.push(e),this._refs.set(t,n),e.removeAttribute("pp-ref")}))}ref(e,t){const n=this._refs.get(e)||[];if(null!=t){const s=n[t];if(!s)throw new Error(`pphp.ref('${e}', ${t}) β€” no element at that index`);return s}if(0===n.length)throw new Error(`pphp.ref('${e}') failed β€” no element was found`);return 1===n.length?n[0]:n}_currentSectionId(){const e=document.currentScript;return e?.closest("[pp-section-id]")?.getAttribute("pp-section-id")||null}getNested(e,t){return t.split(".").reduce(((e,t)=>e?e[t]:void 0),e)}setNested(e,t,n){const s=t.split("."),r=s.pop();s.reduce(((e,t)=>e[t]??={}),e)[r]=n}hasNested(e,t){return void 0!==this.getNested(e,t)}scopeKey(e){const t=this._currentSectionId();return t?e.startsWith(`${t}_`)?e:e.includes(".")?e.replace(/^([^\.]+)/,`${t}_$1`):`${t}_${e}`:e}alreadyScoped(e,t){const n=`${t}_${e}`;return this._scopedKeys.get(t)?.has(n)??!1}scheduleFlush(){this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this._updateScheduled=!1,this.flushBindings()})))}effect(e,t){const n=this._currentSectionId(),s=Array.isArray(t),r=s?t:[],i=s&&0===r.length,o=r.map((e=>{if("function"==typeof e&&e.__pphp_key)return e.__pphp_key;if("string"!=typeof e)return"";if(e.includes("_"))return e;for(const[t,n]of this._scopedKeys)if(n.has(e))return`${t}_${e}`;return n?`${n}_${e}`:e})).filter(Boolean);if(e.__deps=new Set(o),i){try{e()}catch(e){console.error("effect error:",e)}return()=>{}}const a=(window.__PPHP_INLINE_DEPTH__??0)>0?this._pendingEffects:this._effects;return a.delete(e),a.add(e),()=>{this._effects.delete(e),this._pendingEffects.delete(e)}}state(e,t){const n=this._currentSectionId(),s=e;if(this._reservedWords.has(s))throw new Error(`'${s}' is reserved (native object) – choose another state key.`);e=this.scopeKey(e),this._declaredStateRoots.add(e),n&&(this._scopedKeys.has(n)||this._scopedKeys.set(n,new Set),this._scopedKeys.get(n).add(s)),this.hasNested(pphp.props,e)||this.setNested(pphp.props,e,t),this._reservedWords.has(s)||Object.defineProperty(globalThis,s,{configurable:!0,enumerable:!0,get:()=>this.getNested(pphp.props,e),set:t=>{this.setNested(pphp.props,e,t),this.scheduleFlush()}});const r=()=>this.getNested(pphp.props,e),i=()=>r();return Object.defineProperties(i,{valueOf:{value:()=>r()},toString:{value:()=>String(r())}}),[i,t=>{const n="function"==typeof t?t(r()):t;this.setNested(pphp.props,e,n),this.scheduleFlush()}]}extractDependencies(e){let t=e.replace(/\?\./g,".");const n=new Set,s=/(?:^|[^\w$])(?:\(\s*([^)]*?)\s*\)|([A-Za-z_$][\w$]*))\s*=>/g;for(let e;e=s.exec(t);){(e[1]??e[2]??"").split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>n.add(e)))}t=t.replace(/`([^`\\]|\\.)*`/g,(e=>[...e.matchAll(/\$\{([^}]*)\}/g)].map((e=>e[1])).join(" "))),t=t.replace(/(['"])(?:\\.|[^\\])*?\1/g,""),t=t.replace(/\/(?:\\.|[^\/\\])+\/[gimsuy]*/g,"");const r=new Set,i=/\b[A-Za-z_$]\w*(?:\.[A-Za-z_$]\w*)*\b/g;for(const e of t.match(i)??[]){const t=e.split(".")[0];n.has(t)||PPHP._isBuiltIn(t)||r.add(e)}return r}formatValue(e){return"function"==typeof e?"":"boolean"==typeof e?e?"true":"false":Array.isArray(e)?e.map((e=>"object"==typeof e?JSON.stringify(e):String(e))).join(", "):e&&"object"==typeof e?Object.keys(e).length?JSON.stringify(e,null,2):"":e?.toString()??""}registerBinding(e,t,n="text",s){if(this._assignmentRe.test(t))return;const r=e.parentElement?.closest("[pp-section-id]"),i=r?.getAttribute("pp-section-id");let o=t;if(i){const e=this._scopedKeys.get(i),n=e instanceof Set?e:new Set(Array.isArray(e)?e:[]);o=t.replace(/\b([A-Za-z_$][\w$]*)\b/g,((e,t,s,r)=>{const o=n.has(t),a=n.has(`${i}_${t}`);return o||a?"."===r[s-1]||this._reservedWords.has(t)||e.startsWith(`${i}_`)?e:`${i}_${t}`:e}))}const a=new Set([...this.extractDependencies(o)].map((e=>e.split(".")[0])).filter((e=>e in this.props&&!this._reservedWords.has(e)))),c=this.makeSafeEvaluator(o);if("value"===s||"checked"===s){const t=this.makePrimitiveUpdater(e,s,c);return void this._bindings.push({dependencies:a,update:t})}if(s){const t=e.getAttribute(s)??"";if(this._mustacheRe.test(o)||this._mustacheRe.test(t)){const n=t.replace(this._mustacheRe,((e,t)=>{let n=t;if(i){const e=this._scopedKeys.get(i),s=e instanceof Set?e:new Set(Array.isArray(e)?e:[]);n=t.replace(/\b([A-Za-z_$][\w$]*)\b/g,((e,t,n,r)=>{const o=s.has(t),a=s.has(`${i}_${t}`);return o||a?"."===r[n-1]||this._reservedWords.has(t)||e.startsWith(`${i}_`)?e:`${i}_${t}`:e}))}return`{{ ${n} }}`})),r=this.makeAttrTemplateUpdater(e,s,a,n);return void this._bindings.push({dependencies:a,update:r})}const n=()=>{try{const t=c(this.props),n=this.formatValue(t);s in e&&(e[s]=n),e.setAttribute(s,n)}catch(e){console.error(`Error evaluating "${s}"="${o}"`,e)}};return void this._bindings.push({dependencies:a,update:n})}const l={text:(e,t)=>{e.textContent!==t&&(e.textContent=t)},value:(e,t)=>{e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement?e.value!==t&&(e.value=t):e.setAttribute("value",t)},checked:(e,t)=>{e instanceof HTMLInputElement?e.checked="true"===t:e.setAttribute("checked",t)},attr:(e,t)=>{e.setAttribute("attr",t)}};this._bindings.push({dependencies:a,update:()=>{try{const t=c(this.props),s=this.formatValue(t);l[n](e,s)}catch(e){console.error(`Error evaluating expression "${o}".`,e)}}})}makePrimitiveUpdater(e,t,n){const s={};return this._eventHandlers.forEach((e=>{if(e.startsWith("on")){const t=e.slice(2);s[t]=t}})),s.value="input",s.checked="change",()=>{try{const r=n(this.props),i=this.formatValue(r);let o=!1;if("value"===t){const t=e;"value"in e&&t.value!==i?(t.value=i,o=!0):"value"in e||(e.setAttribute("value",i),o=!0)}else{const t=e,n="true"===i;"checked"in e&&t.checked!==n?(t.checked=n,o=!0):"checked"in e||(e.setAttribute("checked",i),o=!0)}if(!o||e instanceof HTMLInputElement&&("hidden"===e.type||e.disabled||e.readOnly))return;const a=e.getAttribute("pp-dispatch-event")||s[t]||t,c="click"===a?new MouseEvent(a,{bubbles:!0,cancelable:!0}):new Event(a,{bubbles:!0});e.dispatchEvent(c)}catch(e){console.error(`Error evaluating attribute "${t}":`,e)}}}makeAttrTemplateUpdater(e,t,n,s){let r=this._templateStore.get(e);r||(r=new Map,this._templateStore.set(e,r)),r.has(t)||r.set(t,e.getAttribute(t)||"");const i=s??r.get(t)??"";return(i.match(this._mustacheRe)||[]).forEach((e=>{this.extractDependencies(e).forEach((e=>n.add(e)))})),()=>{try{const n=i.replace(this._mustacheRe,((e,t)=>{try{const e=this.makeSafeEvaluator(t);return this.formatValue(e(this.props))}catch(e){return console.error("Error token:",t,e),""}}));e.getAttribute(t)!==n&&e.setAttribute(t,n)}catch(e){console.error(`Error evaluating the template for attribute "${t}". Please check the template syntax and dependencies.`,e)}}}initBindings(){this._bindings=[];const e=new WeakSet;document.body.querySelectorAll("[pp-if]").forEach((t=>{if(e.has(t))return;const n=[];let s=t;for(;s;){if(s.hasAttribute("pp-if"))n.push({el:s,expr:s.getAttribute("pp-if")});else if(s.hasAttribute("pp-elseif"))n.push({el:s,expr:s.getAttribute("pp-elseif")});else{if(!s.hasAttribute("pp-else"))break;n.push({el:s,expr:null})}e.add(s),s=s.nextElementSibling}n.forEach((e=>{if(null!==e.expr){const t=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractDependencies(t);const n=this.makeSafeEvaluator(t);e.evaluate=()=>!!n(this.props)}}));const r=new Set;n.forEach((e=>e.deps?.forEach((e=>r.add(e)))));this._bindings.push({dependencies:r,update:()=>{let e=!1;for(const{el:t,expr:s,evaluate:r}of n)!e&&null!==s&&r()?(t.removeAttribute("hidden"),e=!0):e||null!==s?t.setAttribute("hidden",""):(t.removeAttribute("hidden"),e=!0)}})})),document.body.querySelectorAll("*").forEach((e=>{["pp-bind","pp-bind-expr"].forEach((t=>{const n=e.getAttribute(t);n&&this.registerBinding(e,n,"text")})),Array.from(e.attributes).forEach((t=>{if(!t.name.startsWith("pp-bind-"))return;if("pp-bind"===t.name||"pp-bind-expr"===t.name||"pp-bind-spread"===t.name)return;const n=t.value.replace(this._htmlEntitiesRe,(e=>"&quot;"===e?'"':"&#039;"===e?"'":"&")).replace(/^{{\s*|\s*}}$/g,"");let s=t.name.replace(/^(pp-bind-)+/,"");const r=s.toLowerCase();"html"!==r&&"innerhtml"!==r||(s="innerHTML");const i="value"===s?"value":"checked"===s?"checked":"text";this.registerBinding(e,n,i,s)})),Array.from(e.attributes).forEach((t=>{if("pp-bind-spread"!==t.name)return;const n=t.value.split(",").map((e=>e.trim())).filter(Boolean),s=new Set;n.forEach((e=>s.add(e.split(".")[0])));const r=new Set;this._bindings.push({dependencies:s,update:()=>{try{const t={};n.forEach((e=>{const n=this.getNested(this.props,e)??{};Object.assign(t,n)})),r.forEach((n=>{n in t||e.hasAttribute(n)||(e.removeAttribute(n),r.delete(n))})),Object.entries(t).forEach((([t,n])=>{if(!r.has(t)&&e.hasAttribute(t))return;if(!1===n||null==n)return void(r.has(t)&&(e.removeAttribute(t),r.delete(t)));const s="object"==typeof n?JSON.stringify(n):String(n);e.getAttribute(t)!==s&&e.setAttribute(t,s),r.add(t)}))}catch(e){console.error("pp-spread error:",e)}}})}))}))}safeNull=new Proxy({},{get:(e,t)=>t===Symbol.toPrimitive?()=>{}:PPHP._isBuiltIn(t.toString())?(console.warn(`PPHP Warning: The property or method name "${t.toString()}" conflicts with a JavaScript built-in object or function. Please choose a unique name to avoid unexpected behavior.`),()=>""):this.safeNull,apply:()=>""});safeTag=(e,...t)=>e.reduce(((e,n,s)=>{const r=t[s];return e+n+(null==r||"object"==typeof r?"":r)}),"");makeSafeEvaluator(e){let t=e.trim();const n=t.replace(/\?\./g,".");if(/^\(\s*\)\s*=>/.test(t)&&(t=`(${t})()`),t.startsWith("`")&&t.endsWith("`")){const e=new Function("props","safeTag",`\n try {\n with (props) {\n return safeTag${t};\n }\n } catch (e) {\n console.error("PPHP template eval error for:", ${JSON.stringify(t)}, e);\n return "";\n }\n `);return t=>e(t,this.safeTag.bind(this))}const s=n.replace(/(["'])(?:(?=(\\?))\2.)*?\1/g,"").match(/\b[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*\b/g)||[],r=new Set(s.map((e=>e.split(".")[0])).filter((e=>/^[A-Za-z_$][\w$]*$/.test(e)&&!this._reservedWords.has(e)&&"safeTag"!==e))),i=Array.from(r).map((e=>`\n const ${e} = ctx["${e}"] !== undefined\n ? ctx["${e}"]\n : (typeof window !== "undefined" && window["${e}"] !== undefined\n ? window["${e}"]\n : ${new RegExp(`\\b${e}\\.`).test(n)?"{}":"void 0"});\n if (typeof window !== "undefined" && window["${e}"] !== ${e}) {\n window["${e}"] = ${e};\n }\n `)).join("\n"),o=/^\s*[\w\.]+\s*=(?!=)/.test(t),a=new Function("ctx","safeTag",`\n "use strict";\n ${i}\n try {\n ${o?t+"; return '';":"const result = "+t+"; return result === undefined || result === null ? '' : result;"}\n } catch (e) {\n return "";\n }\n `);return e=>a(e,this.safeTag.bind(this))}setNestedProperty(e,t,n){const s=t.split(".");let r=e;for(let e=0;e<s.length-1;e++)s[e]in r||(r[s[e]]={}),r=r[s[e]];r[s[s.length-1]]=n}resetProps(){Object.keys(this._rawProps).forEach((e=>{if(window.hasOwnProperty(e)){const t=Object.getOwnPropertyDescriptor(window,e);t&&t.configurable&&delete window[e]}})),this._rawProps={},this._proxyCache=new WeakMap,this._templateStore=new WeakMap,this._processedPhpSections=new Set,this._processedPhpScripts=new WeakSet,this._scopedKeys=new Map,this._effects=new Set,this._pendingEffects=new Set,this._bindings=[],this.props=this.makeReactive(this._rawProps)}initializeAllReferencedProps(){const e=PPHP._mustachePattern,t=PPHP._mustacheTest,n=this.props,s=new Set,r=(e,t)=>{const n=e.getAttribute("pp-section-id"),s=e.parentElement?.closest("[pp-section-id]")?.getAttribute("pp-section-id")??null,r=n??s;return r?`${r}_${t}`:t},i=(()=>{const e=new Set([...Object.getOwnPropertyNames(String.prototype),...Object.getOwnPropertyNames(Array.prototype),...Object.getOwnPropertyNames(Number.prototype),...Object.getOwnPropertyNames(Boolean.prototype),...Object.getOwnPropertyNames(Object.prototype),...Object.getOwnPropertyNames(Date.prototype),...Object.getOwnPropertyNames(RegExp.prototype)]);return t=>e.has(t)})(),o=(e,t)=>{const[n,o,...a]=t.split(".");if(PPHP._isBuiltIn(n)||this._reservedWords.has(n))return void console.warn(`Invalid path β€œ${t}” while initialising props – the root identifier is reserved or built‑in.`);if(o&&i(o))return void s.add(r(e,n));const c=r(e,n);s.add(o?`${c}.${[o,...a].join(".")}`:c)};for(const n of document.body.getElementsByTagName("*"))for(const{name:s,value:r}of Array.from(n.attributes))if(r){if(t.test(r))for(const t of r.matchAll(e))this.extractDependencies(t[1]).forEach((e=>o(n,e)));"pp-if"!==s&&"pp-elseif"!==s||this.extractDependencies(r).forEach((e=>o(n,e))),s.startsWith("pp-bind")&&this.extractDependencies(r).forEach((e=>o(n,e)))}const a=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT,{acceptNode:e=>e.parentElement?.closest("pre,code,[pp-ignore='true']")?NodeFilter.FILTER_REJECT:t.test(e.nodeValue||"")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});for(let t;t=a.nextNode();){const n=t.parentElement;for(const s of t.nodeValue.matchAll(e))this.extractDependencies(s[1]).forEach((e=>o(n,e)))}const c=Array.from(s).sort(((e,t)=>t.split(".").length-e.split(".").length));for(const e of c){const t=e.split(".");let s=n;for(let n=0;n<t.length;n++){const r=t[n],i=n===t.length-1;if(0===n&&PPHP._isBuiltIn(r)){console.warn(`Skipping root β€œ${r}” inside path β€œ${e}” – collides with a JS built‑in.`);break}r in s&&(i||null!=s[r]&&"object"==typeof s[r])||(s[r]=i?void 0:{}),s=s[r]}}const l=new Set(c.map((e=>e.split(".")[0])));for(const e of this._declaredStateRoots)l.add(e);for(const e of l)e in globalThis||Object.defineProperty(globalThis,e,{configurable:!0,enumerable:!0,get:()=>n[e],set:t=>n[e]=t})}scheduleBindingUpdate(e){this._pendingBindings.add(e),this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this.flushBindings()})))}flushBindings(){const e=new Set;this._pendingBindings.forEach((t=>{t.dependencies.forEach((t=>e.add(t))),t.update()})),this._pendingBindings.clear(),this._updateScheduled=!1,this._effects.forEach((t=>{const n=t.__deps||new Set;if(0===n.size||[...n].some((t=>e.has(t))))try{t()}catch(e){console.error("effect error:",e)}}))}initMakeReactive(){this.initializeAllReferencedProps(),this.initBindings(),this.initLoopBindings(),this.attachWireFunctionEvents(),this._bindings.forEach((e=>e.update()))}getProxiedProps(e){let t=this._proxyCache.get(e);if(t)return t;return t=new Proxy(e,{get:(e,t)=>t in e?e[t]:void 0,set:(e,t,n)=>(e[t]=n,!0)}),this._proxyCache.set(e,t),t}async invokeHandler(e,t,n){try{const s=t.trim(),r=s.replace(/(["'`])(?:\\.|(?!\1).)*\1/g,"").replace(/\/(?:\\.|[^\/])+\/[gimsuy]*/g,"");if(/^\(?\s*[^=]*?\)?\s*=>/.test(r.trim())){const t=new Function("event","proxy","props",`\n with (proxy) {\n const val = (${s});\n return (typeof val === "function")\n ? val.call(this, event, props)\n : val;\n }\n `),r=this.getProxiedProps(pphp.props);return void await t.call(e,n,r,pphp.props)}const i=t.match(/^(\w+(\.\w+)*)\((.*)\)$/);if(i){const s=i[1],r=i[3],o=s.split("."),{context:a,methodName:c}=this.resolveContext(o);if("function"==typeof a[c])if(this.isJsonLike(r)){const t=this.parseJson(r);t.element=e,t.event=n;const s=[t];await a[c](...s)}else new Function("event",t).call(e,n);else await this.handleParsedCallback(e,t)}else if(t.includes("=")){const s=t.match(/^\s*([\w\.]+)\s*=/);if(s){const e=s[1];if(e.includes(".")){const t=e.split(".");let n=pphp.props;for(let e=0;e<t.length-1;e++){const s=t[e];s in n&&null!=n[s]&&"object"==typeof n[s]||(n[s]={}),n=n[s]}}else e in pphp.props||(pphp.props[e]=void 0)}new Function("event","props",`\n with (new Proxy(props, {\n get(target, key) {\n return key in target ? target[key] : undefined;\n },\n set(target, key, value) {\n target[key] = value;\n return true;\n }\n })) {\n ${t}\n }\n `).call(e,n,pphp.props)}else await this.handleParsedCallback(e,t)}catch(e){console.error(`Error executing handler "${t}". Please ensure the handler is defined and valid.`,e)}finally{this.scheduleFlush()}}registerLoop(e){const t=e.getAttribute("pp-for").trim(),[n,s]=t.split(/\s+in\s+/),[r,i]=n.replace(/^\(|\)$/g,"").split(",").map((e=>e.trim())),o=e.parentNode,a=document.createComment("pp-for");o.insertBefore(a,e),o.removeChild(e);const c=this.makeSafeEvaluator(s),l=this.extractDependencies(s);this._bindings.push({dependencies:l,update:()=>{let t=a.nextSibling;for(;t&&t.nodeType!==Node.COMMENT_NODE;){const e=t.nextSibling;o.removeChild(t),t=e}(c(this.props)||[]).forEach(((t,n)=>{this.props[r]=t,i&&(this.props[i]=n);const s=e.content.cloneNode(!0),c=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null);let l;for(;l=c.nextNode();)l.nodeValue=(l.nodeValue||"").replace(PPHP._mustachePattern,((e,t)=>{try{const e=this.makeSafeEvaluator(t)(this.props);return this.formatValue(e)}catch{return""}}));s.querySelectorAll("*").forEach((e=>{Array.from(e.attributes).forEach((e=>{PPHP._mustacheTest.test(e.value)&&(e.value=e.value.replace(PPHP._mustachePattern,((e,t)=>{try{const e=this.makeSafeEvaluator(t)(this.props);return this.formatValue(e)}catch{return""}})))}))})),s.querySelectorAll("[pp-bind]").forEach((e=>{const t=e.getAttribute("pp-bind"),n=this.makeSafeEvaluator(t)(this.props);e.textContent=this.formatValue(n)})),s.querySelectorAll("[pp-bind-expr]").forEach((e=>{const t=e.getAttribute("pp-bind-expr"),n=this.makeSafeEvaluator(t)(this.props);e.textContent=this.formatValue(n)})),s.querySelectorAll("[pp-bind-class]").forEach((e=>{const t=e.getAttribute("pp-bind-class"),n=this.makeSafeEvaluator(t)(this.props);e.setAttribute("class",String(n))})),s.querySelectorAll("*").forEach((e=>{Array.from(e.attributes).forEach((t=>{if(t.name.startsWith("on")&&/\bidx?\b/.test(t.value)){const s=t.value.replace(/\bi\b/g,String(n)).replace(/\bidx\b/g,String(n));e.setAttribute(t.name,s)}}))})),o.insertBefore(s,a.nextSibling)})),this.attachWireFunctionEvents()}})}initLoopBindings(){document.querySelectorAll("[pp-for]").forEach((e=>this.registerLoop(e)))}makeReactive(e,t=[]){const n=this._proxyCache.get(e);if(n)return n;const s=this;if(e instanceof Map||e instanceof Set)return e;const r=new Proxy(e,{get(e,n,r){const i=Reflect.get(e,n,r);if(Array.isArray(e)&&s._mutators.has(n)){let o=s._arrayMethodCache.get(e);if(o||(o=new Map,s._arrayMethodCache.set(e,o)),!o.has(n)){const e=i,a=t.join("."),c=function(...t){const n=Reflect.apply(e,r,t);return queueMicrotask((()=>{s._bindings.forEach((e=>{e.dependencies.has(a)&&s.scheduleBindingUpdate(e)}))})),n};o.set(n,c)}return o.get(n)}return"object"==typeof i&&null!==i?s.makeReactive(i,[...t,n]):i},set(e,n,r){if(r&&"object"==typeof r&&(r=s.makeReactive(r,[...t,n.toString()])),e[n]=r,0===t.length){const e=n;s._reservedWords.has(e)||PPHP._isBuiltIn(e)||e in globalThis||Object.defineProperty(globalThis,e,{configurable:!0,enumerable:!0,get:()=>s.props[e],set(t){s.props[e]=t}})}const i=[...t,n].join(".");return s._bindings.forEach((e=>{for(const t of e.dependencies)if(i===t||i.startsWith(t+".")||t.startsWith(i+".")){s.scheduleBindingUpdate(e);break}})),!0}});return this._proxyCache.set(e,r),r}handlePopState(){window.addEventListener("popstate",(async()=>{await this.handleNavigation()}))}prefixFunctionCalls(e,t){return e.replace(/\b([A-Za-z_$][\w$]*)\s*\(/g,((e,n)=>this._reservedWords.has(n)||n.startsWith(`${t}_`)?e:this.alreadyScoped(n,t)?`${t}_${n}(`:e))}prefixIds(e,t){let n="",s=0,r=(e=this.prefixFunctionCalls(e,t)).length,i=!1,o=!1,a=!1;for(;s<r;){const c=e[s];if("'"!==c||o||a||"\\"===e[s-1])if('"'!==c||i||a||"\\"===e[s-1])if("`"!==c||i||o||"\\"===e[s-1])if(i||o||a)n+=c,s++;else if(/[A-Za-z_$]/.test(c)){let i=s+1;for(;i<r&&/[\w$]/.test(e[i]);)i++;const o=e.slice(s,i),a=e[s-1]??"",c=this._reservedWords.has(o),l="."===a;n+=!o.startsWith(`${t}_`)&&!l&&!c?`${t}_${o}`:o,s=i}else n+=c,s++;else a=!a,n+=c,s++;else o=!o,n+=c,s++;else i=!i,n+=c,s++}return n}attachWireFunctionEvents(){this.handleHiddenAttribute(),this.handleAnchorTag();const e=Array.from(this._eventHandlers).map((e=>`[${e}]`)).join(", ");document.body.querySelectorAll(e).forEach((e=>{const t=e.closest("[pp-section-id]")?.getAttribute("pp-section-id");if(Array.from(e.attributes).filter((e=>this._eventHandlers.has(e.name))).forEach((n=>{const s=n.name.slice(2);e.removeAllEventListeners(s);let r=n.value.trim();if(t){const e=r.indexOf("=>");if(-1!==e){const n=r.slice(0,e+2),s=r.slice(e+2);r=n+this.prefixIds(s,t)}else r=this.prefixIds(r,t)}e instanceof HTMLInputElement&&this.handleInputAppendParams(e,s),e.removeAttribute(n.name),this.handleDebounce(e,s,r)})),e instanceof HTMLFormElement){const n=e.getAttribute("onsubmit")?.trim();if(n){let s=n;t&&(s=s.replace(/^([A-Za-z_$][\w$]*)\s*\(/,((e,n)=>`${t}_${n}(`))),e.removeAttribute("onsubmit"),this.handleDebounce(e,"submit",s)}}}))}async handleDebounce(e,t,n){const s=e.getAttribute("pp-debounce")||"",r=e.getAttribute("pp-before-request")||"",i=e.getAttribute("pp-after-request")||"",o=async t=>{t.preventDefault();try{r&&await this.invokeHandler(e,r,t),await this.invokeHandler(e,n,t),i&&"@close"!==i&&await this.invokeHandler(e,i,t),this.handlerAutofocusAttribute()}catch(e){console.error("Error in debounced handler. Please check the handler logic and ensure it is functioning correctly.",e)}};if(s){const n=this.parseTime(s),r=this.debounce(o,n);e instanceof HTMLFormElement&&"submit"===t?e.addEventListener(t,(e=>{e.preventDefault(),r(e)})):e.addEventListener(t,r)}else e.addEventListener(t,o)}debounce(e,t=300,n=!1){let s;return function(...r){const i=this;s&&clearTimeout(s),s=setTimeout((()=>{s=null,n||e.apply(i,r)}),t),n&&!s&&e.apply(i,r)}}handlerAutofocusAttribute(){const e=document.querySelector("dialog[open]");let t=null;if(e&&(t=e.querySelector("[pp-autofocus]")),t||(t=document.querySelector("[pp-autofocus]")),!t)return;const n=t.getAttribute("pp-autofocus");if(!this.isJsonLike(n))return;const s=this.parseJson(n);requestAnimationFrame((()=>{t.focus(),(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&"function"==typeof this.setCursorPosition&&(t instanceof HTMLInputElement&&"number"===t.type?(t.type="text",this.setCursorPosition(t,s),t.type="number"):this.setCursorPosition(t,s))}))}async handleParsedCallback(e,t){const{funcName:n,data:s}=this.parseCallback(e,t);if(!n)return;const r=this[n],i=window[n];let o;if("function"==typeof r?o=r:"function"==typeof i&&(o=i),"function"==typeof o){const t=e.hasAttribute("pp-after-request"),n=Array.isArray(s.args)?s.args:[],r=this._responseData?this.parseJson(this._responseData):{response:this._responseData};let i={args:n,element:e,data:s};t&&(i={...i,...r}),await o.call(this,i)}else this._responseData=null,this._responseData=await this.handleUndefinedFunction(e,n,s)}async handleUndefinedFunction(e,t,n){const s={callback:t,...n},r=this.createFetchOptions(s),i=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});try{this.saveElementOriginalState(e),this.handleSuspenseElement(e);const s=new URL(window.location.href);let o="",a="",c={success:!1};const l=e.querySelector("input[type='file']");if(l){if(o=await this.fetchFileWithData(s.href,t,l,n),a=this.extractJson(o)||"",a)try{c=this.parseJson(a)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}else{const e=await this.fetch(s.href,r);if(o=await e.text(),this.getRedirectUrl(o))return void await this.redirect(this.getRedirectUrl(o)||"");if(a=this.extractJson(o)||"",a)try{c=this.parseJson(a)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}const p=e.getAttribute("pp-before-request")||"",h=e.getAttribute("pp-after-request")||"";if((p||h&&c.success)&&this.restoreSuspenseElement(e),p||h){let e="";if(c.success){e=o.replace(a,"")}else e=o;if(this.appendAfterbegin(e),!h&&!c.success)return}if(h&&c.success){this.handleAfterRequest(h,a);const e=o.replace(a,"");return this.appendAfterbegin(e),a}if("@close"===h)return c.success?a:void 0;const d=await this.fetch(s.href,i),u=await d.text();if(this.getRedirectUrl(u))return void await this.redirect(this.getRedirectUrl(u)||"");await this.handleResponseRedirectOrUpdate(o,u,a,c)}catch(e){console.error(`Error handling undefined function "${t}". Please ensure the function is defined and accessible.`,e)}}handleAfterRequest(e,t){if(!this.isJsonLike(e))return;const n=this.parseJson(e),s=t?this.parseJson(t):null,r=n.targets;Array.isArray(r)&&r.forEach((e=>{const{id:t,...n}=e,r=document.querySelector(t);let i={};if(s){for(const t in n)if(n.hasOwnProperty(t))switch(t){case"innerHTML":case"outerHTML":case"textContent":case"innerText":"response"===n[t]&&(i[t]=e.responseKey?s[e.responseKey]:s.response);break;default:i[t]=n[t]}}else i=n;r&&this.updateElementAttributes(r,i)}))}async handleResponseRedirectOrUpdate(e,t,n,s){const r=this.getUpdatedHTMLContent(e,n,s),i=(new DOMParser).parseFromString(t,"text/html");r&&i.body.insertAdjacentElement("afterbegin",r),this.updateBodyContent(i.body.outerHTML)}getUpdatedHTMLContent(e,t,n){const s=document.createElement("div");if(s.id="afterbegin-8D95D",n&&t?.success){const t=e.replace(n,"");s.innerHTML=t}else s.innerHTML=e;return s.innerHTML?s:null}async updateBodyContent(e){const t=this.saveScrollPositions();this.saveElementState();const n=(new DOMParser).parseFromString(e,"text/html");await this.appendCallbackResponse(n),this.restoreElementState(),this.restoreScrollPositions(t),await this.processInlineModuleScripts(),this.initMakeReactive()}restoreElementState(){if(this._elementState.focusId){const e=document.getElementById(this._elementState.focusId)||document.querySelector(`[name="${this._elementState.focusId}"]`);if(e instanceof HTMLInputElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&("checkbox"===e.type||"radio"===e.type?e.checked=!!this._elementState.focusChecked:"number"===e.type||"email"===e.type?(e.type="text",e.setSelectionRange(t,t),e.type="number"===e.type?"number":"email"):"date"===e.type||"month"===e.type||"week"===e.type||"time"===e.type||"datetime-local"===e.type||"color"===e.type||"file"===e.type||""!==e.value&&(e.value=this._elementState.focusValue)),e.focus()}else if(e instanceof HTMLTextAreaElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus()}else e instanceof HTMLSelectElement&&(this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus())}this._elementState.checkedElements.forEach((e=>{const t=document.getElementById(e);t&&(t.checked=!0)}))}async appendCallbackResponse(e){const t=e.getElementById("afterbegin-8D95D");if(t){const e=document.getElementById("afterbegin-8D95D");e?e.innerHTML=t.innerHTML:document.body.insertAdjacentHTML("afterbegin",t.outerHTML)}await this.populateDocumentBody(e)}saveElementState(){const e=document.activeElement;this._elementState.focusId=e?.id||e?.name,this._elementState.focusValue=e?.value,this._elementState.focusChecked=e?.checked,this._elementState.focusType=e?.type,this._elementState.focusSelectionStart=e?.selectionStart,this._elementState.focusSelectionEnd=e?.selectionEnd,this._elementState.isSuspense=e.hasAttribute("pp-suspense"),this._elementState.checkedElements.clear(),document.querySelectorAll('input[type="checkbox"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)})),document.querySelectorAll('input[type="radio"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)}))}updateElementAttributes(e,t){for(const n in t)if(t.hasOwnProperty(n))switch(n){case"innerHTML":case"outerHTML":case"textContent":case"innerText":e[n]=this.decodeHTML(t[n]);break;case"insertAdjacentHTML":e.insertAdjacentHTML(t.position||"beforeend",this.decodeHTML(t[n].html));break;case"insertAdjacentText":e.insertAdjacentText(t.position||"beforeend",this.decodeHTML(t[n].text));break;case"setAttribute":e.setAttribute(t.attrName,this.decodeHTML(t[n]));break;case"removeAttribute":e.removeAttribute(t[n]);break;case"className":e.className=this.decodeHTML(t[n]);break;case"classList.add":e.classList.add(...this.decodeHTML(t[n]).split(","));break;case"classList.remove":e.classList.remove(...this.decodeHTML(t[n]).split(","));break;case"classList.toggle":e.classList.toggle(this.decodeHTML(t[n]));break;case"classList.replace":const[s,r]=this.decodeHTML(t[n]).split(",");e.classList.replace(s,r);break;case"dataset":e.dataset[t.attrName]=this.decodeHTML(t[n]);break;case"style":Object.assign(e.style,t[n]);break;case"value":e.value=this.decodeHTML(t[n]);break;case"checked":e.checked=t[n];break;default:e.setAttribute(n,this.decodeHTML(t[n]))}}decodeHTML(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}appendAfterbegin(e){if(!e)return;const t="afterbegin-8D95D";let n=document.getElementById(t);n?(n.innerHTML=e,document.body.insertAdjacentElement("afterbegin",n)):(n=document.createElement("div"),n.id=t,n.innerHTML=e,document.body.insertAdjacentElement("afterbegin",n))}restoreSuspenseElement(e){const t=e.getAttribute("pp-original-state");if(e.hasAttribute("pp-suspense")&&t){const n=(e,t)=>{for(const n in t)t.hasOwnProperty(n)&&("textContent"===n?e.textContent=t[n]:"innerHTML"===n?e.innerHTML=t[n]:"disabled"===n?!0===t[n]?e.setAttribute("disabled","true"):e.removeAttribute("disabled"):e.setAttribute(n,t[n]));for(const n of Array.from(e.attributes))t.hasOwnProperty(n.name)||e.removeAttribute(n.name)},s=(e,t)=>{for(const s in t)if(t.hasOwnProperty(s))for(const t of Array.from(e.elements))if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-original-state")||"";if(e){if(this.isJsonLike(e)){const s=this.parseJson(e);n(t,s)}else r(t,e);t.removeAttribute("pp-original-state")}}},r=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},i=(e,t)=>{e instanceof HTMLFormElement?s(e,t):n(e,t)};try{const r=this.parseJson(t);if(r)if(e instanceof HTMLFormElement){const t=e.id;if(t){const e=document.querySelector(`[form="${t}"]`);if(e){const t=e.getAttribute("pp-original-state");if(t&&this.isJsonLike(t)){const s=this.parseJson(t);n(e,s)}}}const r=new FormData(e),i={};if(r.forEach(((e,t)=>{i[t]=e})),s(e,i),e.hasAttribute("pp-suspense")){const t=e.getAttribute("pp-suspense")||"";if(this.parseJson(t).disabled)for(const t of Array.from(e.elements))(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&t.removeAttribute("disabled")}}else if(r.targets){r.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&i(s,n)}));const{targets:t,...s}=r;n(e,s)}else{const{empty:t,...s}=r;n(e,s)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}e.querySelectorAll("[pp-suspense]").forEach((e=>this.restoreSuspenseElement(e))),e.removeAttribute("pp-original-state")}extractJson(e){const t=e?.match(/\{[\s\S]*\}/);return t?t[0]:null}getRedirectUrl(e){const t=e.match(this._redirectRegex);return t?t[1]:null}async fetchFileWithData(e,t,n,s={}){const r=new FormData,i=n.files;if(i)for(let e=0;e<i.length;e++)r.append("file[]",i[e]);r.append("callback",t);for(const e in s)s.hasOwnProperty(e)&&r.append(e,s[e]);const o=await this.fetch(e,{method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:r});return await o.text()}async handleSuspenseElement(e){let t=e.getAttribute("pp-suspense")||"";const n=(e,t)=>{for(const n in t)if(t.hasOwnProperty(n))for(const t of e.elements)if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-suspense")||"";if(e)if(this.isJsonLike(e)){const n=this.parseJson(e);"disabled"!==n.onsubmit&&this.updateElementAttributes(t,n),n.targets&&n.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&r(s,n)}))}else s(t,e)}},s=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},r=(e,t)=>{e instanceof HTMLFormElement?n(e,t):this.updateElementAttributes(e,t)};try{if(t&&this.isJsonLike(t)){const s=this.parseJson(t);if(s)if(e instanceof HTMLFormElement){const t=new FormData(e),r={};t.forEach(((e,t)=>{r[t]=e})),s.disabled&&this.toggleFormElements(e,!0);const{disabled:i,...o}=s;this.updateElementAttributes(e,o),n(e,r)}else if(s.targets){s.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&r(s,n)}));const{targets:t,...n}=s;this.updateElementAttributes(e,n)}else{if("disabled"===s.empty&&""===e.value)return;const{empty:t,...n}=s;this.updateElementAttributes(e,n)}}else if(t)s(e,t);else if(e instanceof HTMLFormElement){const t=new FormData(e),s={};t.forEach(((e,t)=>{s[t]=e})),n(e,s)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}toggleFormElements(e,t){Array.from(e.elements).forEach((e=>{(e instanceof HTMLInputElement||e instanceof HTMLButtonElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(e.disabled=t)}))}saveElementOriginalState(e){if(e.hasAttribute("pp-suspense")&&!e.hasAttribute("pp-original-state")){const t={};e.textContent&&(t.textContent=e.textContent.trim()),e.innerHTML&&(t.innerHTML=e.innerHTML.trim()),(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(t.value=e.value);for(let n=0;n<e.attributes.length;n++){const s=e.attributes[n];t[s.name]=s.value}e.setAttribute("pp-original-state",JSON.stringify(t))}if(e instanceof HTMLFormElement){let t=null;const n=e.id;n&&(t=document.querySelector(`[form="${n}"]`)),n&&t||(t=Array.from(e.elements).find((e=>e instanceof HTMLButtonElement||e instanceof HTMLInputElement))),t?t.hasAttribute("pp-original-state")||this.saveElementOriginalState(t):console.warn("Warning: No invoker detected for the form. Ensure the form has an associated invoker or an ID for proper handling.")}e.querySelectorAll("[pp-suspense]").forEach((e=>this.saveElementOriginalState(e)))}getUrlParams(){const e={};return new URLSearchParams(window.location.search).forEach(((t,n)=>{e[n]=t})),e}createFetchOptions(e){return{method:"POST",headers:{"Content-Type":"application/json",HTTP_PPHP_WIRE_REQUEST:"true"},body:JSON.stringify(e)}}parseCallback(e,t){let n={};const s=e.closest("form");if(s){new FormData(s).forEach(((e,t)=>{n[t]?Array.isArray(n[t])?n[t].push(e):n[t]=[n[t],e]:n[t]=e}))}else e instanceof HTMLInputElement?n=this.handleInputElement(e):(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(n[e.name]=e.value);const r=t.match(/(\w+)\((.*)\)/);if(r){const e=r[1];let t=r[2].trim();if(t.startsWith("{")&&t.endsWith("}"))try{const e=this.parseJson(t);"object"==typeof e&&null!==e&&(n={...n,...e})}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}else{const e=t.split(/,(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/).map((e=>e.trim().replace(/^['"]|['"]$/g,"")));n.args=e}return{funcName:e,data:n}}return{funcName:t,data:n}}handleInputElement(e){let t={};if(e.name)if("checkbox"===e.type)t[e.name]={value:e.value,checked:e.checked};else if("radio"===e.type){const n=document.querySelector(`input[name="${e.name}"]:checked`);t[e.name]=n?n.value:null}else t[e.name]=e.value;else"checkbox"===e.type||"radio"===e.type?t.value=e.checked:t.value=e.value;return t}resolveContext(e){let t=window;for(let n=0;n<e.length-1;n++)if(t=t[e[n]],!t)throw new Error(`Cannot find object ${e[n]} in the context.`);return{context:t,methodName:e[e.length-1]}}setCursorPosition(e,t){if(t.start)e.setSelectionRange(0,0);else if(t.end){const t=e.value.length||0;e.setSelectionRange(t,t)}else if(t.length){const n=parseInt(t.length,10)||0;e.setSelectionRange(n,n)}}handleInputAppendParams(e,t){const n=e.getAttribute("pp-append-params"),s=e.getAttribute("pp-append-params-sync");if("true"===n){if("true"===s){const t=e.name||e.id;if(t){const n=new URL(window.location.href),s=new URLSearchParams(n.search);s.has(t)&&(e.value=s.get(t)||"")}}e.addEventListener(t,(e=>{const t=e.currentTarget,n=t.value,s=new URL(window.location.href),r=new URLSearchParams(s.search),i=t.name||t.id;if(i){n?r.set(i,n):r.delete(i);const e=r.toString()?`${s.pathname}?${r.toString()}`:s.pathname;history.replaceState(null,"",e)}}))}}handleHiddenAttribute(){const e=document.querySelectorAll("[pp-visibility]"),t=document.querySelectorAll("[pp-display]"),n=this.handleElementVisibility.bind(this),s=this.handleElementDisplay.bind(this);e.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-visibility",n))),t.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-display",s)))}handleVisibilityElementAttribute(e,t,n){const s=e.getAttribute(t);if(s)if(this.isJsonLike(s)){n(e,this.parseJson(s))}else{const n=this.parseTime(s);if(n>0){const s="pp-visibility"===t?"visibility":"display",r="visibility"===s?"hidden":"none";this.scheduleChange(e,n,s,r)}}}handleElementVisibility(e,t){this.handleElementChange(e,t,"visibility","hidden","visible")}handleElementDisplay(e,t){this.handleElementChange(e,t,"display","none","block")}handleElementChange(e,t,n,s,r){const i=t.start?this.parseTime(t.start):0,o=t.end?this.parseTime(t.end):0;i>0?(e.style[n]=s,this.scheduleChange(e,i,n,r),o>0&&this.scheduleChange(e,i+o,n,s)):o>0&&this.scheduleChange(e,o,n,s)}handleAnchorTag(){document.querySelectorAll("a").forEach((e=>{e.addEventListener("click",(async e=>{const t=e.currentTarget,n=t.getAttribute("href"),s=t.getAttribute("target");if(n&&"_blank"!==s&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),!this._isNavigating)){this._isNavigating=!0;try{if(/^(https?:)?\/\//i.test(n)&&!n.startsWith(window.location.origin))window.location.href=n;else{const e=t.getAttribute("pp-append-params");if(n.startsWith("?")&&"true"===e){const e=new URL(window.location.href),t=new URLSearchParams(e.search);let s="";const[r,i]=n.split("#");i&&(s=`#${i}`);new URLSearchParams(r.split("?")[1]).forEach(((e,n)=>{t.set(n,e)}));const o=`${e.pathname}?${t.toString()}${s}`;history.pushState(null,"",o)}else{const[e,t]=n.split("#"),s=`${e}${t?`#${t}`:""}`;history.pushState(null,"",s)}const s=n.indexOf("#");if(-1!==s){const e=n.slice(s+1),t=document.getElementById(e);if(t)t.scrollIntoView({behavior:"smooth"});else{await this.handleNavigation();const t=document.getElementById(e);t&&t.scrollIntoView({behavior:"smooth"})}}else await this.handleNavigation()}}catch(e){console.error("Anchor click error:",e)}finally{this._isNavigating=!1}}}))}))}async handleNavigation(){try{const e=document.getElementById("loading-file-1B87E");if(e){const t=this.findLoadingElement(e,window.location.pathname);t&&await this.updateContentWithTransition(t)}const t=await this.fetch(window.location.href);if(!t.ok){console.error(`Navigation error: ${t.status} ${t.statusText}`);const e=await t.text();return void await this.updateDocumentContent(e)}const n=await t.text(),s=n.match(this._redirectRegex);if(s&&s[1])return void await this.redirect(s[1]);await this.updateDocumentContent(n)}catch(e){console.error("Navigation error:",e)}}findLoadingElement(e,t){let n=t;for(;;){const t=e.querySelector(`div[pp-loading-url='${n}']`);if(t)return t;if("/"===n)break;const s=n.lastIndexOf("/");n=s<=0?"/":n.substring(0,s)}return e.querySelector("div[pp-loading-url='/' ]")}async updateContentWithTransition(e){const t=document.querySelector("[pp-loading-content='true']")||document.body;if(!t)return;const{fadeIn:n,fadeOut:s}=this.parseTransition(e);await this.fadeOut(t,s),t.innerHTML=e.innerHTML,this.fadeIn(t,n)}parseTransition(e){let t=250,n=250;const s=e.querySelector("[pp-loading-transition]"),r=s?.getAttribute("pp-loading-transition");if(r){const e=this.parseJson(r);e&&"object"==typeof e?(t=this.parseTime(e.fadeIn??t),n=this.parseTime(e.fadeOut??n)):console.warn("pp-loading-transition is not valid JSON β†’ default values (250β€―ms) will be used. String:",r)}return{fadeIn:t,fadeOut:n}}fadeOut(e,t){return new Promise((n=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout((()=>{e.style.transition="",n()}),t)}))}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,e.style.opacity="1",setTimeout((()=>{e.style.transition=""}),t)}async updateDocumentContent(e){const t=this.saveScrollPositions(),n=(new DOMParser).parseFromString(e,"text/html"),s="pp-dynamic-script",r="pp-dynamic-link";document.head.querySelectorAll("[pp-dynamic-meta]").forEach((e=>e.remove()));document.head.querySelectorAll(`[${r}]`).forEach((e=>e.remove()));document.head.querySelectorAll(`[${s}]`).forEach((e=>e.remove()));await(async e=>{Array.from(e.head.children).forEach((e=>{const t=e.tagName;if("SCRIPT"===t&&e.hasAttribute(s)){const t=document.createElement("script");Array.from(e.attributes).forEach((e=>t.setAttribute(e.name,e.value))),e.textContent&&(t.textContent=e.textContent),document.head.appendChild(t)}else if("META"===t){if(e.getAttribute("charset")||"viewport"===e.getAttribute("name"))return;const t=e.name,n=e.getAttribute("property"),s=document.head.querySelector(t?`meta[name="${t}"]`:`meta[property="${n}"]`),r=document.head.querySelector("title");s?document.head.replaceChild(e.cloneNode(!0),s):r?.nextSibling?document.head.insertBefore(e.cloneNode(!0),r.nextSibling):document.head.appendChild(e.cloneNode(!0))}else if("TITLE"===t){const t=document.head.querySelector("title");t?document.head.replaceChild(e.cloneNode(!0),t):document.head.appendChild(e.cloneNode(!0))}else if("LINK"===t){const t=t=>{const n=document.head.querySelector('link[rel="icon"]');if(n)document.head.replaceChild(e.cloneNode(!0),n);else{const e=document.createElement("link");e.rel="icon",e.href=t,document.head.appendChild(e)}};if("icon"===e.getAttribute("rel")){t(e.href)}else if(e.hasAttribute(r)){const t=e.cloneNode(!0);document.head.appendChild(t)}}})),await this.populateDocumentBody(e)})(n),this.restoreScrollPositions(t),this.resetProps(),await this.processInlineModuleScripts(),this.initMakeReactive(),this.handlerAutofocusAttribute()}restoreScrollPositions(e){requestAnimationFrame((()=>{const t=e.window;t&&window.scrollTo(t.scrollLeft,t.scrollTop),document.querySelectorAll("*").forEach((t=>{const n=this.getElementKey(t);e[n]&&(t.scrollTop=e[n].scrollTop,t.scrollLeft=e[n].scrollLeft)}))}))}async populateDocumentBody(e){try{const t={DETAILS:(e,t)=>(t.open=e.open,!0),INPUT:(e,t)=>document.activeElement!==e||(t.value=e.value,"checked"in e&&(t.checked=e.checked),e.type.match(/^(text|search|url|email)$/)&&(t.selectionStart=e.selectionStart,t.selectionEnd=e.selectionEnd),!1),TEXTAREA:(e,n)=>t.INPUT(e,n),SELECT:(e,t)=>document.activeElement!==e||(t.selectedIndex=e.selectedIndex,!1),VIDEO:(e,t)=>(t.currentTime=e.currentTime,e.paused?t.pause():t.play(),!0),AUDIO:(e,n)=>t.VIDEO(e,n),CANVAS:()=>!1};morphdom(document.body,e.body,{getNodeKey(e){if(1===e.nodeType){const t=e;if(t.hasAttribute("pp-sync-script"))return`pp-sync-script:${t.getAttribute("pp-sync-script")}`;if(t.hasAttribute("key"))return t.getAttribute("key")}},onBeforeElUpdated(e,n){if("SCRIPT"===e.tagName)return!1;if(e.hasAttribute("data-nomorph"))return!1;const s=t[e.tagName];return!s||s(e,n)},onBeforeNodeDiscarded(e){if(e instanceof HTMLElement){const{timerId:t}=e.dataset;t&&clearTimeout(Number(t))}return!0}})}catch(e){console.error("Error populating document body:",e)}}saveScrollPositions(){const e={window:{scrollTop:window.scrollY||document.documentElement.scrollTop,scrollLeft:window.scrollX||document.documentElement.scrollLeft}};return document.querySelectorAll("*").forEach((t=>{(t.scrollTop||t.scrollLeft)&&(e[this.getElementKey(t)]={scrollTop:t.scrollTop,scrollLeft:t.scrollLeft})})),e}getElementKey(e){return e.id||e.className||e.tagName}async redirect(e){if(e)try{const t=new URL(e,window.location.origin);t.origin!==window.location.origin?window.location.href=e:(history.pushState(null,"",e),await this.handleNavigation())}catch(e){console.error("Redirect error:",e)}}abortActiveRequest(){this._activeAbortController&&this._activeAbortController.abort()}async fetch(e,t,n=!1){let s;return n?(this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=new AbortController,s=this._activeAbortController):s=new AbortController,fetch(e,{...t,signal:s.signal,headers:{...t?.headers,"X-Requested-With":"XMLHttpRequest"}})}isJsonLike(e){return"string"==typeof e&&((e=e.trim()).startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]"))}parseJson(e){try{return JSON5.parse(e)}catch(e){return console.error(`Error parsing JSON: ${e.message}. Please ensure the JSON string is valid.`,e),{}}}parseTime(e){if("number"==typeof e)return e;const t=e.match(/^(\d+)(ms|s|m)?$/);if(t){const e=parseInt(t[1],10);switch(t[2]||"ms"){case"ms":default:return e;case"s":return 1e3*e;case"m":return 60*e*1e3}}return 0}scheduleChange(e,t,n,s){setTimeout((()=>{requestAnimationFrame((()=>{e.style[n]=s}))}),t)}async processInlineModuleScripts(){const e=window;e.__PPHP_INLINE_DEPTH__=(e.__PPHP_INLINE_DEPTH__??0)+1;try{const e=Array.from(document.body.querySelectorAll('script[type="text/php"]:not([src])')).filter((e=>{const t=e.getAttribute("pp-section-id")??e.closest("[pp-section-id]")?.getAttribute("pp-section-id")??null;return t?!this._processedPhpSections.has(t):!this._processedPhpScripts.has(e)}));if(0===e.length)return;const t={};for(const n of e){const e=n.getAttribute("pp-section-id")??n.closest("[pp-section-id]")?.getAttribute("pp-section-id")??null;if(!e)continue;const s=n.textContent||"";for(const[,n]of s.matchAll(/export\s+const\s+([A-Za-z_$]\w*)/g))t[n]=e}for(const n of e){const e=n.getAttribute("pp-section-id")??n.closest("[pp-section-id]")?.getAttribute("pp-section-id")??null;let s=(n.textContent||"").trim();e&&(s=s.replace(/(\bpphp\.state\(\s*['"])([^'"]+)(['"])/g,((t,n,s,r)=>n+(s.startsWith(`${e}_`)?s:`${e}_${s}`)+r))),s=s.replace(/\b([A-Za-z_$]\w*)\s*\(/g,((e,n)=>{const s=t[n];return s?`${s}_${n}(`:e}));const r=new Blob([s],{type:"application/javascript"}),i=URL.createObjectURL(r),o=PPHP.prototype._currentSectionId;e&&(PPHP.prototype._currentSectionId=()=>e);try{const t=await import(i);for(const[n,s]of Object.entries(t))if("function"==typeof s){const t=e?`${e}_${n}`:n;window[t]=s}}catch(e){console.error("Inline module import failed:",e)}finally{PPHP.prototype._currentSectionId=o,URL.revokeObjectURL(i),e?this._processedPhpSections.add(e):this._processedPhpScripts.add(n)}}}finally{e.__PPHP_INLINE_DEPTH__--,0===e.__PPHP_INLINE_DEPTH__&&requestAnimationFrame((()=>{this._pendingEffects.forEach((e=>{try{e()}catch(e){console.error("effect error:",e)}this._effects.add(e)})),this._pendingEffects.clear()}))}}async fetchFunction(e,t={},n=!1){try{const s={callback:e,...t},r=window.location.href;let i;if(Object.keys(s).some((e=>{const t=s[e];return t instanceof File||t instanceof FileList&&t.length>0}))){const e=new FormData;Object.keys(s).forEach((t=>{const n=s[t];n instanceof File?e.append(t,n):n instanceof FileList?Array.from(n).forEach((n=>e.append(t,n))):e.append(t,n)})),i={method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:e}}else i=this.createFetchOptions(s);const o=await this.fetch(r,i,n);if(!o.ok)throw new Error(`Fetch failed with status: ${o.status} ${o.statusText}`);const a=await o.text();try{return JSON.parse(a)}catch{return a}}catch(e){throw console.error("Error in fetchFunction:",e),new Error("Failed to fetch data.")}}processSyncScripts(e){e.forEach((e=>{const t=`script[pp-sync-script="${CSS.escape(e)}"]`,n=document.querySelector(t);if(n){n.remove();const e=document.createElement("script");Array.from(n.attributes).forEach((t=>{e.setAttribute(t.name,t.value)})),n.src?e.src=n.src:e.textContent=n.textContent,e.type=n.type||"module",document.body.appendChild(e)}}))}async sync(...e){try{const t=this.saveScrollPositions();this.saveElementState();const n=e.length>0?e.map((e=>`pp-sync="${e}"`)):['pp-sync="true"'],s=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()}),r=await this.fetch(window.location.href,s),i=await r.text(),o=(new DOMParser).parseFromString(i,"text/html"),a=new Set;n.forEach((e=>{const t=document.querySelectorAll(`[${e}]`),n=o.body.querySelectorAll(`[${e}]`);t.forEach(((e,t)=>{const s=n[t];if(s){if(s.hasAttribute("pp-sync-script")){const e=s.getAttribute("pp-sync-script")||"";e&&a.add(e)}s.querySelectorAll("[pp-sync-script]").forEach((e=>{const t=e.getAttribute("pp-sync-script")||"";t&&a.add(t)})),e.innerHTML=s.innerHTML,this.reRunScripts(e)}}))})),this.processSyncScripts(a),this.restoreElementState(),this.restoreScrollPositions(t),this.attachWireFunctionEvents()}catch(e){console.error("Error in pphpSync:",e)}}async fetchAndUpdateBodyContent(){const e=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});this.abortActiveRequest();const t=await this.fetch(window.location.href,e,!0),n=await t.text();await this.updateBodyContent(n)}reRunScripts(e){e.querySelectorAll("script").forEach((e=>{const t=document.createElement("script");Array.from(e.attributes).forEach((e=>{t.setAttribute(e.name,e.value)})),e.hasAttribute("src")||(t.textContent=e.textContent),e.parentNode?.replaceChild(t,e)}))}copyCode(e,t,n,s,r="img",i=2e3){if(!(e instanceof HTMLElement))return;const o=e.closest(`.${t}`)?.querySelector("pre code"),a=o?.textContent?.trim()||"";a?navigator.clipboard.writeText(a).then((()=>{const t=e.querySelector(r);if(t)for(const[e,n]of Object.entries(s))e in t?t[e]=n:t.setAttribute(e,n);setTimeout((()=>{if(t)for(const[e,s]of Object.entries(n))e in t?t[e]=s:t.setAttribute(e,s)}),i)}),(()=>{alert("Failed to copy command to clipboard")})):alert("Failed to find the code block to copy")}getCookie(e){return document.cookie.split("; ").find((t=>t.startsWith(e+"=")))?.split("=")[1]||null}}class PPHPLocalStore{state;static instance=null;listeners;pphp;STORAGE_KEY;constructor(e={}){this.state=e,this.listeners=[],this.pphp=PPHP.instance,this.STORAGE_KEY=this.pphp.getCookie("pphp_local_store_key")||"pphp_local_store_59e13",this.loadState()}static getInstance(e={}){return PPHPLocalStore.instance||(PPHPLocalStore.instance=new PPHPLocalStore(e)),PPHPLocalStore.instance}setState(e,t=!1){if(this.state={...this.state,...e},this.listeners.forEach((e=>e(this.state))),this.saveState(),t){const e=localStorage.getItem(this.STORAGE_KEY);e&&this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:e})}}saveState(){localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.state))}loadState(){const e=localStorage.getItem(this.STORAGE_KEY);e&&(this.state=this.pphp.parseJson(e),this.listeners.forEach((e=>e(this.state))))}resetState(e,t=!1){if(e?(delete this.state[e],this.saveState()):(this.state={},localStorage.removeItem(this.STORAGE_KEY)),this.listeners.forEach((e=>e(this.state))),t){const t=e?localStorage.getItem(this.STORAGE_KEY):null;this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:t})}}}class SearchParamsManager{static instance=null;listeners=[];constructor(){}static getInstance(){return SearchParamsManager.instance||(SearchParamsManager.instance=new SearchParamsManager),SearchParamsManager.instance}get params(){return new URLSearchParams(window.location.search)}get(e){return this.params.get(e)}set(e,t){const n=this.params;n.set(e,t),this.updateURL(n)}delete(e){const t=this.params;t.delete(e),this.updateURL(t)}replace(e){const t=new URLSearchParams;for(const n in e){const s=e[n];null!==s&&t.set(n,s)}this.updateURL(t,!0)}updateURL(e,t=!1){const n=`${window.location.pathname}?${e.toString()}`;t?history.replaceState(null,"",n):history.pushState(null,"",n),this.notifyListeners(e)}listen(e){this.listeners.push(e)}notifyListeners(e){for(const t of this.listeners)t(e)}enablePopStateListener(){window.addEventListener("popstate",(()=>{this.notifyListeners(this.params)}))}}var pphp=PPHP.instance,store=PPHPLocalStore.getInstance(),searchParams=SearchParamsManager.getInstance();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-prisma-php-app",
3
- "version": "2.3.31",
3
+ "version": "2.3.33",
4
4
  "description": "Prisma-PHP: A Revolutionary Library Bridging PHP with Prisma ORM",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",