@wp-playground/blueprints 0.1.42 → 0.1.45

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.
package/index.cjs CHANGED
@@ -1,16 +1,16 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function _(r){return new DOMParser().parseFromString(r.text,"text/html")}function E(r){const e=r.split(".").shift().replace("-"," ");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}async function P(r,e,t){let s="";await r.fileExists(e)&&(s=await r.readFileAsText(e)),await r.writeFile(e,t(s))}async function Re(r){return new Uint8Array(await r.arrayBuffer())}const K=async(r,{plugin:e},t)=>{t?.tracker.setCaption(`Activating ${e}`);const i=_(await r.request({url:"/wp-admin/plugins.php"})).querySelector(`tr[data-slug="${e}"] a`).attributes.getNamedItem("href").value;await r.request({url:"/wp-admin/"+i})},Y=async(r,e)=>{const t=new Te(r,e.siteUrl,e.wordpressPath||"/wordpress");e.patchSqlitePlugin!==!1&&await t.patchSqlitePlugin(),e.addPhpInfo!==!1&&await t.addPhpInfo(),e.patchSiteUrl!==!1&&await t.patchSiteUrl(),e.disableSiteHealth!==!1&&await t.disableSiteHealth(),e.disableWpNewBlogNotification!==!1&&await t.disableWpNewBlogNotification()};class Te{constructor(e,t,s){this.php=e,this.scopedSiteUrl=t,this.wordpressPath=s}async patchSqlitePlugin(){await P(this.php,`${this.wordpressPath}/wp-content/plugins/sqlite-database-integration/wp-includes/sqlite/class-wp-sqlite-translator.php`,e=>e.replace("if ( false === strtotime( $value ) )",'if ( $value === "0000-00-00 00:00:00" || false === strtotime( $value ) )'))}async addPhpInfo(){await this.php.writeFile(`${this.wordpressPath}/phpinfo.php`,"<?php phpinfo(); ")}async patchSiteUrl(){await P(this.php,`${this.wordpressPath}/wp-config.php`,e=>`<?php
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function b(r){return new DOMParser().parseFromString(r.text,"text/html")}function E(r){const e=r.split(".").shift().replace("-"," ");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}async function g(r,e,t){let s="";await r.fileExists(e)&&(s=await r.readFileAsText(e)),await r.writeFile(e,t(s))}async function Fe(r){return new Uint8Array(await r.arrayBuffer())}const I="/vfs-blueprints",L="/vfs-blueprints/wp-config-consts.php",Z=async(r,{plugin:e},t)=>{t?.tracker.setCaption(`Activating ${e}`);const i=b(await r.request({url:"/wp-admin/plugins.php"})).querySelector(`tr[data-slug="${e}"] a`).attributes.getNamedItem("href").value;await r.request({url:"/wp-admin/"+i})},Q=async(r,e)=>{const t=new Ce(r,e.siteUrl,e.wordpressPath||"/wordpress");e.patchSqlitePlugin!==!1&&await t.patchSqlitePlugin(),e.addPhpInfo!==!1&&await t.addPhpInfo(),e.patchSiteUrl!==!1&&await t.patchSiteUrl(),e.disableSiteHealth!==!1&&await t.disableSiteHealth(),e.disableWpNewBlogNotification!==!1&&await t.disableWpNewBlogNotification()};class Ce{constructor(e,t,s){this.php=e,this.scopedSiteUrl=t,this.wordpressPath=s}async patchSqlitePlugin(){await g(this.php,`${this.wordpressPath}/wp-content/plugins/sqlite-database-integration/wp-includes/sqlite/class-wp-sqlite-translator.php`,e=>e.replace("if ( false === strtotime( $value ) )",'if ( $value === "0000-00-00 00:00:00" || false === strtotime( $value ) )'))}async addPhpInfo(){await this.php.writeFile(`${this.wordpressPath}/phpinfo.php`,"<?php phpinfo(); ")}async patchSiteUrl(){await g(this.php,`${this.wordpressPath}/wp-config.php`,e=>`<?php
2
2
  if(!defined('WP_HOME')) {
3
3
  define('WP_HOME', "${this.scopedSiteUrl}");
4
4
  define('WP_SITEURL', "${this.scopedSiteUrl}");
5
5
  }
6
- ?>${e}`)}async disableSiteHealth(){await P(this.php,`${this.wordpressPath}/wp-includes/default-filters.php`,e=>e.replace(/add_filter[^;]+wp_maybe_grant_site_health_caps[^;]+;/i,""))}async disableWpNewBlogNotification(){await P(this.php,`${this.wordpressPath}/wp-config.php`,e=>`${e} function wp_new_blog_notification(...$args){} `)}}const Z=async(r,{code:e})=>await r.run({code:e}),Q=async(r,{options:e})=>await r.run(e),X=async(r,{key:e,value:t})=>{await r.setPhpIniEntry(e,t)},ee=async(r,{request:e})=>await r.request(e),te=async(r,{fromPath:e,toPath:t})=>{await r.writeFile(t,await r.readFileAsBuffer(e))},re=async(r,{fromPath:e,toPath:t})=>{await r.mv(e,t)},se=async(r,{path:e})=>{await r.mkdir(e)},ne=async(r,{path:e})=>{await r.unlink(e)},ie=async(r,{path:e})=>{await r.rmdir(e)},oe=async(r,{path:e,data:t})=>{t instanceof File&&(t=await Re(t)),await r.writeFile(e,t)},x=async(r,{consts:e})=>{const t=await r.documentRoot;await P(r,`${t}/playground-consts.json`,s=>JSON.stringify({...JSON.parse(s||"{}"),...e})),await P(r,`${t}/wp-config.php`,s=>s.includes("playground-consts.json")?s:`<?php
6
+ ?>${e}`)}async disableSiteHealth(){await g(this.php,`${this.wordpressPath}/wp-includes/default-filters.php`,e=>e.replace(/add_filter[^;]+wp_maybe_grant_site_health_caps[^;]+;/i,""))}async disableWpNewBlogNotification(){await g(this.php,`${this.wordpressPath}/wp-config.php`,e=>`${e} function wp_new_blog_notification(...$args){} `)}}const X=async(r,{code:e})=>await r.run({code:e}),ee=async(r,{options:e})=>await r.run(e),te=async(r,{key:e,value:t})=>{await r.setPhpIniEntry(e,t)},re=async(r,{request:e})=>await r.request(e),se=async(r,{fromPath:e,toPath:t})=>{await r.writeFile(t,await r.readFileAsBuffer(e))},ne=async(r,{fromPath:e,toPath:t})=>{await r.mv(e,t)},ie=async(r,{path:e})=>{await r.mkdir(e)},oe=async(r,{path:e})=>{await r.unlink(e)},ae=async(r,{path:e})=>{await r.rmdir(e)},ce=async(r,{path:e,data:t})=>{t instanceof File&&(t=await Fe(t)),await r.writeFile(e,t)},x=async(r,{consts:e})=>{const t=await r.documentRoot;await g(r,`${t}/playground-consts.json`,s=>JSON.stringify({...JSON.parse(s||"{}"),...e})),await g(r,`${t}/wp-config.php`,s=>s.includes("playground-consts.json")?s:`<?php
7
7
  $consts = json_decode(file_get_contents('./playground-consts.json'), true);
8
8
  foreach ($consts as $const => $value) {
9
9
  if (!defined($const)) {
10
10
  define($const, $value);
11
11
  }
12
12
  }
13
- ?>${s}`)},ae=async(r,{siteUrl:e})=>await x(r,{consts:{WP_HOME:e,WP_SITEURL:e}});class ce{constructor({concurrency:e}){this._running=0,this.concurrency=e,this.queue=[]}get running(){return this._running}async acquire(){for(;;)if(this._running>=this.concurrency)await new Promise(e=>this.queue.push(e));else return this._running++,()=>{this._running--,this.queue.length>0&&this.queue.shift()()}}async run(e){const t=await this.acquire();try{return await e()}finally{t()}}}const xe=Symbol("literal");function b(r){if(typeof r=="string")return r.startsWith("$")?r:JSON.stringify(r);if(typeof r=="number")return r.toString();if(Array.isArray(r))return`array(${r.map(b).join(", ")})`;if(r===null)return"null";if(typeof r=="object")return xe in r?r.toString():`array(${Object.entries(r).map(([t,s])=>`${JSON.stringify(t)} => ${b(s)}`).join(", ")})`;if(typeof r=="function")return r();throw new Error(`Unsupported value: ${r}`)}function F(r){const e={};for(const t in r)e[t]=b(r[t]);return e}const I=`<?php
13
+ ?>${s}`)},le=async(r,{siteUrl:e})=>await x(r,{consts:{WP_HOME:e,WP_SITEURL:e}});class ue{constructor({concurrency:e}){this._running=0,this.concurrency=e,this.queue=[]}get running(){return this._running}async acquire(){for(;;)if(this._running>=this.concurrency)await new Promise(e=>this.queue.push(e));else return this._running++,()=>{this._running--,this.queue.length>0&&this.queue.shift()()}}async run(e){const t=await this.acquire();try{return await e()}finally{t()}}}const ke=Symbol("literal");function _(r){if(typeof r=="string")return r.startsWith("$")?r:JSON.stringify(r);if(typeof r=="number")return r.toString();if(Array.isArray(r))return`array(${r.map(_).join(", ")})`;if(r===null)return"null";if(typeof r=="object")return ke in r?r.toString():`array(${Object.entries(r).map(([t,s])=>`${JSON.stringify(t)} => ${_(s)}`).join(", ")})`;if(typeof r=="function")return r();throw new Error(`Unsupported value: ${r}`)}function F(r){const e={};for(const t in r)e[t]=_(r[t]);return e}const H=`<?php
14
14
 
15
15
  function zipDir($dir, $output, $additionalFiles = array())
16
16
  {
@@ -72,34 +72,39 @@ function delTree($dir)
72
72
  }
73
73
  return rmdir($dir);
74
74
  }
75
- `;async function le(r){const e="wordpress-playground.zip",t=`/${e}`,s=F({zipPath:t,documentRoot:await r.documentRoot});await pe(r,`zipDir(${s.documentRoot}, ${s.zipPath});`);const n=await r.readFileAsBuffer(t);return r.unlink(t),new File([n],e)}const ue=async(r,{fullSiteZip:e})=>{const t="/import.zip";await r.writeFile(t,new Uint8Array(await e.arrayBuffer()));const s=await r.absoluteUrl,n=await r.documentRoot;await r.rmdir(n),await k(r,{zipPath:t,extractToPath:"/"});const i=F({absoluteUrl:s});await ke(r,`${n}/wp-config.php`,o=>`<?php
75
+ `;async function he(r){const e="wordpress-playground.zip",t=`/${e}`,s=F({zipPath:t,documentRoot:await r.documentRoot});await fe(r,`zipDir(${s.documentRoot}, ${s.zipPath});`);const n=await r.readFileAsBuffer(t);return r.unlink(t),new File([n],e)}const pe=async(r,{fullSiteZip:e})=>{const t="/import.zip";await r.writeFile(t,new Uint8Array(await e.arrayBuffer()));const s=await r.absoluteUrl,n=await r.documentRoot;await r.rmdir(n),await C(r,{zipPath:t,extractToPath:"/"});const i=F({absoluteUrl:s});await Oe(r,`${n}/wp-config.php`,o=>`<?php
76
76
  if(!defined('WP_HOME')) {
77
77
  define('WP_HOME', ${i.absoluteUrl});
78
78
  define('WP_SITEURL', ${i.absoluteUrl});
79
79
  }
80
- ?>${o}`)},k=async(r,{zipPath:e,extractToPath:t})=>{const s=F({zipPath:e,extractToPath:t});await pe(r,`unzip(${s.zipPath}, ${s.extractToPath});`)},he=async(r,{file:e})=>{const t=await r.request({url:"/wp-admin/admin.php?import=wordpress"}),s=L(t).getElementById("import-upload-form")?.getAttribute("action"),n=await r.request({url:`/wp-admin/${s}`,method:"POST",files:{import:e}}),i=L(n).querySelector("#wpbody-content form");if(!i)throw console.log(n.text),new Error("Could not find an importer form in response. See the response text above for details.");const o=Fe(i);o.fetch_attachments="1";for(const a in o)if(a.startsWith("user_map[")){const c="user_new["+a.slice(9,-1)+"]";o[c]="1"}await r.request({url:i.action,method:"POST",formData:o})};function L(r){return new DOMParser().parseFromString(r.text,"text/html")}function Fe(r){return Object.fromEntries(new FormData(r).entries())}async function ke(r,e,t){await r.writeFile(e,t(await r.readFileAsText(e)))}async function pe(r,e){const t=await r.run({code:I+e});if(t.exitCode!==0)throw console.log(I+e),console.log(e+""),console.log(t.errors),t.errors;return t}const de=async(r,{pluginZipFile:e,options:t={}},s)=>{s?.tracker.setCaption(`Installing the ${E(e?.name)} plugin`);try{const n="activate"in t?t.activate:!0,i=await r.request({url:"/wp-admin/plugin-install.php?tab=upload"}),o=_(i),a=new FormData(o.querySelector(".wp-upload-form")),{pluginzip:c,...u}=Object.fromEntries(a.entries()),h=await r.request({url:"/wp-admin/update.php?action=upload-plugin",method:"POST",formData:u,files:{pluginzip:e}});if(n){const v=_(h).querySelector("#wpbody-content .button.button-primary").attributes.getNamedItem("href").value,S=new URL(v,await r.pathToInternalUrl("/wp-admin/")).toString();await r.request({url:S})}await r.isDir("/wordpress/wp-content/plugins/gutenberg")&&!await r.fileExists("/wordpress/.gutenberg-patched")&&(await r.writeFile("/wordpress/.gutenberg-patched","1"),await H(r,"/wordpress/wp-content/plugins/gutenberg/build/block-editor/index.js",d=>d.replace(/srcDoc:("[^"]+"|[^,]+)/g,'src:"/wp-includes/empty.html"')),await H(r,"/wordpress/wp-content/plugins/gutenberg/build/block-editor/index.min.js",d=>d.replace(/srcDoc:("[^"]+"|[^,]+)/g,'src:"/wp-includes/empty.html"')))}catch(n){console.error(`Proceeding without the ${e.name} theme. Could not install it in wp-admin. The original error was: ${n}`),console.error(n)}};async function H(r,e,t){return await r.writeFile(e,t(await r.readFileAsText(e)))}const fe=async(r,{themeZipFile:e,options:t={}},s)=>{s?.tracker.setCaption(`Installing the ${E(e.name)} theme`);try{const n="activate"in t?t.activate:!0,i=await r.request({url:"/wp-admin/theme-install.php"}),o=_(i),a=new FormData(o.querySelector(".wp-upload-form")),{themezip:c,...u}=Object.fromEntries(a.entries()),h=await r.request({url:"/wp-admin/update.php?action=upload-theme",method:"POST",formData:u,files:{themezip:e}});if(n){const d=_(h),v=d.querySelector("#wpbody-content > .wrap");if(v?.textContent?.includes("Theme installation failed.")){console.error(v?.textContent);return}const S=d.querySelector("#wpbody-content .activatelink, .update-from-upload-actions .button.button-primary");if(!S){console.error('The "activate" button was not found.');return}const Se=S.attributes.getNamedItem("href").value,Ee=new URL(Se,await r.pathToInternalUrl("/wp-admin/")).toString();await r.request({url:Ee})}}catch(n){console.error(`Proceeding without the ${e.name} theme. Could not install it in wp-admin. The original error was: ${n}`),console.error(n)}},me=async(r,{username:e="admin",password:t="password"}={},s)=>{s?.tracker.setCaption(s?.initialCaption||"Logging in"),await r.request({url:"/wp-login.php"}),await r.request({url:"/wp-login.php",method:"POST",formData:{log:e,pwd:t,rememberme:"forever"}})},we=async(r,{options:e})=>{await r.request({url:"/wp-admin/install.php?step=2",method:"POST",formData:{language:"en",prefix:"wp_",weblog_title:"My WordPress Website",user_name:e.adminPassword||"admin",admin_password:e.adminPassword||"password",admin_password2:e.adminPassword||"password",Submit:"Install WordPress",pw_weak:"1",admin_email:"admin@localhost.com"}})},ge=async(r,{options:e})=>{const t=`<?php
80
+ ?>${o}`)},C=async(r,{zipPath:e,extractToPath:t})=>{const s=F({zipPath:e,extractToPath:t});await fe(r,`unzip(${s.zipPath}, ${s.extractToPath});`)},de=async(r,{file:e})=>{const t=await r.request({url:"/wp-admin/admin.php?import=wordpress"}),s=N(t).getElementById("import-upload-form")?.getAttribute("action"),n=await r.request({url:`/wp-admin/${s}`,method:"POST",files:{import:e}}),i=N(n).querySelector("#wpbody-content form");if(!i)throw console.log(n.text),new Error("Could not find an importer form in response. See the response text above for details.");const o=Ue(i);o.fetch_attachments="1";for(const a in o)if(a.startsWith("user_map[")){const c="user_new["+a.slice(9,-1)+"]";o[c]="1"}await r.request({url:i.action,method:"POST",formData:o})};function N(r){return new DOMParser().parseFromString(r.text,"text/html")}function Ue(r){return Object.fromEntries(new FormData(r).entries())}async function Oe(r,e,t){await r.writeFile(e,t(await r.readFileAsText(e)))}async function fe(r,e){const t=await r.run({code:H+e});if(t.exitCode!==0)throw console.log(H+e),console.log(e+""),console.log(t.errors),t.errors;return t}const me=async(r,{pluginZipFile:e,options:t={}},s)=>{s?.tracker.setCaption(`Installing the ${E(e?.name)} plugin`);try{const n="activate"in t?t.activate:!0,i=await r.request({url:"/wp-admin/plugin-install.php?tab=upload"}),o=b(i),a=new FormData(o.querySelector(".wp-upload-form")),{pluginzip:c,...u}=Object.fromEntries(a.entries()),h=await r.request({url:"/wp-admin/update.php?action=upload-plugin",method:"POST",formData:u,files:{pluginzip:e}});if(n){const v=b(h).querySelector("#wpbody-content .button.button-primary").attributes.getNamedItem("href").value,S=new URL(v,await r.pathToInternalUrl("/wp-admin/")).toString();await r.request({url:S})}await r.isDir("/wordpress/wp-content/plugins/gutenberg")&&!await r.fileExists("/wordpress/.gutenberg-patched")&&(await r.writeFile("/wordpress/.gutenberg-patched","1"),await W(r,"/wordpress/wp-content/plugins/gutenberg/build/block-editor/index.js",d=>d.replace(/srcDoc:("[^"]+"|[^,]+)/g,'src:"/wp-includes/empty.html"')),await W(r,"/wordpress/wp-content/plugins/gutenberg/build/block-editor/index.min.js",d=>d.replace(/srcDoc:("[^"]+"|[^,]+)/g,'src:"/wp-includes/empty.html"')))}catch(n){console.error(`Proceeding without the ${e.name} theme. Could not install it in wp-admin. The original error was: ${n}`),console.error(n)}};async function W(r,e,t){return await r.writeFile(e,t(await r.readFileAsText(e)))}const we=async(r,{themeZipFile:e,options:t={}},s)=>{s?.tracker.setCaption(`Installing the ${E(e.name)} theme`);try{const n="activate"in t?t.activate:!0,i=await r.request({url:"/wp-admin/theme-install.php"}),o=b(i),a=new FormData(o.querySelector(".wp-upload-form")),{themezip:c,...u}=Object.fromEntries(a.entries()),h=await r.request({url:"/wp-admin/update.php?action=upload-theme",method:"POST",formData:u,files:{themezip:e}});if(n){const d=b(h),v=d.querySelector("#wpbody-content > .wrap");if(v?.textContent?.includes("Theme installation failed.")){console.error(v?.textContent);return}const S=d.querySelector("#wpbody-content .activatelink, .update-from-upload-actions .button.button-primary");if(!S){console.error('The "activate" button was not found.');return}const Te=S.attributes.getNamedItem("href").value,xe=new URL(Te,await r.pathToInternalUrl("/wp-admin/")).toString();await r.request({url:xe})}}catch(n){console.error(`Proceeding without the ${e.name} theme. Could not install it in wp-admin. The original error was: ${n}`),console.error(n)}},ge=async(r,{username:e="admin",password:t="password"}={},s)=>{s?.tracker.setCaption(s?.initialCaption||"Logging in"),await r.request({url:"/wp-login.php"}),await r.request({url:"/wp-login.php",method:"POST",formData:{log:e,pwd:t,rememberme:"forever"}})},ye=async(r,{options:e})=>{await r.request({url:"/wp-admin/install.php?step=2",method:"POST",formData:{language:"en",prefix:"wp_",weblog_title:"My WordPress Website",user_name:e.adminPassword||"admin",admin_password:e.adminPassword||"password",admin_password2:e.adminPassword||"password",Submit:"Install WordPress",pw_weak:"1",admin_email:"admin@localhost.com"}})},Pe=async(r,{options:e})=>{const t=`<?php
81
81
  include 'wordpress/wp-load.php';
82
- $site_options = ${b(e)};
82
+ $site_options = ${_(e)};
83
83
  foreach($site_options as $name => $value) {
84
84
  update_option($name, $value);
85
85
  }
86
86
  echo "Success";
87
- `,s=await r.run({code:t});return Pe(s),{code:t,result:s}},ye=async(r,{meta:e,userId:t})=>{const s=`<?php
87
+ `,s=await r.run({code:t});return be(s),{code:t,result:s}},_e=async(r,{meta:e,userId:t})=>{const s=`<?php
88
88
  include 'wordpress/wp-load.php';
89
- $meta = ${b(e)};
89
+ $meta = ${_(e)};
90
90
  foreach($meta as $name => $value) {
91
- update_user_meta(${b(t)}, $name, $value);
91
+ update_user_meta(${_(t)}, $name, $value);
92
92
  }
93
93
  echo "Success";
94
- `,n=await r.run({code:s});return Pe(n),{code:s,result:n}};async function Pe(r){if(r.text!=="Success")throw console.log(r),new Error(`Failed to run code: ${r.text} ${r.errors}`)}const Ce=Object.freeze(Object.defineProperty({__proto__:null,activatePlugin:K,applyWordPressPatches:Y,cp:te,defineSiteUrl:ae,defineWpConfigConsts:x,importFile:he,installPlugin:de,installTheme:fe,login:me,mkdir:se,mv:re,replaceSite:ue,request:ee,rm:ne,rmdir:ie,runPHP:Z,runPHPWithOptions:Q,runWpInstallationWizard:we,setPhpIniEntry:X,setSiteOptions:ge,unzip:k,updateUserMeta:ye,writeFile:oe,zipEntireSite:le},Symbol.toStringTag,{value:"Module"})),Ue=5*1024*1024;function Oe(r,e){const t=r.headers.get("content-length")||"",s=parseInt(t,10)||Ue;function n(i,o){e(new CustomEvent("progress",{detail:{loaded:i,total:o}}))}return new Response(new ReadableStream({async start(i){if(!r.body){i.close();return}const o=r.body.getReader();let a=0;for(;;)try{const{done:c,value:u}=await o.read();if(u&&(a+=u.byteLength),c){n(a,a),i.close();break}else n(a,s),i.enqueue(u)}catch(c){console.error({e:c}),i.error(c);break}}}),{status:r.status,statusText:r.statusText,headers:r.headers})}const R=1e-5;class C extends EventTarget{constructor({weight:e=1,caption:t="",fillTime:s=4}={}){super(),this._selfWeight=1,this._selfDone=!1,this._selfProgress=0,this._selfCaption="",this._isFilling=!1,this._subTrackers=[],this._weight=e,this._selfCaption=t,this._fillTime=s}stage(e,t=""){if(e||(e=this._selfWeight),this._selfWeight-e<-R)throw new Error(`Cannot add a stage with weight ${e} as the total weight of registered stages would exceed 1.`);this._selfWeight-=e;const s=new C({caption:t,weight:e,fillTime:this._fillTime});return this._subTrackers.push(s),s.addEventListener("progress",()=>this.notifyProgress()),s.addEventListener("done",()=>{this.done&&this.notifyDone()}),s}fillSlowly({stopBeforeFinishing:e=!0}={}){if(this._isFilling)return;this._isFilling=!0;const t=100,s=this._fillTime/t;this._fillInterval=setInterval(()=>{this.set(this._selfProgress+1),e&&this._selfProgress>=99&&clearInterval(this._fillInterval)},s)}set(e){this._selfProgress=Math.min(e,100),this.notifyProgress(),this._selfProgress+R>=100&&this.finish()}finish(){this._fillInterval&&clearInterval(this._fillInterval),this._selfDone=!0,this._selfProgress=100,this._isFilling=!1,this._fillInterval=void 0,this.notifyProgress(),this.notifyDone()}get caption(){for(let e=this._subTrackers.length-1;e>=0;e--)if(!this._subTrackers[e].done){const t=this._subTrackers[e].caption;if(t)return t}return this._selfCaption}setCaption(e){this._selfCaption=e,this.notifyProgress()}get done(){return this.progress+R>=100}get progress(){if(this._selfDone)return 100;const e=this._subTrackers.reduce((t,s)=>t+s.progress*s.weight,this._selfProgress*this._selfWeight);return Math.round(e*1e4)/1e4}get weight(){return this._weight}get observer(){return this._progressObserver||(this._progressObserver=e=>{this.set(e)}),this._progressObserver}get loadingListener(){return this._loadingListener||(this._loadingListener=e=>{this.set(e.detail.loaded/e.detail.total*100)}),this._loadingListener}pipe(e){e.setProgress({progress:this.progress,caption:this.caption}),this.addEventListener("progress",t=>{e.setProgress({progress:t.detail.progress,caption:t.detail.caption})}),this.addEventListener("done",()=>{e.setLoaded()})}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}notifyProgress(){const e=this;this.dispatchEvent(new CustomEvent("progress",{detail:{get progress(){return e.progress},get caption(){return e.caption}}}))}notifyDone(){this.dispatchEvent(new CustomEvent("done"))}}class ${constructor(e,t,s,n="",i=0){this.httpStatusCode=e,this.headers=t,this.bytes=s,this.exitCode=i,this.errors=n}static fromRawData(e){return new $(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}const be=["8.2","8.1","8.0","7.4","7.3","7.2","7.1","7.0","5.6"],Ae=be[0];class Ie{#e;#t;constructor(e,t={}){this.requestHandler=e,this.#e={},this.#t={handleRedirects:!1,maxRedirects:4,...t}}async request(e,t=0){const s=await this.requestHandler.request({...e,headers:{...e.headers,cookie:this.#n()}});if(s.headers["set-cookie"]&&this.#r(s.headers["set-cookie"]),this.#t.handleRedirects&&s.headers.location&&t<this.#t.maxRedirects){const n=new URL(s.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:n.toString(),method:"GET",headers:{}},t+1)}return s}pathToInternalUrl(e){return this.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.internalUrlToPath(e)}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}#r(e){for(const t of e)try{if(!t.includes("="))continue;const s=t.indexOf("="),n=t.substring(0,s),i=t.substring(s+1).split(";")[0];this.#e[n]=i}catch(s){console.error(s)}}#n(){const e=[];for(const t in this.#e)e.push(`${t}=${this.#e[t]}`);return e.join("; ")}}const Le="http://example.com";function N(r){return r.toString().substring(r.origin.length)}function W(r,e){return!e||!r.startsWith(e)?r:r.substring(e.length)}function He(r,e){return!e||r.startsWith(e)?r:e+r}class Ne{#e;#t;#r;#n;#i;#s;#o;#a;#c;constructor(e,t={}){this.#a=new ce({concurrency:1});const{documentRoot:s="/www/",absoluteUrl:n=typeof location=="object"?location?.href:"",isStaticFilePath:i=()=>!1}=t;this.php=e,this.#e=s,this.#c=i;const o=new URL(n);this.#r=o.hostname,this.#n=o.port?Number(o.port):o.protocol==="https:"?443:80,this.#t=(o.protocol||"").replace(":","");const a=this.#n!==443&&this.#n!==80;this.#i=[this.#r,a?`:${this.#n}`:""].join(""),this.#s=o.pathname.replace(/\/+$/,""),this.#o=[`${this.#t}://`,this.#i,this.#s].join("")}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const t=new URL(e);return t.pathname.startsWith(this.#s)&&(t.pathname=t.pathname.slice(this.#s.length)),N(t)}get isRequestRunning(){return this.#a.running>0}get absoluteUrl(){return this.#o}get documentRoot(){return this.#e}async request(e){const t=e.url.startsWith("http://")||e.url.startsWith("https://"),s=new URL(e.url,t?void 0:Le),n=W(s.pathname,this.#s);return this.#c(n)?this.#l(n):await this.#u(e,s)}#l(e){const t=`${this.#e}${e}`;if(!this.php.fileExists(t))return new $(404,{},new TextEncoder().encode("404 File not found"));const s=this.php.readFileAsBuffer(t);return new $(200,{"content-length":[`${s.byteLength}`],"content-type":[qe(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)}async#u(e,t){const s=await this.#a.acquire();try{this.php.addServerGlobalEntry("DOCUMENT_ROOT",this.#e),this.php.addServerGlobalEntry("HTTPS",this.#o.startsWith("https://")?"on":"");let n="GET";const i={host:this.#i,..._e(e.headers||{})},o=[];if(e.files&&Object.keys(e.files).length){n="POST";for(const c in e.files){const u=e.files[c];o.push({key:c,name:u.name,type:u.type,data:new Uint8Array(await u.arrayBuffer())})}i["content-type"]?.startsWith("multipart/form-data")&&(e.formData=We(e.body||""),i["content-type"]="application/x-www-form-urlencoded",delete e.body)}let a;return e.formData!==void 0?(n="POST",i["content-type"]=i["content-type"]||"application/x-www-form-urlencoded",a=new URLSearchParams(e.formData).toString()):a=e.body,await this.php.run({relativeUri:He(N(t),this.#s),protocol:this.#t,method:e.method||n,body:a,fileInfos:o,scriptPath:this.#h(t.pathname),headers:i})}finally{s()}}#h(e){let t=W(e,this.#s);t.includes(".php")?t=t.split(".php")[0]+".php":(t.endsWith("/")||(t+="/"),t.endsWith("index.php")||(t+="index.php"));const s=`${this.#e}${t}`;return this.php.fileExists(s)?s:`${this.#e}/index.php`}}function We(r){const e={},t=r.match(/--(.*)\r\n/);if(!t)return e;const s=t[1],n=r.split(`--${s}`);return n.shift(),n.pop(),n.forEach(i=>{const o=i.indexOf(`\r
95
- \r
96
- `),a=i.substring(0,o).trim(),c=i.substring(o+4).trim(),u=a.match(/name="([^"]+)"/);if(u){const h=u[1];e[h]=c}}),e}function qe(r){switch(r.split(".").pop()){case"css":return"text/css";case"js":return"application/javascript";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"svg":return"image/svg+xml";case"woff":return"font/woff";case"woff2":return"font/woff2";case"ttf":return"font/ttf";case"otf":return"font/otf";case"eot":return"font/eot";case"ico":return"image/x-icon";case"html":return"text/html";case"json":return"application/json";case"xml":return"application/xml";case"txt":case"md":return"text/plain";default:return"application-octet-stream"}}const q={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function f(r=""){return function(t,s,n){const i=n.value;n.value=function(...o){try{return i.apply(this,o)}catch(a){const c=typeof a=="object"?a?.errno:null;if(c in q){const u=q[c],h=typeof o[0]=="string"?o[0]:null,d=h!==null?r.replaceAll("{path}",h):r;throw new Error(`${d}: ${u}`,{cause:a})}throw a}}}}const De=[];function Me(r){return De[r]}(function(){return typeof process<"u"&&process.release?.name==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();const D=Symbol("error"),M=Symbol("message");class U extends Event{constructor(e,t={}){super(e),this[D]=t.error===void 0?null:t.error,this[M]=t.message===void 0?"":t.message}get error(){return this[D]}get message(){return this[M]}}Object.defineProperty(U.prototype,"error",{enumerable:!0});Object.defineProperty(U.prototype,"message",{enumerable:!0});const ze=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:U;class Be extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,t){++this.listenersCount,super.addEventListener(e,t)}removeEventListener(e,t){--this.listenersCount,super.removeEventListener(e,t)}hasListeners(){return this.listenersCount>0}}function je(r){r.asm={...r.asm};const e=new Be;for(const t in r.asm)if(typeof r.asm[t]=="function"){const s=r.asm[t];r.asm[t]=function(...n){try{return s(...n)}catch(i){if(!(i instanceof Error))throw i;if("exitCode"in i&&i?.exitCode===0)return;const o=Ve(i,r.lastAsyncifyStackSource?.stack);if(r.lastAsyncifyStackSource&&(i.cause=r.lastAsyncifyStackSource),!e.hasListeners())throw Ye(o),i;e.dispatchEvent(new ze("error",{error:i,message:o}))}}}return e}let T=[];function Ge(){return T}function Ve(r,e){if(r.message==="unreachable"){let t=Je;e||(t+=`
94
+ `,n=await r.run({code:s});return be(n),{code:s,result:n}};async function be(r){if(r.text!=="Success")throw console.log(r),new Error(`Failed to run code: ${r.text} ${r.errors}`)}const $e=async(r,{consts:e})=>{r.mkdir(I);const t=`${I}/playground-consts.json`;return await g(r,t,s=>JSON.stringify({...JSON.parse(s||"{}"),...e})),await g(r,L,s=>s.includes("playground-consts.json")?s:`<?php
95
+ $consts = json_decode(file_get_contents('${t}'), true);
96
+ foreach ($consts as $const => $value) {
97
+ if (!defined($const)) {
98
+ define($const, $value);
99
+ }
100
+ }
101
+ ?>${s}`),L},Ae=Object.freeze(Object.defineProperty({__proto__:null,activatePlugin:Z,applyWordPressPatches:Q,cp:se,defineSiteUrl:le,defineVirtualWpConfigConsts:$e,defineWpConfigConsts:x,importFile:de,installPlugin:me,installTheme:we,login:ge,mkdir:ie,mv:ne,replaceSite:pe,request:re,rm:oe,rmdir:ae,runPHP:X,runPHPWithOptions:ee,runWpInstallationWizard:ye,setPhpIniEntry:te,setSiteOptions:Pe,unzip:C,updateUserMeta:_e,writeFile:ce,zipEntireSite:he},Symbol.toStringTag,{value:"Module"})),Ie=5*1024*1024;function Le(r,e){const t=r.headers.get("content-length")||"",s=parseInt(t,10)||Ie;function n(i,o){e(new CustomEvent("progress",{detail:{loaded:i,total:o}}))}return new Response(new ReadableStream({async start(i){if(!r.body){i.close();return}const o=r.body.getReader();let a=0;for(;;)try{const{done:c,value:u}=await o.read();if(u&&(a+=u.byteLength),c){n(a,a),i.close();break}else n(a,s),i.enqueue(u)}catch(c){console.error({e:c}),i.error(c);break}}}),{status:r.status,statusText:r.statusText,headers:r.headers})}const R=1e-5;class k extends EventTarget{constructor({weight:e=1,caption:t="",fillTime:s=4}={}){super(),this._selfWeight=1,this._selfDone=!1,this._selfProgress=0,this._selfCaption="",this._isFilling=!1,this._subTrackers=[],this._weight=e,this._selfCaption=t,this._fillTime=s}stage(e,t=""){if(e||(e=this._selfWeight),this._selfWeight-e<-R)throw new Error(`Cannot add a stage with weight ${e} as the total weight of registered stages would exceed 1.`);this._selfWeight-=e;const s=new k({caption:t,weight:e,fillTime:this._fillTime});return this._subTrackers.push(s),s.addEventListener("progress",()=>this.notifyProgress()),s.addEventListener("done",()=>{this.done&&this.notifyDone()}),s}fillSlowly({stopBeforeFinishing:e=!0}={}){if(this._isFilling)return;this._isFilling=!0;const t=100,s=this._fillTime/t;this._fillInterval=setInterval(()=>{this.set(this._selfProgress+1),e&&this._selfProgress>=99&&clearInterval(this._fillInterval)},s)}set(e){this._selfProgress=Math.min(e,100),this.notifyProgress(),this._selfProgress+R>=100&&this.finish()}finish(){this._fillInterval&&clearInterval(this._fillInterval),this._selfDone=!0,this._selfProgress=100,this._isFilling=!1,this._fillInterval=void 0,this.notifyProgress(),this.notifyDone()}get caption(){for(let e=this._subTrackers.length-1;e>=0;e--)if(!this._subTrackers[e].done){const t=this._subTrackers[e].caption;if(t)return t}return this._selfCaption}setCaption(e){this._selfCaption=e,this.notifyProgress()}get done(){return this.progress+R>=100}get progress(){if(this._selfDone)return 100;const e=this._subTrackers.reduce((t,s)=>t+s.progress*s.weight,this._selfProgress*this._selfWeight);return Math.round(e*1e4)/1e4}get weight(){return this._weight}get observer(){return this._progressObserver||(this._progressObserver=e=>{this.set(e)}),this._progressObserver}get loadingListener(){return this._loadingListener||(this._loadingListener=e=>{this.set(e.detail.loaded/e.detail.total*100)}),this._loadingListener}pipe(e){e.setProgress({progress:this.progress,caption:this.caption}),this.addEventListener("progress",t=>{e.setProgress({progress:t.detail.progress,caption:t.detail.caption})}),this.addEventListener("done",()=>{e.setLoaded()})}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}notifyProgress(){const e=this;this.dispatchEvent(new CustomEvent("progress",{detail:{get progress(){return e.progress},get caption(){return e.caption}}}))}notifyDone(){this.dispatchEvent(new CustomEvent("done"))}}const q=Symbol("error"),D=Symbol("message");class U extends Event{constructor(e,t={}){super(e),this[q]=t.error===void 0?null:t.error,this[D]=t.message===void 0?"":t.message}get error(){return this[q]}get message(){return this[D]}}Object.defineProperty(U.prototype,"error",{enumerable:!0});Object.defineProperty(U.prototype,"message",{enumerable:!0});const He=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:U;class Ne extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,t){++this.listenersCount,super.addEventListener(e,t)}removeEventListener(e,t){--this.listenersCount,super.removeEventListener(e,t)}hasListeners(){return this.listenersCount>0}}function We(r){r.asm={...r.asm};const e=new Ne;for(const t in r.asm)if(typeof r.asm[t]=="function"){const s=r.asm[t];r.asm[t]=function(...n){try{return s(...n)}catch(i){if(!(i instanceof Error))throw i;if("exitCode"in i&&i?.exitCode===0)return;const o=De(i,r.lastAsyncifyStackSource?.stack);if(r.lastAsyncifyStackSource&&(i.cause=r.lastAsyncifyStackSource),!e.hasListeners())throw je(o),i;e.dispatchEvent(new He("error",{error:i,message:o}))}}}return e}let T=[];function qe(){return T}function De(r,e){if(r.message==="unreachable"){let t=Me;e||(t+=`
97
102
 
98
103
  This stack trace is lacking. For a better one initialize
99
104
  the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
100
105
 
101
- `),T=Ze(e||r.stack||"");for(const s of T)t+=` * ${s}
102
- `;return t}return r.message}const Je=`
106
+ `),T=Be(e||r.stack||"");for(const s of T)t+=` * ${s}
107
+ `;return t}return r.message}const Me=`
103
108
  "unreachable" WASM instruction executed.
104
109
 
105
110
  The typical reason is a PHP function missing from the ASYNCIFY_ONLY
@@ -123,11 +128,13 @@ the Dockerfile, you'll need to trigger this error again with long stack
123
128
  traces enabled. In node.js, you can do it using the --stack-trace-limit=100
124
129
  CLI option:
125
130
 
126
- `,z="\x1B[41m",Ke="\x1B[1m",B="\x1B[0m",j="\x1B[K";let G=!1;function Ye(r){if(!G){G=!0,console.log(`${z}
131
+ `,M="\x1B[41m",ze="\x1B[1m",z="\x1B[0m",j="\x1B[K";let B=!1;function je(r){if(!B){B=!0,console.log(`${M}
127
132
  ${j}
128
- ${Ke} WASM ERROR${B}${z}`);for(const e of r.split(`
129
- `))console.log(`${j} ${e} `);console.log(`${B}`)}}function Ze(r){try{const e=r.split(`
130
- `).slice(1).map(t=>{const s=t.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:t.includes("wasm://")}}).filter(({fn:t,isWasm:s})=>s&&!t.startsWith("dynCall_")&&!t.startsWith("invoke_")).map(({fn:t})=>t);return Array.from(new Set(e))}catch{return[]}}var Qe=Object.defineProperty,Xe=Object.getOwnPropertyDescriptor,m=(r,e,t,s)=>{for(var n=s>1?void 0:s?Xe(e,t):e,i=r.length-1,o;i>=0;i--)(o=r[i])&&(n=(s?o(e,t,n):o(n))||n);return s&&n&&Qe(e,t,n),n};const p="string",y="number",l=Symbol("__private__dont__use");class w{constructor(e,t){this.#e=[],this.#t=!1,this.#r=null,e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new Ie(new Ne(this,t)))}#e;#t;#r;get absoluteUrl(){return this.requestHandler.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.requestHandler.documentRoot}pathToInternalUrl(e){return this.requestHandler.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.requestHandler.internalUrlToPath(e)}initializeRuntime(e){if(this[l])throw new Error("PHP runtime already initialized.");const t=Me(e);if(!t)throw new Error("Invalid PHP runtime id.");this[l]=t,this.#r=je(t)}setPhpIniPath(e){if(this.#t)throw new Error("Cannot set PHP ini path after calling run().");this[l].ccall("wasm_set_phpini_path",null,["string"],[e])}setPhpIniEntry(e,t){if(this.#t)throw new Error("Cannot set PHP ini entries after calling run().");this.#e.push([e,t])}chdir(e){this[l].FS.chdir(e)}async request(e,t){if(!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(e,t)}async run(e){this.#t||(this.#n(),this.#t=!0),this.#u(e.scriptPath||""),this.#s(e.relativeUri||""),this.#a(e.method||"GET");const{host:t,...s}={host:"example.com:443",..._e(e.headers||{})};if(this.#o(t,e.protocol||"http"),this.#c(s),e.body&&this.#l(e.body),e.fileInfos)for(const n of e.fileInfos)this.#h(n);return e.code&&this.#p(" ?>"+e.code),await this.#d()}#n(){if(this.#e.length>0){const e=this.#e.map(([t,s])=>`${t}=${s}`).join(`
133
+ ${ze} WASM ERROR${z}${M}`);for(const e of r.split(`
134
+ `))console.log(`${j} ${e} `);console.log(`${z}`)}}function Be(r){try{const e=r.split(`
135
+ `).slice(1).map(t=>{const s=t.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:t.includes("wasm://")}}).filter(({fn:t,isWasm:s})=>s&&!t.startsWith("dynCall_")&&!t.startsWith("invoke_")).map(({fn:t})=>t);return Array.from(new Set(e))}catch{return[]}}class ${constructor(e,t,s,n="",i=0){this.httpStatusCode=e,this.headers=t,this.bytes=s,this.exitCode=i,this.errors=n}static fromRawData(e){return new $(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}const ve=["8.2","8.1","8.0","7.4","7.3","7.2","7.1","7.0","5.6"],Ve=ve[0];class Ge{#e;#t;constructor(e,t={}){this.requestHandler=e,this.#e={},this.#t={handleRedirects:!1,maxRedirects:4,...t}}async request(e,t=0){const s=await this.requestHandler.request({...e,headers:{...e.headers,cookie:this.#r()}});if(s.headers["set-cookie"]&&this.#s(s.headers["set-cookie"]),this.#t.handleRedirects&&s.headers.location&&t<this.#t.maxRedirects){const n=new URL(s.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:n.toString(),method:"GET",headers:{}},t+1)}return s}pathToInternalUrl(e){return this.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.internalUrlToPath(e)}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}#s(e){for(const t of e)try{if(!t.includes("="))continue;const s=t.indexOf("="),n=t.substring(0,s),i=t.substring(s+1).split(";")[0];this.#e[n]=i}catch(s){console.error(s)}}#r(){const e=[];for(const t in this.#e)e.push(`${t}=${this.#e[t]}`);return e.join("; ")}}const Je="http://example.com";function V(r){return r.toString().substring(r.origin.length)}function G(r,e){return!e||!r.startsWith(e)?r:r.substring(e.length)}function Ke(r,e){return!e||r.startsWith(e)?r:e+r}class Ye{#e;#t;#s;#r;#i;#n;#o;#a;#c;constructor(e,t={}){this.#a=new ue({concurrency:1});const{documentRoot:s="/www/",absoluteUrl:n=typeof location=="object"?location?.href:"",isStaticFilePath:i=()=>!1}=t;this.php=e,this.#e=s,this.#c=i;const o=new URL(n);this.#s=o.hostname,this.#r=o.port?Number(o.port):o.protocol==="https:"?443:80,this.#t=(o.protocol||"").replace(":","");const a=this.#r!==443&&this.#r!==80;this.#i=[this.#s,a?`:${this.#r}`:""].join(""),this.#n=o.pathname.replace(/\/+$/,""),this.#o=[`${this.#t}://`,this.#i,this.#n].join("")}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const t=new URL(e);return t.pathname.startsWith(this.#n)&&(t.pathname=t.pathname.slice(this.#n.length)),V(t)}get isRequestRunning(){return this.#a.running>0}get absoluteUrl(){return this.#o}get documentRoot(){return this.#e}async request(e){const t=e.url.startsWith("http://")||e.url.startsWith("https://"),s=new URL(e.url,t?void 0:Je),n=G(s.pathname,this.#n);return this.#c(n)?this.#l(n):await this.#u(e,s)}#l(e){const t=`${this.#e}${e}`;if(!this.php.fileExists(t))return new $(404,{},new TextEncoder().encode("404 File not found"));const s=this.php.readFileAsBuffer(t);return new $(200,{"content-length":[`${s.byteLength}`],"content-type":[Qe(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)}async#u(e,t){const s=await this.#a.acquire();try{this.php.addServerGlobalEntry("DOCUMENT_ROOT",this.#e),this.php.addServerGlobalEntry("HTTPS",this.#o.startsWith("https://")?"on":"");let n="GET";const i={host:this.#i,...Se(e.headers||{})},o=[];if(e.files&&Object.keys(e.files).length){n="POST";for(const c in e.files){const u=e.files[c];o.push({key:c,name:u.name,type:u.type,data:new Uint8Array(await u.arrayBuffer())})}i["content-type"]?.startsWith("multipart/form-data")&&(e.formData=Ze(e.body||""),i["content-type"]="application/x-www-form-urlencoded",delete e.body)}let a;return e.formData!==void 0?(n="POST",i["content-type"]=i["content-type"]||"application/x-www-form-urlencoded",a=new URLSearchParams(e.formData).toString()):a=e.body,await this.php.run({relativeUri:Ke(V(t),this.#n),protocol:this.#t,method:e.method||n,body:a,fileInfos:o,scriptPath:this.#h(t.pathname),headers:i})}finally{s()}}#h(e){let t=G(e,this.#n);t.includes(".php")?t=t.split(".php")[0]+".php":(t.endsWith("/")||(t+="/"),t.endsWith("index.php")||(t+="index.php"));const s=`${this.#e}${t}`;return this.php.fileExists(s)?s:`${this.#e}/index.php`}}function Ze(r){const e={},t=r.match(/--(.*)\r\n/);if(!t)return e;const s=t[1],n=r.split(`--${s}`);return n.shift(),n.pop(),n.forEach(i=>{const o=i.indexOf(`\r
136
+ \r
137
+ `),a=i.substring(0,o).trim(),c=i.substring(o+4).trim(),u=a.match(/name="([^"]+)"/);if(u){const h=u[1];e[h]=c}}),e}function Qe(r){switch(r.split(".").pop()){case"css":return"text/css";case"js":return"application/javascript";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"svg":return"image/svg+xml";case"woff":return"font/woff";case"woff2":return"font/woff2";case"ttf":return"font/ttf";case"otf":return"font/otf";case"eot":return"font/eot";case"ico":return"image/x-icon";case"html":return"text/html";case"json":return"application/json";case"xml":return"application/xml";case"txt":case"md":return"text/plain";default:return"application-octet-stream"}}const J={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function f(r=""){return function(t,s,n){const i=n.value;n.value=function(...o){try{return i.apply(this,o)}catch(a){const c=typeof a=="object"?a?.errno:null;if(c in J){const u=J[c],h=typeof o[0]=="string"?o[0]:null,d=h!==null?r.replaceAll("{path}",h):r;throw new Error(`${d}: ${u}`,{cause:a})}throw a}}}}const Xe=[];function et(r){return Xe[r]}(function(){return typeof process<"u"&&process.release?.name==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();var tt=Object.defineProperty,rt=Object.getOwnPropertyDescriptor,m=(r,e,t,s)=>{for(var n=s>1?void 0:s?rt(e,t):e,i=r.length-1,o;i>=0;i--)(o=r[i])&&(n=(s?o(e,t,n):o(n))||n);return s&&n&&tt(e,t,n),n};const p="string",P="number",l=Symbol("__private__dont__use");class w{constructor(e,t){this.#e=[],this.#t=!1,this.#s=null,this.#r={},e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new Ge(new Ye(this,t)))}#e;#t;#s;#r;get absoluteUrl(){return this.requestHandler.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.requestHandler.documentRoot}pathToInternalUrl(e){return this.requestHandler.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.requestHandler.internalUrlToPath(e)}initializeRuntime(e){if(this[l])throw new Error("PHP runtime already initialized.");const t=et(e);if(!t)throw new Error("Invalid PHP runtime id.");this[l]=t,this.#s=We(t)}setPhpIniPath(e){if(this.#t)throw new Error("Cannot set PHP ini path after calling run().");this[l].ccall("wasm_set_phpini_path",null,["string"],[e])}setPhpIniEntry(e,t){if(this.#t)throw new Error("Cannot set PHP ini entries after calling run().");this.#e.push([e,t])}chdir(e){this[l].FS.chdir(e)}async request(e,t){if(!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(e,t)}async run(e){this.#t||(this.#i(),this.#t=!0),this.#h(e.scriptPath||""),this.#o(e.relativeUri||""),this.#c(e.method||"GET");const{host:t,...s}={host:"example.com:443",...Se(e.headers||{})};if(this.#a(t,e.protocol||"http"),this.#l(s),e.body&&this.#u(e.body),e.fileInfos)for(const n of e.fileInfos)this.#d(n);return e.code&&this.#f(" ?>"+e.code),this.#p(),await this.#m()}#i(){if(this.#e.length>0){const e=this.#e.map(([t,s])=>`${t}=${s}`).join(`
131
138
  `)+`
132
139
 
133
- `;this[l].ccall("wasm_set_phpini_entries",null,[p],[e])}this[l].ccall("php_wasm_init",null,[],[])}#i(){const e="/tmp/headers.json";if(!this.fileExists(e))throw new Error("SAPI Error: Could not find response headers file.");const t=JSON.parse(this.readFileAsText(e)),s={};for(const n of t.headers){if(!n.includes(": "))continue;const i=n.indexOf(": "),o=n.substring(0,i).toLowerCase(),a=n.substring(i+2);o in s||(s[o]=[]),s[o].push(a)}return{headers:s,httpStatusCode:t.status}}#s(e){if(this[l].ccall("wasm_set_request_uri",null,[p],[e]),e.includes("?")){const t=e.substring(e.indexOf("?")+1);this[l].ccall("wasm_set_query_string",null,[p],[t])}}#o(e,t){this[l].ccall("wasm_set_request_host",null,[p],[e]);let s;try{s=parseInt(new URL(e).port,10)}catch{}(!s||isNaN(s)||s===80)&&(s=t==="https"?443:80),this[l].ccall("wasm_set_request_port",null,[y],[s]),(t==="https"||!t&&s===443)&&this.addServerGlobalEntry("HTTPS","on")}#a(e){this[l].ccall("wasm_set_request_method",null,[p],[e])}#c(e){e.cookie&&this[l].ccall("wasm_set_cookies",null,[p],[e.cookie]),e["content-type"]&&this[l].ccall("wasm_set_content_type",null,[p],[e["content-type"]]),e["content-length"]&&this[l].ccall("wasm_set_content_length",null,[y],[parseInt(e["content-length"],10)]);for(const t in e)this.addServerGlobalEntry(`HTTP_${t.toUpperCase().replace(/-/g,"_")}`,e[t])}#l(e){this[l].ccall("wasm_set_request_body",null,[p],[e]),this[l].ccall("wasm_set_content_length",null,[y],[new TextEncoder().encode(e).length])}#u(e){this[l].ccall("wasm_set_path_translated",null,[p],[e])}addServerGlobalEntry(e,t){this[l].ccall("wasm_add_SERVER_entry",null,[p,p],[e,t])}#h(e){const{key:t,name:s,type:n,data:i}=e,o=`/tmp/${Math.random().toFixed(20)}`;this.writeFile(o,i);const a=0;this[l].ccall("wasm_add_uploaded_file",null,[p,p,p,p,y,y],[t,s,n,o,a,i.byteLength])}#p(e){this[l].ccall("wasm_set_php_code",null,[p],[e])}async#d(){let e,t;try{e=await new Promise(async(i,o)=>{t=a=>{const c=new Error("Rethrown");c.cause=a.error,c.betterMessage=a.message,o(c)},this.#r?.addEventListener("error",t);try{i(await await this[l].ccall("wasm_sapi_handle_request",y,[],[]))}catch(a){o(a)}})}catch(i){for(const u in this)typeof this[u]=="function"&&(this[u]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=Ge();const o=i,a="betterMessage"in o?o.betterMessage:o.message,c=new Error(a);throw c.cause=o,c}finally{this.#r?.removeEventListener("error",t)}const{headers:s,httpStatusCode:n}=this.#i();return new $(n,s,this.readFileAsBuffer("/tmp/stdout"),this.readFileAsText("/tmp/stderr"),e)}mkdir(e){this[l].FS.mkdirTree(e)}mkdirTree(e){this.mkdir(e)}readFileAsText(e){return new TextDecoder().decode(this.readFileAsBuffer(e))}readFileAsBuffer(e){return this[l].FS.readFile(e)}writeFile(e,t){this[l].FS.writeFile(e,t)}unlink(e){this[l].FS.unlink(e)}mv(e,t){this[l].FS.mv(e,t)}rmdir(e,t={recursive:!0}){t?.recursive&&this.listFiles(e).forEach(s=>{const n=`${e}/${s}`;this.isDir(n)?this.rmdir(n,t):this.unlink(n)}),this[l].FS.rmdir(e)}listFiles(e){if(!this.fileExists(e))return[];try{return this[l].FS.readdir(e).filter(t=>t!=="."&&t!=="..")}catch(t){return console.error(t,{path:e}),[]}}isDir(e){return this.fileExists(e)?this[l].FS.isDir(this[l].FS.lookupPath(e).node.mode):!1}fileExists(e){try{return this[l].FS.lookupPath(e),!0}catch{return!1}}}m([f('Could not create directory "{path}"')],w.prototype,"mkdir",1);m([f('Could not create directory "{path}"')],w.prototype,"mkdirTree",1);m([f('Could not read "{path}"')],w.prototype,"readFileAsText",1);m([f('Could not read "{path}"')],w.prototype,"readFileAsBuffer",1);m([f('Could not write to "{path}"')],w.prototype,"writeFile",1);m([f('Could not unlink "{path}"')],w.prototype,"unlink",1);m([f('Could not move "{path}"')],w.prototype,"mv",1);m([f('Could not remove directory "{path}"')],w.prototype,"rmdir",1);m([f('Could not list files in "{path}"')],w.prototype,"listFiles",1);m([f('Could not stat "{path}"')],w.prototype,"isDir",1);m([f('Could not stat "{path}"')],w.prototype,"fileExists",1);function _e(r){const e={};for(const t in r)e[t.toLowerCase()]=r[t];return e}const et=["vfs","literal","wordpress.org/themes","wordpress.org/plugins","url"];function tt(r){return r&&typeof r=="object"&&typeof r.resource=="string"&&et.includes(r.resource)}class g{static create(e,{semaphore:t,progress:s}){let n;switch(e.resource){case"vfs":n=new rt(e,s);break;case"literal":n=new st(e,s);break;case"wordpress.org/themes":n=new at(e,s);break;case"wordpress.org/plugins":n=new ct(e,s);break;case"url":n=new it(e,s);break;default:throw new Error(`Invalid resource: ${e}`)}return n=new lt(n),t&&(n=new ut(n,t)),n}setPlayground(e){this.playground=e}get isAsync(){return!1}}class rt extends g{constructor(e,t){super(),this.resource=e,this.progress=t}async resolve(){const e=await this.playground.readFileAsBuffer(this.resource.path);return this.progress?.set(100),new File([e],this.name)}get name(){return this.resource.path}}class st extends g{constructor(e,t){super(),this.resource=e,this.progress=t}async resolve(){return this.progress?.set(100),new File([this.resource.contents],this.resource.name)}get name(){return this.resource.name}}class O extends g{constructor(e){super(),this.progress=e}async resolve(){this.progress?.setCaption(this.caption);const e=this.getURL();let t=await fetch(e);if(t=await Oe(t,this.progress?.loadingListener??nt),t.status!==200)throw new Error(`Could not download "${e}"`);return new File([await t.blob()],this.name)}get caption(){return`Downloading ${this.name}`}get name(){try{return new URL(this.getURL(),"http://example.com").pathname.split("/").pop()}catch{return this.getURL()}}get isAsync(){return!0}}const nt=()=>{};class it extends O{constructor(e,t){super(t),this.resource=e}getURL(){return this.resource.url}get caption(){return this.resource.caption??super.caption}}let A="https://playground.wordpress.net/plugin-proxy";function ot(r){A=r}class at extends O{constructor(e,t){super(t),this.resource=e}get name(){return E(this.resource.slug)}getURL(){const e=$e(this.resource.slug);return`${A}?theme=`+e}}class ct extends O{constructor(e,t){super(t),this.resource=e}get name(){return E(this.resource.slug)}getURL(){const e=$e(this.resource.slug);return`${A}?plugin=`+e}}function $e(r){return!r||r.endsWith(".zip")?r:r+".latest-stable.zip"}class ve extends g{constructor(e){super(),this.resource=e}async resolve(){return this.resource.resolve()}async setPlayground(e){return this.resource.setPlayground(e)}get progress(){return this.resource.progress}set progress(e){this.resource.progress=e}get name(){return this.resource.name}get isAsync(){return this.resource.isAsync}}class lt extends ve{async resolve(){return this.promise||(this.promise=super.resolve()),this.promise}}class ut extends ve{constructor(e,t){super(e),this.semaphore=t}async resolve(){return this.isAsync?this.semaphore.run(()=>super.resolve()):super.resolve()}}const ht=["6.2","6.1","6.0","5.9"];function pt(r,{progress:e=new C,semaphore:t=new ce({concurrency:3}),onStepCompleted:s=()=>{}}={}){const n=(r.steps||[]).filter(dt),i=n.reduce((a,c)=>a+(c.progress?.weight||1),0),o=n.map(a=>ft(a,{semaphore:t,rootProgressTracker:e,totalProgressWeight:i}));return{versions:{php:V(r.preferredVersions?.php,be,Ae),wp:V(r.preferredVersions?.wp,ht,"6.2")},run:async a=>{try{for(const{resources:c}of o)for(const u of c)u.setPlayground(a),u.isAsync&&u.resolve();for(const{run:c,step:u}of o){const h=await c(a);s(h,u)}try{await a.goTo(r.landingPage||"/")}catch{}}finally{e.finish()}}}}function V(r,e,t){return r&&e.includes(r)?r:t}function dt(r){return!!(typeof r=="object"&&r)}function ft(r,{semaphore:e,rootProgressTracker:t,totalProgressWeight:s}){const n=t.stage((r.progress?.weight||1)/s),i={};for(const h of Object.keys(r)){let d=r[h];tt(d)&&(d=g.create(d,{semaphore:e})),i[h]=d}const o=async h=>{try{return n.fillSlowly(),await Ce[r.step](h,await mt(i),{tracker:n,initialCaption:r.progress?.caption})}finally{n.finish()}},a=J(i),c=J(i).filter(h=>h.isAsync),u=1/(c.length+1);for(const h of c)h.progress=n.stage(u);return{run:o,step:r,resources:a}}function J(r){const e=[];for(const t in r){const s=r[t];s instanceof g&&e.push(s)}return e}async function mt(r){const e={};for(const t in r){const s=r[t];s instanceof g?e[t]=await s.resolve():e[t]=s}return e}async function wt(r,e){await r.run(e)}exports.activatePlugin=K;exports.applyWordPressPatches=Y;exports.compileBlueprint=pt;exports.cp=te;exports.defineSiteUrl=ae;exports.defineWpConfigConsts=x;exports.importFile=he;exports.installPlugin=de;exports.installTheme=fe;exports.login=me;exports.mkdir=se;exports.mv=re;exports.replaceSite=ue;exports.request=ee;exports.rm=ne;exports.rmdir=ie;exports.runBlueprintSteps=wt;exports.runPHP=Z;exports.runPHPWithOptions=Q;exports.runWpInstallationWizard=we;exports.setPhpIniEntry=X;exports.setPluginProxyURL=ot;exports.setSiteOptions=ge;exports.unzip=k;exports.updateUserMeta=ye;exports.writeFile=oe;exports.zipEntireSite=le;
140
+ `;this[l].ccall("wasm_set_phpini_entries",null,[p],[e])}this[l].ccall("php_wasm_init",null,[],[])}#n(){const e="/tmp/headers.json";if(!this.fileExists(e))throw new Error("SAPI Error: Could not find response headers file.");const t=JSON.parse(this.readFileAsText(e)),s={};for(const n of t.headers){if(!n.includes(": "))continue;const i=n.indexOf(": "),o=n.substring(0,i).toLowerCase(),a=n.substring(i+2);o in s||(s[o]=[]),s[o].push(a)}return{headers:s,httpStatusCode:t.status}}#o(e){if(this[l].ccall("wasm_set_request_uri",null,[p],[e]),e.includes("?")){const t=e.substring(e.indexOf("?")+1);this[l].ccall("wasm_set_query_string",null,[p],[t])}}#a(e,t){this[l].ccall("wasm_set_request_host",null,[p],[e]);let s;try{s=parseInt(new URL(e).port,10)}catch{}(!s||isNaN(s)||s===80)&&(s=t==="https"?443:80),this[l].ccall("wasm_set_request_port",null,[P],[s]),(t==="https"||!t&&s===443)&&this.addServerGlobalEntry("HTTPS","on")}#c(e){this[l].ccall("wasm_set_request_method",null,[p],[e])}#l(e){e.cookie&&this[l].ccall("wasm_set_cookies",null,[p],[e.cookie]),e["content-type"]&&this[l].ccall("wasm_set_content_type",null,[p],[e["content-type"]]),e["content-length"]&&this[l].ccall("wasm_set_content_length",null,[P],[parseInt(e["content-length"],10)]);for(const t in e)this.addServerGlobalEntry(`HTTP_${t.toUpperCase().replace(/-/g,"_")}`,e[t])}#u(e){this[l].ccall("wasm_set_request_body",null,[p],[e]),this[l].ccall("wasm_set_content_length",null,[P],[new TextEncoder().encode(e).length])}#h(e){this[l].ccall("wasm_set_path_translated",null,[p],[e])}addServerGlobalEntry(e,t){this.#r[e]=t}#p(){for(const e in this.#r)this[l].ccall("wasm_add_SERVER_entry",null,[p,p],[e,this.#r[e]])}#d(e){const{key:t,name:s,type:n,data:i}=e,o=`/tmp/${Math.random().toFixed(20)}`;this.writeFile(o,i);const a=0;this[l].ccall("wasm_add_uploaded_file",null,[p,p,p,p,P,P],[t,s,n,o,a,i.byteLength])}#f(e){this[l].ccall("wasm_set_php_code",null,[p],[e])}async#m(){let e,t;try{e=await new Promise(async(i,o)=>{t=a=>{const c=new Error("Rethrown");c.cause=a.error,c.betterMessage=a.message,o(c)},this.#s?.addEventListener("error",t);try{i(await await this[l].ccall("wasm_sapi_handle_request",P,[],[]))}catch(a){o(a)}})}catch(i){for(const u in this)typeof this[u]=="function"&&(this[u]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=qe();const o=i,a="betterMessage"in o?o.betterMessage:o.message,c=new Error(a);throw c.cause=o,c}finally{this.#s?.removeEventListener("error",t),this.#r={}}const{headers:s,httpStatusCode:n}=this.#n();return new $(n,s,this.readFileAsBuffer("/tmp/stdout"),this.readFileAsText("/tmp/stderr"),e)}mkdir(e){this[l].FS.mkdirTree(e)}mkdirTree(e){this.mkdir(e)}readFileAsText(e){return new TextDecoder().decode(this.readFileAsBuffer(e))}readFileAsBuffer(e){return this[l].FS.readFile(e)}writeFile(e,t){this[l].FS.writeFile(e,t)}unlink(e){this[l].FS.unlink(e)}mv(e,t){this[l].FS.mv(e,t)}rmdir(e,t={recursive:!0}){t?.recursive&&this.listFiles(e).forEach(s=>{const n=`${e}/${s}`;this.isDir(n)?this.rmdir(n,t):this.unlink(n)}),this[l].FS.rmdir(e)}listFiles(e){if(!this.fileExists(e))return[];try{return this[l].FS.readdir(e).filter(t=>t!=="."&&t!=="..")}catch(t){return console.error(t,{path:e}),[]}}isDir(e){return this.fileExists(e)?this[l].FS.isDir(this[l].FS.lookupPath(e).node.mode):!1}fileExists(e){try{return this[l].FS.lookupPath(e),!0}catch{return!1}}}m([f('Could not create directory "{path}"')],w.prototype,"mkdir",1);m([f('Could not create directory "{path}"')],w.prototype,"mkdirTree",1);m([f('Could not read "{path}"')],w.prototype,"readFileAsText",1);m([f('Could not read "{path}"')],w.prototype,"readFileAsBuffer",1);m([f('Could not write to "{path}"')],w.prototype,"writeFile",1);m([f('Could not unlink "{path}"')],w.prototype,"unlink",1);m([f('Could not move "{path}"')],w.prototype,"mv",1);m([f('Could not remove directory "{path}"')],w.prototype,"rmdir",1);m([f('Could not list files in "{path}"')],w.prototype,"listFiles",1);m([f('Could not stat "{path}"')],w.prototype,"isDir",1);m([f('Could not stat "{path}"')],w.prototype,"fileExists",1);function Se(r){const e={};for(const t in r)e[t.toLowerCase()]=r[t];return e}const st=["vfs","literal","wordpress.org/themes","wordpress.org/plugins","url"];function nt(r){return r&&typeof r=="object"&&typeof r.resource=="string"&&st.includes(r.resource)}class y{static create(e,{semaphore:t,progress:s}){let n;switch(e.resource){case"vfs":n=new it(e,s);break;case"literal":n=new ot(e,s);break;case"wordpress.org/themes":n=new ut(e,s);break;case"wordpress.org/plugins":n=new ht(e,s);break;case"url":n=new ct(e,s);break;default:throw new Error(`Invalid resource: ${e}`)}return n=new pt(n),t&&(n=new dt(n,t)),n}setPlayground(e){this.playground=e}get isAsync(){return!1}}class it extends y{constructor(e,t){super(),this.resource=e,this.progress=t}async resolve(){const e=await this.playground.readFileAsBuffer(this.resource.path);return this.progress?.set(100),new File([e],this.name)}get name(){return this.resource.path}}class ot extends y{constructor(e,t){super(),this.resource=e,this.progress=t}async resolve(){return this.progress?.set(100),new File([this.resource.contents],this.resource.name)}get name(){return this.resource.name}}class O extends y{constructor(e){super(),this.progress=e}async resolve(){this.progress?.setCaption(this.caption);const e=this.getURL();let t=await fetch(e);if(t=await Le(t,this.progress?.loadingListener??at),t.status!==200)throw new Error(`Could not download "${e}"`);return new File([await t.blob()],this.name)}get caption(){return`Downloading ${this.name}`}get name(){try{return new URL(this.getURL(),"http://example.com").pathname.split("/").pop()}catch{return this.getURL()}}get isAsync(){return!0}}const at=()=>{};class ct extends O{constructor(e,t){super(t),this.resource=e}getURL(){return this.resource.url}get caption(){return this.resource.caption??super.caption}}let A="https://playground.wordpress.net/plugin-proxy";function lt(r){A=r}class ut extends O{constructor(e,t){super(t),this.resource=e}get name(){return E(this.resource.slug)}getURL(){const e=Ee(this.resource.slug);return`${A}?theme=`+e}}class ht extends O{constructor(e,t){super(t),this.resource=e}get name(){return E(this.resource.slug)}getURL(){const e=Ee(this.resource.slug);return`${A}?plugin=`+e}}function Ee(r){return!r||r.endsWith(".zip")?r:r+".latest-stable.zip"}class Re extends y{constructor(e){super(),this.resource=e}async resolve(){return this.resource.resolve()}async setPlayground(e){return this.resource.setPlayground(e)}get progress(){return this.resource.progress}set progress(e){this.resource.progress=e}get name(){return this.resource.name}get isAsync(){return this.resource.isAsync}}class pt extends Re{async resolve(){return this.promise||(this.promise=super.resolve()),this.promise}}class dt extends Re{constructor(e,t){super(e),this.semaphore=t}async resolve(){return this.isAsync?this.semaphore.run(()=>super.resolve()):super.resolve()}}const ft=["6.2","6.1","6.0","5.9"];function mt(r,{progress:e=new k,semaphore:t=new ue({concurrency:3}),onStepCompleted:s=()=>{}}={}){const n=(r.steps||[]).filter(wt),i=n.reduce((a,c)=>a+(c.progress?.weight||1),0),o=n.map(a=>gt(a,{semaphore:t,rootProgressTracker:e,totalProgressWeight:i}));return{versions:{php:K(r.preferredVersions?.php,ve,Ve),wp:K(r.preferredVersions?.wp,ft,"6.2")},run:async a=>{try{for(const{resources:c}of o)for(const u of c)u.setPlayground(a),u.isAsync&&u.resolve();for(const{run:c,step:u}of o){const h=await c(a);s(h,u)}try{await a.goTo(r.landingPage||"/")}catch{}}finally{e.finish()}}}}function K(r,e,t){return r&&e.includes(r)?r:t}function wt(r){return!!(typeof r=="object"&&r)}function gt(r,{semaphore:e,rootProgressTracker:t,totalProgressWeight:s}){const n=t.stage((r.progress?.weight||1)/s),i={};for(const h of Object.keys(r)){let d=r[h];nt(d)&&(d=y.create(d,{semaphore:e})),i[h]=d}const o=async h=>{try{return n.fillSlowly(),await Ae[r.step](h,await yt(i),{tracker:n,initialCaption:r.progress?.caption})}finally{n.finish()}},a=Y(i),c=Y(i).filter(h=>h.isAsync),u=1/(c.length+1);for(const h of c)h.progress=n.stage(u);return{run:o,step:r,resources:a}}function Y(r){const e=[];for(const t in r){const s=r[t];s instanceof y&&e.push(s)}return e}async function yt(r){const e={};for(const t in r){const s=r[t];s instanceof y?e[t]=await s.resolve():e[t]=s}return e}async function Pt(r,e){await r.run(e)}exports.activatePlugin=Z;exports.applyWordPressPatches=Q;exports.compileBlueprint=mt;exports.cp=se;exports.defineSiteUrl=le;exports.defineVirtualWpConfigConsts=$e;exports.defineWpConfigConsts=x;exports.importFile=de;exports.installPlugin=me;exports.installTheme=we;exports.login=ge;exports.mkdir=ie;exports.mv=ne;exports.replaceSite=pe;exports.request=re;exports.rm=oe;exports.rmdir=ae;exports.runBlueprintSteps=Pt;exports.runPHP=X;exports.runPHPWithOptions=ee;exports.runWpInstallationWizard=ye;exports.setPhpIniEntry=te;exports.setPluginProxyURL=lt;exports.setSiteOptions=Pe;exports.unzip=C;exports.updateUserMeta=_e;exports.writeFile=ce;exports.zipEntireSite=he;