@wp-playground/client 0.6.15 → 0.6.16
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 +5 -5
- package/index.js +32 -18
- package/package.json +2 -2
package/index.cjs
CHANGED
|
@@ -4,7 +4,7 @@ require_once( ${phpVar(s)}. "/wp-load.php" );
|
|
|
4
4
|
require_once( ${phpVar(s)}. "/wp-admin/includes/plugin.php" );
|
|
5
5
|
|
|
6
6
|
// Set current user to admin
|
|
7
|
-
|
|
7
|
+
wp_set_current_user( get_users(array('role' => 'Administrator') )[0]->ID );
|
|
8
8
|
|
|
9
9
|
$plugin_path = ${phpVar(t)};
|
|
10
10
|
|
|
@@ -28,7 +28,7 @@ define( 'WP_ADMIN', true );
|
|
|
28
28
|
require_once( ${phpVar(n)}. "/wp-load.php" );
|
|
29
29
|
|
|
30
30
|
// Set current user to admin
|
|
31
|
-
|
|
31
|
+
wp_set_current_user( get_users(array('role' => 'Administrator') )[0]->ID );
|
|
32
32
|
|
|
33
33
|
switch_theme( ${phpVar(t)} );
|
|
34
34
|
`})},runPHP=async(e,{code:t})=>await e.run({code:t}),runPHPWithOptions=async(e,{options:t})=>await e.run(t),rm=async(e,{path:t})=>{await e.unlink(t)},runSql=async(e,{sql:t},r)=>{r==null||r.tracker.setCaption("Executing SQL Queries");const n=`/tmp/${randomFilename()}.sql`;await e.writeFile(n,new Uint8Array(await t.arrayBuffer()));const s=await e.documentRoot,i=phpVars({docroot:s,sqlFilename:n}),o=await e.run({code:`<?php
|
|
@@ -404,7 +404,7 @@ define( 'WP_ADMIN', true );
|
|
|
404
404
|
require_once(${phpVar(s)} . "/wp-load.php");
|
|
405
405
|
|
|
406
406
|
// Set current user to admin
|
|
407
|
-
|
|
407
|
+
( get_users(array('role' => 'Administrator') )[0] );
|
|
408
408
|
|
|
409
409
|
require_once(${phpVar(s)} . "/wp-admin/includes/plugin.php");
|
|
410
410
|
$plugins_root = ${phpVar(s)} . "/wp-content/plugins";
|
|
@@ -605,7 +605,7 @@ ${bold} WASM ERROR${reset}${redBg}`);for(const t of e.split(`
|
|
|
605
605
|
`)),s.push(`\r
|
|
606
606
|
`),u instanceof File?s.push(await fileToUint8Array(u)):s.push(u),s.push(`\r
|
|
607
607
|
`);s.push(`--${t}--\r
|
|
608
|
-
`);const i=s.reduce((d,u)=>d+u.length,0),o=new Uint8Array(i);let c=0;for(const d of s)o.set(typeof d=="string"?n.encode(d):d,c),c+=d.length;return{bytes:o,contentType:r}}function fileToUint8Array(e){return new Promise(t=>{const r=new FileReader;r.onload=()=>{t(new Uint8Array(r.result))},r.readAsArrayBuffer(e)})}var Pe,Ke,dt,De,Je,ve,Qe,Fe,mt,zt,_t,Wt,gt,Bt;class PHPRequestHandler{constructor(t,r={}){Q(this,mt);Q(this,_t);Q(this,gt);Q(this,Pe,void 0);Q(this,Ke,void 0);Q(this,dt,void 0);Q(this,De,void 0);Q(this,Je,void 0);Q(this,ve,void 0);Q(this,Qe,void 0);Q(this,Fe,void 0);te(this,Fe,new Semaphore({concurrency:1}));const{documentRoot:n="/www/",absoluteUrl:s=typeof location=="object"?location==null?void 0:location.href:"",rewriteRules:i=[]}=r;this.php=t,te(this,Pe,n);const o=new URL(s);te(this,dt,o.hostname),te(this,De,o.port?Number(o.port):o.protocol==="https:"?443:80),te(this,Ke,(o.protocol||"").replace(":",""));const c=x(this,De)!==443&&x(this,De)!==80;te(this,Je,[x(this,dt),c?`:${x(this,De)}`:""].join("")),te(this,ve,o.pathname.replace(/\/+$/,"")),te(this,Qe,[`${x(this,Ke)}://`,x(this,Je),x(this,ve)].join("")),this.rewriteRules=i}pathToInternalUrl(t){return`${this.absoluteUrl}${t}`}internalUrlToPath(t){const r=new URL(t);return r.pathname.startsWith(x(this,ve))&&(r.pathname=r.pathname.slice(x(this,ve).length)),toRelativeUrl(r)}get isRequestRunning(){return x(this,Fe).running>0}get absoluteUrl(){return x(this,Qe)}get documentRoot(){return x(this,Pe)}async request(t){const r=t.url.startsWith("http://")||t.url.startsWith("https://"),n=new URL(t.url.split("#")[0],r?void 0:DEFAULT_BASE_URL),s=applyRewriteRules(removePathPrefix(decodeURIComponent(n.pathname),x(this,ve)),this.rewriteRules),i=joinPaths(x(this,Pe),s);return seemsLikeAPHPRequestHandlerPath(i)?await ce(this,_t,Wt).call(this,t,n):ce(this,mt,zt).call(this,i)}}Pe=new WeakMap,Ke=new WeakMap,dt=new WeakMap,De=new WeakMap,Je=new WeakMap,ve=new WeakMap,Qe=new WeakMap,Fe=new WeakMap,mt=new WeakSet,zt=function(t){if(!this.php.fileExists(t))return new PHPResponse(404,{"x-file-type":["static"]},new TextEncoder().encode("404 File not found"));const r=this.php.readFileAsBuffer(t);return new PHPResponse(200,{"content-length":[`${r.byteLength}`],"content-type":[inferMimeType(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},r)},_t=new WeakSet,Wt=async function(t,r){var s;if(x(this,Fe).running>0&&((s=t.headers)==null?void 0:s["x-request-issuer"])==="php")return console.warn("Possible deadlock: Called request() before the previous request() have finished. PHP likely issued an HTTP call to itself. Normally this would lead to infinite waiting as Request 1 holds the lock that the Request 2 is waiting to acquire. That's not useful, so PHPRequestHandler will return error 502 instead."),new PHPResponse(502,{},new TextEncoder().encode("502 Bad Gateway"));const n=await x(this,Fe).acquire();try{this.php.addServerGlobalEntry("REMOTE_ADDR","127.0.0.1"),this.php.addServerGlobalEntry("DOCUMENT_ROOT",x(this,Pe)),this.php.addServerGlobalEntry("HTTPS",x(this,Qe).startsWith("https://")?"on":"");let i="GET";const o={host:x(this,Je),...normalizeHeaders(t.headers||{})};let c=t.body;if(typeof c=="object"&&!(c instanceof Uint8Array)){i="POST";const{bytes:u,contentType:p}=await encodeAsMultipart(c);c=u,o["content-type"]=p}let d;try{d=ce(this,gt,Bt).call(this,decodeURIComponent(r.pathname))}catch{return new PHPResponse(404,{},new TextEncoder().encode("404 File not found"))}return await this.php.run({relativeUri:ensurePathPrefix(toRelativeUrl(r),x(this,ve)),protocol:x(this,Ke),method:t.method||i,body:c,scriptPath:d,headers:o})}finally{n()}},gt=new WeakSet,Bt=function(t){let r=removePathPrefix(t,x(this,ve));r=applyRewriteRules(r,this.rewriteRules),r.includes(".php")?r=r.split(".php")[0]+".php":this.php.isDir(`${x(this,Pe)}${r}`)?(r.endsWith("/")||(r=`${r}/`),r=`${r}index.php`):r="/index.php";const n=`${x(this,Pe)}${r}`;if(this.php.fileExists(n))return n;throw new Error(`File not found: ${n}`)};function inferMimeType(e){switch(e.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"}}function seemsLikeAPHPRequestHandlerPath(e){return seemsLikeAPHPFile(e)||seemsLikeADirectoryRoot(e)}function seemsLikeAPHPFile(e){return e.endsWith(".php")||e.includes(".php/")}function seemsLikeADirectoryRoot(e){return!e.split("/").pop().includes(".")}function applyRewriteRules(e,t){for(const r of t)if(new RegExp(r.match).test(e))return e.replace(r.match,r.replacement);return e}const FileErrorCodes={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 getEmscriptenFsError(e){const t=typeof e=="object"?e==null?void 0:e.errno:null;if(t in FileErrorCodes)return FileErrorCodes[t]}function rethrowFileSystemError(e=""){return function(r,n,s){const i=s.value;s.value=function(...o){try{return i.apply(this,o)}catch(c){const d=typeof c=="object"?c==null?void 0:c.errno:null;if(d in FileErrorCodes){const u=FileErrorCodes[d],p=typeof o[0]=="string"?o[0]:null,_=p!==null?e.replaceAll("{path}",p):e;throw new Error(`${_}: ${u}`,{cause:c})}throw c}}}}const loadedRuntimes=new Map;function getLoadedRuntime(e){return loadedRuntimes.get(e)}(function(){var e;return typeof process<"u"&&((e=process.release)==null?void 0:e.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(e,t,r,n)=>{for(var s=n>1?void 0:n?__getOwnPropDesc(t,r):t,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(n?o(t,r,s):o(s))||s);return n&&s&&__defProp(t,r,s),s};const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");var Me,Ze,Ye,Ee,Re,Te,be,Xe,yt,Gt,$t,Kt,vt,Jt,wt,Qt,Pt,Zt,Et,Yt,bt,Xt,St,er,Rt,tr,Tt,rr,kt,nr,Ct,sr;class BasePHP{constructor(e,t){Q(this,yt);Q(this,$t);Q(this,vt);Q(this,wt);Q(this,Pt);Q(this,Et);Q(this,bt);Q(this,St);Q(this,Rt);Q(this,Tt);Q(this,kt);Q(this,Ct);Q(this,Me,void 0);Q(this,Ze,void 0);Q(this,Ye,void 0);Q(this,Ee,void 0);Q(this,Re,void 0);Q(this,Te,void 0);Q(this,be,void 0);Q(this,Xe,void 0);te(this,Me,[]),te(this,Ee,!1),te(this,Re,null),te(this,Te,{}),te(this,be,new Map),te(this,Xe,[]),this.semaphore=new Semaphore({concurrency:1}),e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new PHPBrowser(new PHPRequestHandler(this,t)))}addEventListener(e,t){x(this,be).has(e)||x(this,be).set(e,new Set),x(this,be).get(e).add(t)}removeEventListener(e,t){var r;(r=x(this,be).get(e))==null||r.delete(t)}dispatchEvent(e){const t=x(this,be).get(e.type);if(t)for(const r of t)r(e)}async onMessage(e){x(this,Xe).push(e)}async setSpawnHandler(handler){typeof handler=="string"&&(handler=createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}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[__private__dont__use])throw new Error("PHP runtime already initialized.");const t=getLoadedRuntime(e);if(!t)throw new Error("Invalid PHP runtime id.");this[__private__dont__use]=t,t.onMessage=async r=>{for(const n of x(this,Xe)){const s=await n(r);if(s)return s}return""},te(this,Re,improveWASMErrorReporting(t)),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(e){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[e])!==0)throw new Error("Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?");te(this,Ye,e)}setPhpIniPath(e){if(x(this,Ee))throw new Error("Cannot set PHP ini path after calling run().");te(this,Ze,e),this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[e])}setPhpIniEntry(e,t){if(x(this,Ee))throw new Error("Cannot set PHP ini entries after calling run().");x(this,Me).push([e,t])}chdir(e){this[__private__dont__use].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){const t=await this.semaphore.acquire();let r;try{if(x(this,Ee)||(ce(this,yt,Gt).call(this),te(this,Ee,!0)),e.scriptPath&&!this.fileExists(e.scriptPath))throw new Error(`The script path "${e.scriptPath}" does not exist.`);ce(this,St,er).call(this,e.scriptPath||""),ce(this,vt,Jt).call(this,e.relativeUri||""),ce(this,Pt,Zt).call(this,e.method||"GET");const n=normalizeHeaders(e.headers||{}),s=n.host||"example.com:443";ce(this,wt,Qt).call(this,s,e.protocol||"http"),ce(this,Et,Yt).call(this,n),e.body&&(r=ce(this,bt,Xt).call(this,e.body)),typeof e.code=="string"&&ce(this,kt,nr).call(this," ?>"+e.code),ce(this,Rt,tr).call(this);const i=e.env||{};for(const c in i)ce(this,Tt,rr).call(this,c,i[c]);const o=await ce(this,Ct,sr).call(this);if(o.exitCode!==0){console.warn("PHP.run() output was:",o.text);const c=new Error(`PHP.run() failed with exit code ${o.exitCode} and the following output: `+o.errors);throw c.response=o,c.source="request",console.error(c),c}return o}catch(n){throw this.dispatchEvent({type:"request.error",error:n,source:n.source??"php-wasm"}),n}finally{try{r&&this[__private__dont__use].free(r)}finally{t(),this.dispatchEvent({type:"request.end"})}}}addServerGlobalEntry(e,t){x(this,Te)[e]=t}defineConstant(e,t){let r={};try{r=JSON.parse(this.fileExists("/internal/consts.json")&&this.readFileAsText("/internal/consts.json")||"{}")}catch{}this.writeFile("/internal/consts.json",JSON.stringify({...r,[e]:t}))}mkdir(e){this[__private__dont__use].FS.mkdirTree(e)}mkdirTree(e){this.mkdir(e)}readFileAsText(e){return new TextDecoder().decode(this.readFileAsBuffer(e))}readFileAsBuffer(e){return this[__private__dont__use].FS.readFile(e)}writeFile(e,t){this[__private__dont__use].FS.writeFile(e,t)}unlink(e){this[__private__dont__use].FS.unlink(e)}mv(e,t){try{this[__private__dont__use].FS.rename(e,t)}catch(r){const n=getEmscriptenFsError(r);throw n?new Error(`Could not move ${e} to ${t}: ${n}`,{cause:r}):r}}rmdir(e,t={recursive:!0}){t!=null&&t.recursive&&this.listFiles(e).forEach(r=>{const n=`${e}/${r}`;this.isDir(n)?this.rmdir(n,t):this.unlink(n)}),this[__private__dont__use].FS.rmdir(e)}listFiles(e,t={prependPath:!1}){if(!this.fileExists(e))return[];try{const r=this[__private__dont__use].FS.readdir(e).filter(n=>n!=="."&&n!=="..");if(t.prependPath){const n=e.replace(/\/$/,"");return r.map(s=>`${n}/${s}`)}return r}catch(r){return console.error(r,{path:e}),[]}}isDir(e){return this.fileExists(e)?this[__private__dont__use].FS.isDir(this[__private__dont__use].FS.lookupPath(e).node.mode):!1}fileExists(e){try{return this[__private__dont__use].FS.lookupPath(e),!0}catch{return!1}}hotSwapPHPRuntime(e){const t=this[__private__dont__use].FS;try{this.exit()}catch{}if(this.initializeRuntime(e),x(this,Ze)&&this.setPhpIniPath(x(this,Ze)),x(this,Ye)&&this.setSapiName(x(this,Ye)),this.requestHandler){const r=this.documentRoot;copyFS(t,this[__private__dont__use].FS,r)}}exit(e=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(e)}catch{}te(this,Ee,!1),te(this,Re,null),delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}}Me=new WeakMap,Ze=new WeakMap,Ye=new WeakMap,Ee=new WeakMap,Re=new WeakMap,Te=new WeakMap,be=new WeakMap,Xe=new WeakMap,yt=new WeakSet,Gt=function(){if(this.setPhpIniEntry("auto_prepend_file","/internal/consts.php"),this.fileExists("/internal/consts.php")||this.writeFile("/internal/consts.php",`<?php
|
|
608
|
+
`);const i=s.reduce((d,u)=>d+u.length,0),o=new Uint8Array(i);let c=0;for(const d of s)o.set(typeof d=="string"?n.encode(d):d,c),c+=d.length;return{bytes:o,contentType:r}}function fileToUint8Array(e){return new Promise(t=>{const r=new FileReader;r.onload=()=>{t(new Uint8Array(r.result))},r.readAsArrayBuffer(e)})}var Pe,Ke,dt,De,Je,ve,Qe,Fe,mt,zt,_t,Wt,gt,Bt;class PHPRequestHandler{constructor(t,r={}){Q(this,mt);Q(this,_t);Q(this,gt);Q(this,Pe,void 0);Q(this,Ke,void 0);Q(this,dt,void 0);Q(this,De,void 0);Q(this,Je,void 0);Q(this,ve,void 0);Q(this,Qe,void 0);Q(this,Fe,void 0);te(this,Fe,new Semaphore({concurrency:1}));const{documentRoot:n="/www/",absoluteUrl:s=typeof location=="object"?location==null?void 0:location.href:"",rewriteRules:i=[]}=r;this.php=t,te(this,Pe,n);const o=new URL(s);te(this,dt,o.hostname),te(this,De,o.port?Number(o.port):o.protocol==="https:"?443:80),te(this,Ke,(o.protocol||"").replace(":",""));const c=x(this,De)!==443&&x(this,De)!==80;te(this,Je,[x(this,dt),c?`:${x(this,De)}`:""].join("")),te(this,ve,o.pathname.replace(/\/+$/,"")),te(this,Qe,[`${x(this,Ke)}://`,x(this,Je),x(this,ve)].join("")),this.rewriteRules=i}pathToInternalUrl(t){return`${this.absoluteUrl}${t}`}internalUrlToPath(t){const r=new URL(t);return r.pathname.startsWith(x(this,ve))&&(r.pathname=r.pathname.slice(x(this,ve).length)),toRelativeUrl(r)}get isRequestRunning(){return x(this,Fe).running>0}get absoluteUrl(){return x(this,Qe)}get documentRoot(){return x(this,Pe)}async request(t){const r=t.url.startsWith("http://")||t.url.startsWith("https://"),n=new URL(t.url.split("#")[0],r?void 0:DEFAULT_BASE_URL),s=applyRewriteRules(removePathPrefix(decodeURIComponent(n.pathname),x(this,ve)),this.rewriteRules),i=joinPaths(x(this,Pe),s);return seemsLikeAPHPRequestHandlerPath(i)?await ce(this,_t,Wt).call(this,t,n):ce(this,mt,zt).call(this,i)}}Pe=new WeakMap,Ke=new WeakMap,dt=new WeakMap,De=new WeakMap,Je=new WeakMap,ve=new WeakMap,Qe=new WeakMap,Fe=new WeakMap,mt=new WeakSet,zt=function(t){if(!this.php.fileExists(t))return new PHPResponse(404,{"x-file-type":["static"]},new TextEncoder().encode("404 File not found"));const r=this.php.readFileAsBuffer(t);return new PHPResponse(200,{"content-length":[`${r.byteLength}`],"content-type":[inferMimeType(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},r)},_t=new WeakSet,Wt=async function(t,r){var s;if(x(this,Fe).running>0&&((s=t.headers)==null?void 0:s["x-request-issuer"])==="php")return console.warn("Possible deadlock: Called request() before the previous request() have finished. PHP likely issued an HTTP call to itself. Normally this would lead to infinite waiting as Request 1 holds the lock that the Request 2 is waiting to acquire. That's not useful, so PHPRequestHandler will return error 502 instead."),new PHPResponse(502,{},new TextEncoder().encode("502 Bad Gateway"));const n=await x(this,Fe).acquire();try{this.php.addServerGlobalEntry("REMOTE_ADDR","127.0.0.1"),this.php.addServerGlobalEntry("DOCUMENT_ROOT",x(this,Pe)),this.php.addServerGlobalEntry("HTTPS",x(this,Qe).startsWith("https://")?"on":"");let i="GET";const o={host:x(this,Je),...normalizeHeaders(t.headers||{})};let c=t.body;if(typeof c=="object"&&!(c instanceof Uint8Array)){i="POST";const{bytes:u,contentType:p}=await encodeAsMultipart(c);c=u,o["content-type"]=p}let d;try{d=ce(this,gt,Bt).call(this,decodeURIComponent(r.pathname))}catch{return new PHPResponse(404,{},new TextEncoder().encode("404 File not found"))}try{return await this.php.run({relativeUri:ensurePathPrefix(toRelativeUrl(r),x(this,ve)),protocol:x(this,Ke),method:t.method||i,body:c,scriptPath:d,headers:o})}catch(u){const p=u;if(p!=null&&p.response)return p.response;throw u}}finally{n()}},gt=new WeakSet,Bt=function(t){let r=removePathPrefix(t,x(this,ve));r=applyRewriteRules(r,this.rewriteRules),r.includes(".php")?r=r.split(".php")[0]+".php":this.php.isDir(`${x(this,Pe)}${r}`)?(r.endsWith("/")||(r=`${r}/`),r=`${r}index.php`):r="/index.php";const n=`${x(this,Pe)}${r}`;if(this.php.fileExists(n))return n;throw new Error(`File not found: ${n}`)};function inferMimeType(e){switch(e.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"}}function seemsLikeAPHPRequestHandlerPath(e){return seemsLikeAPHPFile(e)||seemsLikeADirectoryRoot(e)}function seemsLikeAPHPFile(e){return e.endsWith(".php")||e.includes(".php/")}function seemsLikeADirectoryRoot(e){return!e.split("/").pop().includes(".")}function applyRewriteRules(e,t){for(const r of t)if(new RegExp(r.match).test(e))return e.replace(r.match,r.replacement);return e}const FileErrorCodes={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 getEmscriptenFsError(e){const t=typeof e=="object"?e==null?void 0:e.errno:null;if(t in FileErrorCodes)return FileErrorCodes[t]}function rethrowFileSystemError(e=""){return function(r,n,s){const i=s.value;s.value=function(...o){try{return i.apply(this,o)}catch(c){const d=typeof c=="object"?c==null?void 0:c.errno:null;if(d in FileErrorCodes){const u=FileErrorCodes[d],p=typeof o[0]=="string"?o[0]:null,_=p!==null?e.replaceAll("{path}",p):e;throw new Error(`${_}: ${u}`,{cause:c})}throw c}}}}const loadedRuntimes=new Map;function getLoadedRuntime(e){return loadedRuntimes.get(e)}(function(){var e;return typeof process<"u"&&((e=process.release)==null?void 0:e.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(e,t,r,n)=>{for(var s=n>1?void 0:n?__getOwnPropDesc(t,r):t,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(n?o(t,r,s):o(s))||s);return n&&s&&__defProp(t,r,s),s};const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(t,r,n){super(t),this.response=r,this.source=n}}var Me,Ze,Ye,Ee,Re,Te,be,Xe,yt,Gt,$t,Kt,vt,Jt,wt,Qt,Pt,Zt,Et,Yt,bt,Xt,St,er,Rt,tr,Tt,rr,kt,nr,Ct,sr;class BasePHP{constructor(e,t){Q(this,yt);Q(this,$t);Q(this,vt);Q(this,wt);Q(this,Pt);Q(this,Et);Q(this,bt);Q(this,St);Q(this,Rt);Q(this,Tt);Q(this,kt);Q(this,Ct);Q(this,Me,void 0);Q(this,Ze,void 0);Q(this,Ye,void 0);Q(this,Ee,void 0);Q(this,Re,void 0);Q(this,Te,void 0);Q(this,be,void 0);Q(this,Xe,void 0);te(this,Me,[]),te(this,Ee,!1),te(this,Re,null),te(this,Te,{}),te(this,be,new Map),te(this,Xe,[]),this.semaphore=new Semaphore({concurrency:1}),e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new PHPBrowser(new PHPRequestHandler(this,t)))}addEventListener(e,t){x(this,be).has(e)||x(this,be).set(e,new Set),x(this,be).get(e).add(t)}removeEventListener(e,t){var r;(r=x(this,be).get(e))==null||r.delete(t)}dispatchEvent(e){const t=x(this,be).get(e.type);if(t)for(const r of t)r(e)}async onMessage(e){x(this,Xe).push(e)}async setSpawnHandler(handler){typeof handler=="string"&&(handler=createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}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[__private__dont__use])throw new Error("PHP runtime already initialized.");const t=getLoadedRuntime(e);if(!t)throw new Error("Invalid PHP runtime id.");this[__private__dont__use]=t,t.onMessage=async r=>{for(const n of x(this,Xe)){const s=await n(r);if(s)return s}return""},te(this,Re,improveWASMErrorReporting(t)),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(e){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[e])!==0)throw new Error("Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?");te(this,Ye,e)}setPhpIniPath(e){if(x(this,Ee))throw new Error("Cannot set PHP ini path after calling run().");te(this,Ze,e),this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[e])}setPhpIniEntry(e,t){if(x(this,Ee))throw new Error("Cannot set PHP ini entries after calling run().");x(this,Me).push([e,t])}chdir(e){this[__private__dont__use].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){const t=await this.semaphore.acquire();let r;try{if(x(this,Ee)||(ce(this,yt,Gt).call(this),te(this,Ee,!0)),e.scriptPath&&!this.fileExists(e.scriptPath))throw new Error(`The script path "${e.scriptPath}" does not exist.`);ce(this,St,er).call(this,e.scriptPath||""),ce(this,vt,Jt).call(this,e.relativeUri||""),ce(this,Pt,Zt).call(this,e.method||"GET");const n=normalizeHeaders(e.headers||{}),s=n.host||"example.com:443";ce(this,wt,Qt).call(this,s,e.protocol||"http"),ce(this,Et,Yt).call(this,n),e.body&&(r=ce(this,bt,Xt).call(this,e.body)),typeof e.code=="string"&&ce(this,kt,nr).call(this," ?>"+e.code),ce(this,Rt,tr).call(this);const i=e.env||{};for(const c in i)ce(this,Tt,rr).call(this,c,i[c]);const o=await ce(this,Ct,sr).call(this);if(o.exitCode!==0){console.warn("PHP.run() output was:",o.text);const c=new PHPExecutionFailureError(`PHP.run() failed with exit code ${o.exitCode} and the following output: `+o.errors,o,"request");throw console.error(c),c}return o}catch(n){throw this.dispatchEvent({type:"request.error",error:n,source:n.source??"php-wasm"}),n}finally{try{r&&this[__private__dont__use].free(r)}finally{t(),this.dispatchEvent({type:"request.end"})}}}addServerGlobalEntry(e,t){x(this,Te)[e]=t}defineConstant(e,t){let r={};try{r=JSON.parse(this.fileExists("/internal/consts.json")&&this.readFileAsText("/internal/consts.json")||"{}")}catch{}this.writeFile("/internal/consts.json",JSON.stringify({...r,[e]:t}))}mkdir(e){this[__private__dont__use].FS.mkdirTree(e)}mkdirTree(e){this.mkdir(e)}readFileAsText(e){return new TextDecoder().decode(this.readFileAsBuffer(e))}readFileAsBuffer(e){return this[__private__dont__use].FS.readFile(e)}writeFile(e,t){this[__private__dont__use].FS.writeFile(e,t)}unlink(e){this[__private__dont__use].FS.unlink(e)}mv(e,t){try{this[__private__dont__use].FS.rename(e,t)}catch(r){const n=getEmscriptenFsError(r);throw n?new Error(`Could not move ${e} to ${t}: ${n}`,{cause:r}):r}}rmdir(e,t={recursive:!0}){t!=null&&t.recursive&&this.listFiles(e).forEach(r=>{const n=`${e}/${r}`;this.isDir(n)?this.rmdir(n,t):this.unlink(n)}),this[__private__dont__use].FS.rmdir(e)}listFiles(e,t={prependPath:!1}){if(!this.fileExists(e))return[];try{const r=this[__private__dont__use].FS.readdir(e).filter(n=>n!=="."&&n!=="..");if(t.prependPath){const n=e.replace(/\/$/,"");return r.map(s=>`${n}/${s}`)}return r}catch(r){return console.error(r,{path:e}),[]}}isDir(e){return this.fileExists(e)?this[__private__dont__use].FS.isDir(this[__private__dont__use].FS.lookupPath(e).node.mode):!1}fileExists(e){try{return this[__private__dont__use].FS.lookupPath(e),!0}catch{return!1}}hotSwapPHPRuntime(e){const t=this[__private__dont__use].FS;try{this.exit()}catch{}if(this.initializeRuntime(e),x(this,Ze)&&this.setPhpIniPath(x(this,Ze)),x(this,Ye)&&this.setSapiName(x(this,Ye)),this.requestHandler){const r=this.documentRoot;copyFS(t,this[__private__dont__use].FS,r)}}exit(e=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(e)}catch{}te(this,Ee,!1),te(this,Re,null),delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}}Me=new WeakMap,Ze=new WeakMap,Ye=new WeakMap,Ee=new WeakMap,Re=new WeakMap,Te=new WeakMap,be=new WeakMap,Xe=new WeakMap,yt=new WeakSet,Gt=function(){if(this.setPhpIniEntry("auto_prepend_file","/internal/consts.php"),this.fileExists("/internal/consts.php")||this.writeFile("/internal/consts.php",`<?php
|
|
609
609
|
if(file_exists('/internal/consts.json')) {
|
|
610
610
|
$consts = json_decode(file_get_contents('/internal/consts.json'), true);
|
|
611
611
|
foreach ($consts as $const => $value) {
|
|
@@ -616,7 +616,7 @@ ${bold} WASM ERROR${reset}${redBg}`);for(const t of e.split(`
|
|
|
616
616
|
}`),x(this,Me).length>0){const e=x(this,Me).map(([t,r])=>`${t}=${r}`).join(`
|
|
617
617
|
`)+`
|
|
618
618
|
|
|
619
|
-
`;this[__private__dont__use].ccall("wasm_set_phpini_entries",null,[STRING],[e])}this[__private__dont__use].ccall("php_wasm_init",null,[],[])},$t=new WeakSet,Kt=function(){const e="/internal/headers.json";if(!this.fileExists(e))throw new Error("SAPI Error: Could not find response headers file.");const t=JSON.parse(this.readFileAsText(e)),r={};for(const n of t.headers){if(!n.includes(": "))continue;const s=n.indexOf(": "),i=n.substring(0,s).toLowerCase(),o=n.substring(s+2);i in r||(r[i]=[]),r[i].push(o)}return{headers:r,httpStatusCode:t.status}},vt=new WeakSet,Jt=function(e){if(this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[e]),e.includes("?")){const t=e.substring(e.indexOf("?")+1);this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[t])}},wt=new WeakSet,Qt=function(e,t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[e]);let r;try{r=parseInt(new URL(e).port,10)}catch{}(!r||isNaN(r)||r===80)&&(r=t==="https"?443:80),this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[r]),(t==="https"||!t&&r===443)&&this.addServerGlobalEntry("HTTPS","on")},Pt=new WeakSet,Zt=function(e){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[e])},Et=new WeakSet,Yt=function(e){e.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[e.cookie]),e["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[e["content-type"]]),e["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(e["content-length"],10)]);for(const t in e){let r="HTTP_";["content-type","content-length"].includes(t.toLowerCase())&&(r=""),this.addServerGlobalEntry(`${r}${t.toUpperCase().replace(/-/g,"_")}`,e[t])}},bt=new WeakSet,Xt=function(e){let t,r;typeof e=="string"?(console.warn("Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"),r=this[__private__dont__use].lengthBytesUTF8(e),t=r+1):(r=e.byteLength,t=e.byteLength);const n=this[__private__dont__use].malloc(t);if(!n)throw new Error("Could not allocate memory for the request body.");return typeof e=="string"?this[__private__dont__use].stringToUTF8(e,n,t+1):this[__private__dont__use].HEAPU8.set(e,n),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[n]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[r]),n},St=new WeakSet,er=function(e){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[e])},Rt=new WeakSet,tr=function(){for(const e in x(this,Te))this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[e,x(this,Te)[e]])},Tt=new WeakSet,rr=function(e,t){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[e,t])},kt=new WeakSet,nr=function(e){this[__private__dont__use].ccall("wasm_set_php_code",null,[STRING],[e])},Ct=new WeakSet,sr=async function(){var s;let e,t;try{e=await new Promise((i,o)=>{var d;t=u=>{console.error(u),console.error(u.error);const p=new Error("Rethrown");p.cause=u.error,p.betterMessage=u.message,o(p)},(d=x(this,Re))==null||d.addEventListener("error",t);const c=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return c instanceof Promise?c.then(i,o):i(c)})}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=getFunctionsMaybeMissingFromAsyncify();const o=i,c="betterMessage"in o?o.betterMessage:o.message,d=new Error(c);throw d.cause=o,console.error(d),d}finally{(s=x(this,Re))==null||s.removeEventListener("error",t),te(this,Te,{})}const{headers:r,httpStatusCode:n}=ce(this,$t,Kt).call(this);return new PHPResponse(n,r,this.readFileAsBuffer("/internal/stdout"),this.readFileAsText("/internal/stderr"),e)};__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],BasePHP.prototype,"mkdir",1);__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],BasePHP.prototype,"mkdirTree",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],BasePHP.prototype,"readFileAsText",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],BasePHP.prototype,"readFileAsBuffer",1);__decorateClass([rethrowFileSystemError('Could not write to "{path}"')],BasePHP.prototype,"writeFile",1);__decorateClass([rethrowFileSystemError('Could not unlink "{path}"')],BasePHP.prototype,"unlink",1);__decorateClass([rethrowFileSystemError('Could not remove directory "{path}"')],BasePHP.prototype,"rmdir",1);__decorateClass([rethrowFileSystemError('Could not list files in "{path}"')],BasePHP.prototype,"listFiles",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],BasePHP.prototype,"isDir",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],BasePHP.prototype,"fileExists",1);function normalizeHeaders(e){const t={};for(const r in e)t[r.toLowerCase()]=e[r];return t}function copyFS(e,t,r){let n;try{n=e.lookupPath(r)}catch{return}if(!("contents"in n.node))return;if(!e.isDir(n.node.mode)){t.writeFile(r,e.readFile(r));return}t.mkdirTree(r);const s=e.readdir(r).filter(i=>i!=="."&&i!=="..");for(const i of s)copyFS(e,t,joinPaths(r,i))}const ResourceTypes=["vfs","literal","wordpress.org/themes","wordpress.org/plugins","url"];function isFileReference(e){return e&&typeof e=="object"&&typeof e.resource=="string"&&ResourceTypes.includes(e.resource)}class Resource{static create(t,{semaphore:r,progress:n}){let s;switch(t.resource){case"vfs":s=new VFSResource(t,n);break;case"literal":s=new LiteralResource(t,n);break;case"wordpress.org/themes":s=new CoreThemeResource(t,n);break;case"wordpress.org/plugins":s=new CorePluginResource(t,n);break;case"url":s=new UrlResource(t,n);break;default:throw new Error(`Invalid resource: ${t}`)}return s=new CachedResource(s),r&&(s=new SemaphoreResource(s,r)),s}setPlayground(t){this.playground=t}get isAsync(){return!1}}class VFSResource extends Resource{constructor(t,r){super(),this.resource=t,this.progress=r}async resolve(){var r;const t=await this.playground.readFileAsBuffer(this.resource.path);return(r=this.progress)==null||r.set(100),new File([t],this.name)}get name(){return this.resource.path.split("/").pop()||""}}class LiteralResource extends Resource{constructor(t,r){super(),this.resource=t,this.progress=r}async resolve(){var t;return(t=this.progress)==null||t.set(100),new File([this.resource.contents],this.resource.name)}get name(){return this.resource.name}}class FetchResource extends Resource{constructor(t){super(),this.progress=t}async resolve(){var n,s;(n=this.progress)==null||n.setCaption(this.caption);const t=this.getURL();let r=await fetch(t);if(r=await cloneResponseMonitorProgress(r,((s=this.progress)==null?void 0:s.loadingListener)??noop),r.status!==200)throw new Error(`Could not download "${t}"`);return new File([await r.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 noop=()=>{};class UrlResource extends FetchResource{constructor(t,r){super(r),this.resource=t}getURL(){return this.resource.url}get caption(){return this.resource.caption??super.caption}}class CoreThemeResource extends FetchResource{constructor(t,r){super(r),this.resource=t}get name(){return zipNameToHumanName(this.resource.slug)}getURL(){return`https://downloads.wordpress.org/theme/${toDirectoryZipName(this.resource.slug)}`}}class CorePluginResource extends FetchResource{constructor(t,r){super(r),this.resource=t}get name(){return zipNameToHumanName(this.resource.slug)}getURL(){return`https://downloads.wordpress.org/plugin/${toDirectoryZipName(this.resource.slug)}`}}function toDirectoryZipName(e){return!e||e.endsWith(".zip")?e:e+".latest-stable.zip"}class DecoratedResource extends Resource{constructor(t){super(),this.resource=t}async resolve(){return this.resource.resolve()}async setPlayground(t){return this.resource.setPlayground(t)}get progress(){return this.resource.progress}set progress(t){this.resource.progress=t}get name(){return this.resource.name}get isAsync(){return this.resource.isAsync}}class CachedResource extends DecoratedResource{async resolve(){return this.promise||(this.promise=super.resolve()),this.promise}}class SemaphoreResource extends DecoratedResource{constructor(t,r){super(t),this.semaphore=r}async resolve(){return this.isAsync?this.semaphore.run(()=>super.resolve()):super.resolve()}}var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ajv$1={exports:{}},core$2={},validate={},boolSchema={},errors={},codegen={},code$1={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(y){if(super(),!e.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((P,I)=>`${P}${I}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((P,I)=>(I instanceof r&&(P[I.str]=(P[I.str]||0)+1),P),{})}}e._Code=n,e.nil=new n("");function s(g,...y){const P=[g[0]];let I=0;for(;I<y.length;)c(P,y[I]),P.push(g[++I]);return new n(P)}e._=s;const i=new n("+");function o(g,...y){const P=[C(g[0])];let I=0;for(;I<y.length;)P.push(i),c(P,y[I]),P.push(i,C(g[++I]));return d(P),new n(P)}e.str=o;function c(g,y){y instanceof n?g.push(...y._items):y instanceof r?g.push(y):g.push(_(y))}e.addCodeArg=c;function d(g){let y=1;for(;y<g.length-1;){if(g[y]===i){const P=u(g[y-1],g[y+1]);if(P!==void 0){g.splice(y-1,3,P);continue}g[y++]="+"}y++}}function u(g,y){if(y==='""')return g;if(g==='""')return y;if(typeof g=="string")return y instanceof r||g[g.length-1]!=='"'?void 0:typeof y!="string"?`${g.slice(0,-1)}${y}"`:y[0]==='"'?g.slice(0,-1)+y.slice(1):void 0;if(typeof y=="string"&&y[0]==='"'&&!(g instanceof r))return`"${g}${y.slice(1)}`}function p(g,y){return y.emptyStr()?g:g.emptyStr()?y:o`${g}${y}`}e.strConcat=p;function _(g){return typeof g=="number"||typeof g=="boolean"||g===null?g:C(Array.isArray(g)?g.join(","):g)}function T(g){return new n(C(g))}e.stringify=T;function C(g){return JSON.stringify(g).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=C;function S(g){return typeof g=="string"&&e.IDENTIFIER.test(g)?new n(`.${g}`):s`[${g}]`}e.getProperty=S;function k(g){if(typeof g=="string"&&e.IDENTIFIER.test(g))return new n(`${g}`);throw new Error(`CodeGen: invalid export name: ${g}, use explicit $id name mapping`)}e.getEsmExportName=k;function $(g){return new n(g.toString())}e.regexpCode=$})(code$1);var scope={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=code$1;class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var n;(function(d){d[d.Started=0]="Started",d[d.Completed=1]="Completed"})(n=e.UsedValueState||(e.UsedValueState={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class s{constructor({prefixes:u,parent:p}={}){this._names={},this._prefixes=u,this._parent=p}toName(u){return u instanceof t.Name?u:this.name(u)}name(u){return new t.Name(this._newName(u))}_newName(u){const p=this._names[u]||this._nameGroup(u);return`${u}${p.index++}`}_nameGroup(u){var p,_;if(!((_=(p=this._parent)===null||p===void 0?void 0:p._prefixes)===null||_===void 0)&&_.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}e.Scope=s;class i extends t.Name{constructor(u,p){super(p),this.prefix=u}setValue(u,{property:p,itemIndex:_}){this.value=u,this.scopePath=(0,t._)`.${new t.Name(p)}[${_}]`}}e.ValueScopeName=i;const o=(0,t._)`\n`;class c extends s{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?o:t.nil}}get(){return this._scope}name(u){return new i(u,this._newName(u))}value(u,p){var _;if(p.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const T=this.toName(u),{prefix:C}=T,S=(_=p.key)!==null&&_!==void 0?_:p.ref;let k=this._values[C];if(k){const y=k.get(S);if(y)return y}else k=this._values[C]=new Map;k.set(S,T);const $=this._scope[C]||(this._scope[C]=[]),g=$.length;return $[g]=p.ref,T.setValue(p,{property:C,itemIndex:g}),T}getValue(u,p){const _=this._values[u];if(_)return _.get(p)}scopeRefs(u,p=this._values){return this._reduceValues(p,_=>{if(_.scopePath===void 0)throw new Error(`CodeGen: name "${_}" has no value`);return(0,t._)`${u}${_.scopePath}`})}scopeCode(u=this._values,p,_){return this._reduceValues(u,T=>{if(T.value===void 0)throw new Error(`CodeGen: name "${T}" has no value`);return T.value.code},p,_)}_reduceValues(u,p,_={},T){let C=t.nil;for(const S in u){const k=u[S];if(!k)continue;const $=_[S]=_[S]||new Map;k.forEach(g=>{if($.has(g))return;$.set(g,n.Started);let y=p(g);if(y){const P=this.opts.es5?e.varKinds.var:e.varKinds.const;C=(0,t._)`${C}${P} ${g} = ${y};${this.opts._n}`}else if(y=T==null?void 0:T(g))C=(0,t._)`${C}${y}${this.opts._n}`;else throw new r(g);$.set(g,n.Completed)})}return C}}e.ValueScope=c})(scope);(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=code$1,r=scope;var n=code$1;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var s=scope;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class i{optimizeNodes(){return this}optimizeNames(a,h){return this}}class o extends i{constructor(a,h,N){super(),this.varKind=a,this.name=h,this.rhs=N}render({es5:a,_n:h}){const N=a?r.varKinds.var:this.varKind,M=this.rhs===void 0?"":` = ${this.rhs}`;return`${N} ${this.name}${M};`+h}optimizeNames(a,h){if(a[this.name.str])return this.rhs&&(this.rhs=oe(this.rhs,a,h)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class c extends i{constructor(a,h,N){super(),this.lhs=a,this.rhs=h,this.sideEffects=N}render({_n:a}){return`${this.lhs} = ${this.rhs};`+a}optimizeNames(a,h){if(!(this.lhs instanceof t.Name&&!a[this.lhs.str]&&!this.sideEffects))return this.rhs=oe(this.rhs,a,h),this}get names(){const a=this.lhs instanceof t.Name?{}:{...this.lhs.names};return ue(a,this.rhs)}}class d extends c{constructor(a,h,N,M){super(a,N,M),this.op=h}render({_n:a}){return`${this.lhs} ${this.op}= ${this.rhs};`+a}}class u extends i{constructor(a){super(),this.label=a,this.names={}}render({_n:a}){return`${this.label}:`+a}}class p extends i{constructor(a){super(),this.label=a,this.names={}}render({_n:a}){return`break${this.label?` ${this.label}`:""};`+a}}class _ extends i{constructor(a){super(),this.error=a}render({_n:a}){return`throw ${this.error};`+a}get names(){return this.error.names}}class T extends i{constructor(a){super(),this.code=a}render({_n:a}){return`${this.code};`+a}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(a,h){return this.code=oe(this.code,a,h),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class C extends i{constructor(a=[]){super(),this.nodes=a}render(a){return this.nodes.reduce((h,N)=>h+N.render(a),"")}optimizeNodes(){const{nodes:a}=this;let h=a.length;for(;h--;){const N=a[h].optimizeNodes();Array.isArray(N)?a.splice(h,1,...N):N?a[h]=N:a.splice(h,1)}return a.length>0?this:void 0}optimizeNames(a,h){const{nodes:N}=this;let M=N.length;for(;M--;){const L=N[M];L.optimizeNames(a,h)||(ke(a,L.names),N.splice(M,1))}return N.length>0?this:void 0}get names(){return this.nodes.reduce((a,h)=>K(a,h.names),{})}}class S extends C{render(a){return"{"+a._n+super.render(a)+"}"+a._n}}class k extends C{}class $ extends S{}$.kind="else";class g extends S{constructor(a,h){super(h),this.condition=a}render(a){let h=`if(${this.condition})`+super.render(a);return this.else&&(h+="else "+this.else.render(a)),h}optimizeNodes(){super.optimizeNodes();const a=this.condition;if(a===!0)return this.nodes;let h=this.else;if(h){const N=h.optimizeNodes();h=this.else=Array.isArray(N)?new $(N):N}if(h)return a===!1?h instanceof g?h:h.nodes:this.nodes.length?this:new g(Ce(a),h instanceof g?[h]:h.nodes);if(!(a===!1||!this.nodes.length))return this}optimizeNames(a,h){var N;if(this.else=(N=this.else)===null||N===void 0?void 0:N.optimizeNames(a,h),!!(super.optimizeNames(a,h)||this.else))return this.condition=oe(this.condition,a,h),this}get names(){const a=super.names;return ue(a,this.condition),this.else&&K(a,this.else.names),a}}g.kind="if";class y extends S{}y.kind="for";class P extends y{constructor(a){super(),this.iteration=a}render(a){return`for(${this.iteration})`+super.render(a)}optimizeNames(a,h){if(super.optimizeNames(a,h))return this.iteration=oe(this.iteration,a,h),this}get names(){return K(super.names,this.iteration.names)}}class I extends y{constructor(a,h,N,M){super(),this.varKind=a,this.name=h,this.from=N,this.to=M}render(a){const h=a.es5?r.varKinds.var:this.varKind,{name:N,from:M,to:L}=this;return`for(${h} ${N}=${M}; ${N}<${L}; ${N}++)`+super.render(a)}get names(){const a=ue(super.names,this.from);return ue(a,this.to)}}class D extends y{constructor(a,h,N,M){super(),this.loop=a,this.varKind=h,this.name=N,this.iterable=M}render(a){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(a)}optimizeNames(a,h){if(super.optimizeNames(a,h))return this.iterable=oe(this.iterable,a,h),this}get names(){return K(super.names,this.iterable.names)}}class w extends S{constructor(a,h,N){super(),this.name=a,this.args=h,this.async=N}render(a){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(a)}}w.kind="func";class O extends C{render(a){return"return "+super.render(a)}}O.kind="return";class A extends S{render(a){let h="try"+super.render(a);return this.catch&&(h+=this.catch.render(a)),this.finally&&(h+=this.finally.render(a)),h}optimizeNodes(){var a,h;return super.optimizeNodes(),(a=this.catch)===null||a===void 0||a.optimizeNodes(),(h=this.finally)===null||h===void 0||h.optimizeNodes(),this}optimizeNames(a,h){var N,M;return super.optimizeNames(a,h),(N=this.catch)===null||N===void 0||N.optimizeNames(a,h),(M=this.finally)===null||M===void 0||M.optimizeNames(a,h),this}get names(){const a=super.names;return this.catch&&K(a,this.catch.names),this.finally&&K(a,this.finally.names),a}}class H extends S{constructor(a){super(),this.error=a}render(a){return`catch(${this.error})`+super.render(a)}}H.kind="catch";class z extends S{render(a){return"finally"+super.render(a)}}z.kind="finally";class re{constructor(a,h={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...h,_n:h.lines?`
|
|
619
|
+
`;this[__private__dont__use].ccall("wasm_set_phpini_entries",null,[STRING],[e])}this[__private__dont__use].ccall("php_wasm_init",null,[],[])},$t=new WeakSet,Kt=function(){const e="/internal/headers.json";if(!this.fileExists(e))throw new Error("SAPI Error: Could not find response headers file.");const t=JSON.parse(this.readFileAsText(e)),r={};for(const n of t.headers){if(!n.includes(": "))continue;const s=n.indexOf(": "),i=n.substring(0,s).toLowerCase(),o=n.substring(s+2);i in r||(r[i]=[]),r[i].push(o)}return{headers:r,httpStatusCode:t.status}},vt=new WeakSet,Jt=function(e){if(this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[e]),e.includes("?")){const t=e.substring(e.indexOf("?")+1);this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[t])}},wt=new WeakSet,Qt=function(e,t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[e]);let r;try{r=parseInt(new URL(e).port,10)}catch{}(!r||isNaN(r)||r===80)&&(r=t==="https"?443:80),this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[r]),(t==="https"||!t&&r===443)&&this.addServerGlobalEntry("HTTPS","on")},Pt=new WeakSet,Zt=function(e){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[e])},Et=new WeakSet,Yt=function(e){e.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[e.cookie]),e["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[e["content-type"]]),e["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(e["content-length"],10)]);for(const t in e){let r="HTTP_";["content-type","content-length"].includes(t.toLowerCase())&&(r=""),this.addServerGlobalEntry(`${r}${t.toUpperCase().replace(/-/g,"_")}`,e[t])}},bt=new WeakSet,Xt=function(e){let t,r;typeof e=="string"?(console.warn("Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"),r=this[__private__dont__use].lengthBytesUTF8(e),t=r+1):(r=e.byteLength,t=e.byteLength);const n=this[__private__dont__use].malloc(t);if(!n)throw new Error("Could not allocate memory for the request body.");return typeof e=="string"?this[__private__dont__use].stringToUTF8(e,n,t+1):this[__private__dont__use].HEAPU8.set(e,n),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[n]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[r]),n},St=new WeakSet,er=function(e){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[e])},Rt=new WeakSet,tr=function(){for(const e in x(this,Te))this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[e,x(this,Te)[e]])},Tt=new WeakSet,rr=function(e,t){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[e,t])},kt=new WeakSet,nr=function(e){this[__private__dont__use].ccall("wasm_set_php_code",null,[STRING],[e])},Ct=new WeakSet,sr=async function(){var s;let e,t;try{e=await new Promise((i,o)=>{var d;t=u=>{console.error(u),console.error(u.error);const p=new Error("Rethrown");p.cause=u.error,p.betterMessage=u.message,o(p)},(d=x(this,Re))==null||d.addEventListener("error",t);const c=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return c instanceof Promise?c.then(i,o):i(c)})}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=getFunctionsMaybeMissingFromAsyncify();const o=i,c="betterMessage"in o?o.betterMessage:o.message,d=new Error(c);throw d.cause=o,console.error(d),d}finally{(s=x(this,Re))==null||s.removeEventListener("error",t),te(this,Te,{})}const{headers:r,httpStatusCode:n}=ce(this,$t,Kt).call(this);return new PHPResponse(e===0?n:500,r,this.readFileAsBuffer("/internal/stdout"),this.readFileAsText("/internal/stderr"),e)};__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],BasePHP.prototype,"mkdir",1);__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],BasePHP.prototype,"mkdirTree",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],BasePHP.prototype,"readFileAsText",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],BasePHP.prototype,"readFileAsBuffer",1);__decorateClass([rethrowFileSystemError('Could not write to "{path}"')],BasePHP.prototype,"writeFile",1);__decorateClass([rethrowFileSystemError('Could not unlink "{path}"')],BasePHP.prototype,"unlink",1);__decorateClass([rethrowFileSystemError('Could not remove directory "{path}"')],BasePHP.prototype,"rmdir",1);__decorateClass([rethrowFileSystemError('Could not list files in "{path}"')],BasePHP.prototype,"listFiles",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],BasePHP.prototype,"isDir",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],BasePHP.prototype,"fileExists",1);function normalizeHeaders(e){const t={};for(const r in e)t[r.toLowerCase()]=e[r];return t}function copyFS(e,t,r){let n;try{n=e.lookupPath(r)}catch{return}if(!("contents"in n.node))return;if(!e.isDir(n.node.mode)){t.writeFile(r,e.readFile(r));return}t.mkdirTree(r);const s=e.readdir(r).filter(i=>i!=="."&&i!=="..");for(const i of s)copyFS(e,t,joinPaths(r,i))}const ResourceTypes=["vfs","literal","wordpress.org/themes","wordpress.org/plugins","url"];function isFileReference(e){return e&&typeof e=="object"&&typeof e.resource=="string"&&ResourceTypes.includes(e.resource)}class Resource{static create(t,{semaphore:r,progress:n}){let s;switch(t.resource){case"vfs":s=new VFSResource(t,n);break;case"literal":s=new LiteralResource(t,n);break;case"wordpress.org/themes":s=new CoreThemeResource(t,n);break;case"wordpress.org/plugins":s=new CorePluginResource(t,n);break;case"url":s=new UrlResource(t,n);break;default:throw new Error(`Invalid resource: ${t}`)}return s=new CachedResource(s),r&&(s=new SemaphoreResource(s,r)),s}setPlayground(t){this.playground=t}get isAsync(){return!1}}class VFSResource extends Resource{constructor(t,r){super(),this.resource=t,this.progress=r}async resolve(){var r;const t=await this.playground.readFileAsBuffer(this.resource.path);return(r=this.progress)==null||r.set(100),new File([t],this.name)}get name(){return this.resource.path.split("/").pop()||""}}class LiteralResource extends Resource{constructor(t,r){super(),this.resource=t,this.progress=r}async resolve(){var t;return(t=this.progress)==null||t.set(100),new File([this.resource.contents],this.resource.name)}get name(){return this.resource.name}}class FetchResource extends Resource{constructor(t){super(),this.progress=t}async resolve(){var n,s;(n=this.progress)==null||n.setCaption(this.caption);const t=this.getURL();let r=await fetch(t);if(r=await cloneResponseMonitorProgress(r,((s=this.progress)==null?void 0:s.loadingListener)??noop),r.status!==200)throw new Error(`Could not download "${t}"`);return new File([await r.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 noop=()=>{};class UrlResource extends FetchResource{constructor(t,r){super(r),this.resource=t}getURL(){return this.resource.url}get caption(){return this.resource.caption??super.caption}}class CoreThemeResource extends FetchResource{constructor(t,r){super(r),this.resource=t}get name(){return zipNameToHumanName(this.resource.slug)}getURL(){return`https://downloads.wordpress.org/theme/${toDirectoryZipName(this.resource.slug)}`}}class CorePluginResource extends FetchResource{constructor(t,r){super(r),this.resource=t}get name(){return zipNameToHumanName(this.resource.slug)}getURL(){return`https://downloads.wordpress.org/plugin/${toDirectoryZipName(this.resource.slug)}`}}function toDirectoryZipName(e){return!e||e.endsWith(".zip")?e:e+".latest-stable.zip"}class DecoratedResource extends Resource{constructor(t){super(),this.resource=t}async resolve(){return this.resource.resolve()}async setPlayground(t){return this.resource.setPlayground(t)}get progress(){return this.resource.progress}set progress(t){this.resource.progress=t}get name(){return this.resource.name}get isAsync(){return this.resource.isAsync}}class CachedResource extends DecoratedResource{async resolve(){return this.promise||(this.promise=super.resolve()),this.promise}}class SemaphoreResource extends DecoratedResource{constructor(t,r){super(t),this.semaphore=r}async resolve(){return this.isAsync?this.semaphore.run(()=>super.resolve()):super.resolve()}}var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ajv$1={exports:{}},core$2={},validate={},boolSchema={},errors={},codegen={},code$1={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(y){if(super(),!e.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((P,I)=>`${P}${I}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((P,I)=>(I instanceof r&&(P[I.str]=(P[I.str]||0)+1),P),{})}}e._Code=n,e.nil=new n("");function s(g,...y){const P=[g[0]];let I=0;for(;I<y.length;)c(P,y[I]),P.push(g[++I]);return new n(P)}e._=s;const i=new n("+");function o(g,...y){const P=[C(g[0])];let I=0;for(;I<y.length;)P.push(i),c(P,y[I]),P.push(i,C(g[++I]));return d(P),new n(P)}e.str=o;function c(g,y){y instanceof n?g.push(...y._items):y instanceof r?g.push(y):g.push(_(y))}e.addCodeArg=c;function d(g){let y=1;for(;y<g.length-1;){if(g[y]===i){const P=u(g[y-1],g[y+1]);if(P!==void 0){g.splice(y-1,3,P);continue}g[y++]="+"}y++}}function u(g,y){if(y==='""')return g;if(g==='""')return y;if(typeof g=="string")return y instanceof r||g[g.length-1]!=='"'?void 0:typeof y!="string"?`${g.slice(0,-1)}${y}"`:y[0]==='"'?g.slice(0,-1)+y.slice(1):void 0;if(typeof y=="string"&&y[0]==='"'&&!(g instanceof r))return`"${g}${y.slice(1)}`}function p(g,y){return y.emptyStr()?g:g.emptyStr()?y:o`${g}${y}`}e.strConcat=p;function _(g){return typeof g=="number"||typeof g=="boolean"||g===null?g:C(Array.isArray(g)?g.join(","):g)}function T(g){return new n(C(g))}e.stringify=T;function C(g){return JSON.stringify(g).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=C;function S(g){return typeof g=="string"&&e.IDENTIFIER.test(g)?new n(`.${g}`):s`[${g}]`}e.getProperty=S;function k(g){if(typeof g=="string"&&e.IDENTIFIER.test(g))return new n(`${g}`);throw new Error(`CodeGen: invalid export name: ${g}, use explicit $id name mapping`)}e.getEsmExportName=k;function $(g){return new n(g.toString())}e.regexpCode=$})(code$1);var scope={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=code$1;class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var n;(function(d){d[d.Started=0]="Started",d[d.Completed=1]="Completed"})(n=e.UsedValueState||(e.UsedValueState={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class s{constructor({prefixes:u,parent:p}={}){this._names={},this._prefixes=u,this._parent=p}toName(u){return u instanceof t.Name?u:this.name(u)}name(u){return new t.Name(this._newName(u))}_newName(u){const p=this._names[u]||this._nameGroup(u);return`${u}${p.index++}`}_nameGroup(u){var p,_;if(!((_=(p=this._parent)===null||p===void 0?void 0:p._prefixes)===null||_===void 0)&&_.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}e.Scope=s;class i extends t.Name{constructor(u,p){super(p),this.prefix=u}setValue(u,{property:p,itemIndex:_}){this.value=u,this.scopePath=(0,t._)`.${new t.Name(p)}[${_}]`}}e.ValueScopeName=i;const o=(0,t._)`\n`;class c extends s{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?o:t.nil}}get(){return this._scope}name(u){return new i(u,this._newName(u))}value(u,p){var _;if(p.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const T=this.toName(u),{prefix:C}=T,S=(_=p.key)!==null&&_!==void 0?_:p.ref;let k=this._values[C];if(k){const y=k.get(S);if(y)return y}else k=this._values[C]=new Map;k.set(S,T);const $=this._scope[C]||(this._scope[C]=[]),g=$.length;return $[g]=p.ref,T.setValue(p,{property:C,itemIndex:g}),T}getValue(u,p){const _=this._values[u];if(_)return _.get(p)}scopeRefs(u,p=this._values){return this._reduceValues(p,_=>{if(_.scopePath===void 0)throw new Error(`CodeGen: name "${_}" has no value`);return(0,t._)`${u}${_.scopePath}`})}scopeCode(u=this._values,p,_){return this._reduceValues(u,T=>{if(T.value===void 0)throw new Error(`CodeGen: name "${T}" has no value`);return T.value.code},p,_)}_reduceValues(u,p,_={},T){let C=t.nil;for(const S in u){const k=u[S];if(!k)continue;const $=_[S]=_[S]||new Map;k.forEach(g=>{if($.has(g))return;$.set(g,n.Started);let y=p(g);if(y){const P=this.opts.es5?e.varKinds.var:e.varKinds.const;C=(0,t._)`${C}${P} ${g} = ${y};${this.opts._n}`}else if(y=T==null?void 0:T(g))C=(0,t._)`${C}${y}${this.opts._n}`;else throw new r(g);$.set(g,n.Completed)})}return C}}e.ValueScope=c})(scope);(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=code$1,r=scope;var n=code$1;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var s=scope;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class i{optimizeNodes(){return this}optimizeNames(a,h){return this}}class o extends i{constructor(a,h,N){super(),this.varKind=a,this.name=h,this.rhs=N}render({es5:a,_n:h}){const N=a?r.varKinds.var:this.varKind,M=this.rhs===void 0?"":` = ${this.rhs}`;return`${N} ${this.name}${M};`+h}optimizeNames(a,h){if(a[this.name.str])return this.rhs&&(this.rhs=oe(this.rhs,a,h)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class c extends i{constructor(a,h,N){super(),this.lhs=a,this.rhs=h,this.sideEffects=N}render({_n:a}){return`${this.lhs} = ${this.rhs};`+a}optimizeNames(a,h){if(!(this.lhs instanceof t.Name&&!a[this.lhs.str]&&!this.sideEffects))return this.rhs=oe(this.rhs,a,h),this}get names(){const a=this.lhs instanceof t.Name?{}:{...this.lhs.names};return ue(a,this.rhs)}}class d extends c{constructor(a,h,N,M){super(a,N,M),this.op=h}render({_n:a}){return`${this.lhs} ${this.op}= ${this.rhs};`+a}}class u extends i{constructor(a){super(),this.label=a,this.names={}}render({_n:a}){return`${this.label}:`+a}}class p extends i{constructor(a){super(),this.label=a,this.names={}}render({_n:a}){return`break${this.label?` ${this.label}`:""};`+a}}class _ extends i{constructor(a){super(),this.error=a}render({_n:a}){return`throw ${this.error};`+a}get names(){return this.error.names}}class T extends i{constructor(a){super(),this.code=a}render({_n:a}){return`${this.code};`+a}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(a,h){return this.code=oe(this.code,a,h),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class C extends i{constructor(a=[]){super(),this.nodes=a}render(a){return this.nodes.reduce((h,N)=>h+N.render(a),"")}optimizeNodes(){const{nodes:a}=this;let h=a.length;for(;h--;){const N=a[h].optimizeNodes();Array.isArray(N)?a.splice(h,1,...N):N?a[h]=N:a.splice(h,1)}return a.length>0?this:void 0}optimizeNames(a,h){const{nodes:N}=this;let M=N.length;for(;M--;){const L=N[M];L.optimizeNames(a,h)||(ke(a,L.names),N.splice(M,1))}return N.length>0?this:void 0}get names(){return this.nodes.reduce((a,h)=>K(a,h.names),{})}}class S extends C{render(a){return"{"+a._n+super.render(a)+"}"+a._n}}class k extends C{}class $ extends S{}$.kind="else";class g extends S{constructor(a,h){super(h),this.condition=a}render(a){let h=`if(${this.condition})`+super.render(a);return this.else&&(h+="else "+this.else.render(a)),h}optimizeNodes(){super.optimizeNodes();const a=this.condition;if(a===!0)return this.nodes;let h=this.else;if(h){const N=h.optimizeNodes();h=this.else=Array.isArray(N)?new $(N):N}if(h)return a===!1?h instanceof g?h:h.nodes:this.nodes.length?this:new g(Ce(a),h instanceof g?[h]:h.nodes);if(!(a===!1||!this.nodes.length))return this}optimizeNames(a,h){var N;if(this.else=(N=this.else)===null||N===void 0?void 0:N.optimizeNames(a,h),!!(super.optimizeNames(a,h)||this.else))return this.condition=oe(this.condition,a,h),this}get names(){const a=super.names;return ue(a,this.condition),this.else&&K(a,this.else.names),a}}g.kind="if";class y extends S{}y.kind="for";class P extends y{constructor(a){super(),this.iteration=a}render(a){return`for(${this.iteration})`+super.render(a)}optimizeNames(a,h){if(super.optimizeNames(a,h))return this.iteration=oe(this.iteration,a,h),this}get names(){return K(super.names,this.iteration.names)}}class I extends y{constructor(a,h,N,M){super(),this.varKind=a,this.name=h,this.from=N,this.to=M}render(a){const h=a.es5?r.varKinds.var:this.varKind,{name:N,from:M,to:L}=this;return`for(${h} ${N}=${M}; ${N}<${L}; ${N}++)`+super.render(a)}get names(){const a=ue(super.names,this.from);return ue(a,this.to)}}class D extends y{constructor(a,h,N,M){super(),this.loop=a,this.varKind=h,this.name=N,this.iterable=M}render(a){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(a)}optimizeNames(a,h){if(super.optimizeNames(a,h))return this.iterable=oe(this.iterable,a,h),this}get names(){return K(super.names,this.iterable.names)}}class w extends S{constructor(a,h,N){super(),this.name=a,this.args=h,this.async=N}render(a){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(a)}}w.kind="func";class O extends C{render(a){return"return "+super.render(a)}}O.kind="return";class A extends S{render(a){let h="try"+super.render(a);return this.catch&&(h+=this.catch.render(a)),this.finally&&(h+=this.finally.render(a)),h}optimizeNodes(){var a,h;return super.optimizeNodes(),(a=this.catch)===null||a===void 0||a.optimizeNodes(),(h=this.finally)===null||h===void 0||h.optimizeNodes(),this}optimizeNames(a,h){var N,M;return super.optimizeNames(a,h),(N=this.catch)===null||N===void 0||N.optimizeNames(a,h),(M=this.finally)===null||M===void 0||M.optimizeNames(a,h),this}get names(){const a=super.names;return this.catch&&K(a,this.catch.names),this.finally&&K(a,this.finally.names),a}}class H extends S{constructor(a){super(),this.error=a}render(a){return`catch(${this.error})`+super.render(a)}}H.kind="catch";class z extends S{render(a){return"finally"+super.render(a)}}z.kind="finally";class re{constructor(a,h={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...h,_n:h.lines?`
|
|
620
620
|
`:""},this._extScope=a,this._scope=new r.Scope({parent:a}),this._nodes=[new k]}toString(){return this._root.render(this.opts)}name(a){return this._scope.name(a)}scopeName(a){return this._extScope.name(a)}scopeValue(a,h){const N=this._extScope.value(a,h);return(this._values[N.prefix]||(this._values[N.prefix]=new Set)).add(N),N}getScopeValue(a,h){return this._extScope.getValue(a,h)}scopeRefs(a){return this._extScope.scopeRefs(a,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(a,h,N,M){const L=this._scope.toName(h);return N!==void 0&&M&&(this._constants[L.str]=N),this._leafNode(new o(a,L,N)),L}const(a,h,N){return this._def(r.varKinds.const,a,h,N)}let(a,h,N){return this._def(r.varKinds.let,a,h,N)}var(a,h,N){return this._def(r.varKinds.var,a,h,N)}assign(a,h,N){return this._leafNode(new c(a,h,N))}add(a,h){return this._leafNode(new d(a,e.operators.ADD,h))}code(a){return typeof a=="function"?a():a!==t.nil&&this._leafNode(new T(a)),this}object(...a){const h=["{"];for(const[N,M]of a)h.length>1&&h.push(","),h.push(N),(N!==M||this.opts.es5)&&(h.push(":"),(0,t.addCodeArg)(h,M));return h.push("}"),new t._Code(h)}if(a,h,N){if(this._blockNode(new g(a)),h&&N)this.code(h).else().code(N).endIf();else if(h)this.code(h).endIf();else if(N)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(a){return this._elseNode(new g(a))}else(){return this._elseNode(new $)}endIf(){return this._endBlockNode(g,$)}_for(a,h){return this._blockNode(a),h&&this.code(h).endFor(),this}for(a,h){return this._for(new P(a),h)}forRange(a,h,N,M,L=this.opts.es5?r.varKinds.var:r.varKinds.let){const W=this._scope.toName(a);return this._for(new I(L,W,h,N),()=>M(W))}forOf(a,h,N,M=r.varKinds.const){const L=this._scope.toName(a);if(this.opts.es5){const W=h instanceof t.Name?h:this.var("_arr",h);return this.forRange("_i",0,(0,t._)`${W}.length`,G=>{this.var(L,(0,t._)`${W}[${G}]`),N(L)})}return this._for(new D("of",M,L,h),()=>N(L))}forIn(a,h,N,M=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(a,(0,t._)`Object.keys(${h})`,N);const L=this._scope.toName(a);return this._for(new D("in",M,L,h),()=>N(L))}endFor(){return this._endBlockNode(y)}label(a){return this._leafNode(new u(a))}break(a){return this._leafNode(new p(a))}return(a){const h=new O;if(this._blockNode(h),this.code(a),h.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(O)}try(a,h,N){if(!h&&!N)throw new Error('CodeGen: "try" without "catch" and "finally"');const M=new A;if(this._blockNode(M),this.code(a),h){const L=this.name("e");this._currNode=M.catch=new H(L),h(L)}return N&&(this._currNode=M.finally=new z,this.code(N)),this._endBlockNode(H,z)}throw(a){return this._leafNode(new _(a))}block(a,h){return this._blockStarts.push(this._nodes.length),a&&this.code(a).endBlock(h),this}endBlock(a){const h=this._blockStarts.pop();if(h===void 0)throw new Error("CodeGen: not in self-balancing block");const N=this._nodes.length-h;if(N<0||a!==void 0&&N!==a)throw new Error(`CodeGen: wrong number of nodes: ${N} vs ${a} expected`);return this._nodes.length=h,this}func(a,h=t.nil,N,M){return this._blockNode(new w(a,h,N)),M&&this.code(M).endFunc(),this}endFunc(){return this._endBlockNode(w)}optimize(a=1){for(;a-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(a){return this._currNode.nodes.push(a),this}_blockNode(a){this._currNode.nodes.push(a),this._nodes.push(a)}_endBlockNode(a,h){const N=this._currNode;if(N instanceof a||h&&N instanceof h)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${h?`${a.kind}/${h.kind}`:a.kind}"`)}_elseNode(a){const h=this._currNode;if(!(h instanceof g))throw new Error('CodeGen: "else" without "if"');return this._currNode=h.else=a,this}get _root(){return this._nodes[0]}get _currNode(){const a=this._nodes;return a[a.length-1]}set _currNode(a){const h=this._nodes;h[h.length-1]=a}}e.CodeGen=re;function K(E,a){for(const h in a)E[h]=(E[h]||0)+(a[h]||0);return E}function ue(E,a){return a instanceof t._CodeOrName?K(E,a.names):E}function oe(E,a,h){if(E instanceof t.Name)return N(E);if(!M(E))return E;return new t._Code(E._items.reduce((L,W)=>(W instanceof t.Name&&(W=N(W)),W instanceof t._Code?L.push(...W._items):L.push(W),L),[]));function N(L){const W=h[L.str];return W===void 0||a[L.str]!==1?L:(delete a[L.str],W)}function M(L){return L instanceof t._Code&&L._items.some(W=>W instanceof t.Name&&a[W.str]===1&&h[W.str]!==void 0)}}function ke(E,a){for(const h in a)E[h]=(E[h]||0)-(a[h]||0)}function Ce(E){return typeof E=="boolean"||typeof E=="number"||E===null?!E:(0,t._)`!${j(E)}`}e.not=Ce;const Le=v(e.operators.AND);function et(...E){return E.reduce(Le)}e.and=et;const qe=v(e.operators.OR);function F(...E){return E.reduce(qe)}e.or=F;function v(E){return(a,h)=>a===t.nil?h:h===t.nil?a:(0,t._)`${j(a)} ${E} ${j(h)}`}function j(E){return E instanceof t.Name?E:(0,t._)`(${E})`}})(codegen);var util={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;const t=codegen,r=code$1;function n(w){const O={};for(const A of w)O[A]=!0;return O}e.toHash=n;function s(w,O){return typeof O=="boolean"?O:Object.keys(O).length===0?!0:(i(w,O),!o(O,w.self.RULES.all))}e.alwaysValidSchema=s;function i(w,O=w.schema){const{opts:A,self:H}=w;if(!A.strictSchema||typeof O=="boolean")return;const z=H.RULES.keywords;for(const re in O)z[re]||D(w,`unknown keyword: "${re}"`)}e.checkUnknownRules=i;function o(w,O){if(typeof w=="boolean")return!w;for(const A in w)if(O[A])return!0;return!1}e.schemaHasRules=o;function c(w,O){if(typeof w=="boolean")return!w;for(const A in w)if(A!=="$ref"&&O.all[A])return!0;return!1}e.schemaHasRulesButRef=c;function d({topSchemaRef:w,schemaPath:O},A,H,z){if(!z){if(typeof A=="number"||typeof A=="boolean")return A;if(typeof A=="string")return(0,t._)`${A}`}return(0,t._)`${w}${O}${(0,t.getProperty)(H)}`}e.schemaRefOrVal=d;function u(w){return T(decodeURIComponent(w))}e.unescapeFragment=u;function p(w){return encodeURIComponent(_(w))}e.escapeFragment=p;function _(w){return typeof w=="number"?`${w}`:w.replace(/~/g,"~0").replace(/\//g,"~1")}e.escapeJsonPointer=_;function T(w){return w.replace(/~1/g,"/").replace(/~0/g,"~")}e.unescapeJsonPointer=T;function C(w,O){if(Array.isArray(w))for(const A of w)O(A);else O(w)}e.eachItem=C;function S({mergeNames:w,mergeToName:O,mergeValues:A,resultToName:H}){return(z,re,K,ue)=>{const oe=K===void 0?re:K instanceof t.Name?(re instanceof t.Name?w(z,re,K):O(z,re,K),K):re instanceof t.Name?(O(z,K,re),re):A(re,K);return ue===t.Name&&!(oe instanceof t.Name)?H(z,oe):oe}}e.mergeEvaluated={props:S({mergeNames:(w,O,A)=>w.if((0,t._)`${A} !== true && ${O} !== undefined`,()=>{w.if((0,t._)`${O} === true`,()=>w.assign(A,!0),()=>w.assign(A,(0,t._)`${A} || {}`).code((0,t._)`Object.assign(${A}, ${O})`))}),mergeToName:(w,O,A)=>w.if((0,t._)`${A} !== true`,()=>{O===!0?w.assign(A,!0):(w.assign(A,(0,t._)`${A} || {}`),$(w,A,O))}),mergeValues:(w,O)=>w===!0?!0:{...w,...O},resultToName:k}),items:S({mergeNames:(w,O,A)=>w.if((0,t._)`${A} !== true && ${O} !== undefined`,()=>w.assign(A,(0,t._)`${O} === true ? true : ${A} > ${O} ? ${A} : ${O}`)),mergeToName:(w,O,A)=>w.if((0,t._)`${A} !== true`,()=>w.assign(A,O===!0?!0:(0,t._)`${A} > ${O} ? ${A} : ${O}`)),mergeValues:(w,O)=>w===!0?!0:Math.max(w,O),resultToName:(w,O)=>w.var("items",O)})};function k(w,O){if(O===!0)return w.var("props",!0);const A=w.var("props",(0,t._)`{}`);return O!==void 0&&$(w,A,O),A}e.evaluatedPropsToName=k;function $(w,O,A){Object.keys(A).forEach(H=>w.assign((0,t._)`${O}${(0,t.getProperty)(H)}`,!0))}e.setEvaluated=$;const g={};function y(w,O){return w.scopeValue("func",{ref:O,code:g[O.code]||(g[O.code]=new r._Code(O.code))})}e.useFunc=y;var P;(function(w){w[w.Num=0]="Num",w[w.Str=1]="Str"})(P=e.Type||(e.Type={}));function I(w,O,A){if(w instanceof t.Name){const H=O===P.Num;return A?H?(0,t._)`"[" + ${w} + "]"`:(0,t._)`"['" + ${w} + "']"`:H?(0,t._)`"/" + ${w}`:(0,t._)`"/" + ${w}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return A?(0,t.getProperty)(w).toString():"/"+_(w)}e.getErrorPath=I;function D(w,O,A=w.opts.strictSchema){if(A){if(O=`strict mode: ${O}`,A===!0)throw new Error(O);w.self.logger.warn(O)}}e.checkStrictMode=D})(util);var names$1={};Object.defineProperty(names$1,"__esModule",{value:!0});const codegen_1$t=codegen,names={data:new codegen_1$t.Name("data"),valCxt:new codegen_1$t.Name("valCxt"),instancePath:new codegen_1$t.Name("instancePath"),parentData:new codegen_1$t.Name("parentData"),parentDataProperty:new codegen_1$t.Name("parentDataProperty"),rootData:new codegen_1$t.Name("rootData"),dynamicAnchors:new codegen_1$t.Name("dynamicAnchors"),vErrors:new codegen_1$t.Name("vErrors"),errors:new codegen_1$t.Name("errors"),this:new codegen_1$t.Name("this"),self:new codegen_1$t.Name("self"),scope:new codegen_1$t.Name("scope"),json:new codegen_1$t.Name("json"),jsonPos:new codegen_1$t.Name("jsonPos"),jsonLen:new codegen_1$t.Name("jsonLen"),jsonPart:new codegen_1$t.Name("jsonPart")};names$1.default=names;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=codegen,r=util,n=names$1;e.keywordError={message:({keyword:$})=>(0,t.str)`must pass "${$}" keyword validation`},e.keyword$DataError={message:({keyword:$,schemaType:g})=>g?(0,t.str)`"${$}" keyword must be ${g} ($data)`:(0,t.str)`"${$}" keyword is invalid ($data)`};function s($,g=e.keywordError,y,P){const{it:I}=$,{gen:D,compositeRule:w,allErrors:O}=I,A=_($,g,y);P??(w||O)?d(D,A):u(I,(0,t._)`[${A}]`)}e.reportError=s;function i($,g=e.keywordError,y){const{it:P}=$,{gen:I,compositeRule:D,allErrors:w}=P,O=_($,g,y);d(I,O),D||w||u(P,n.default.vErrors)}e.reportExtraError=i;function o($,g){$.assign(n.default.errors,g),$.if((0,t._)`${n.default.vErrors} !== null`,()=>$.if(g,()=>$.assign((0,t._)`${n.default.vErrors}.length`,g),()=>$.assign(n.default.vErrors,null)))}e.resetErrorsCount=o;function c({gen:$,keyword:g,schemaValue:y,data:P,errsCount:I,it:D}){if(I===void 0)throw new Error("ajv implementation error");const w=$.name("err");$.forRange("i",I,n.default.errors,O=>{$.const(w,(0,t._)`${n.default.vErrors}[${O}]`),$.if((0,t._)`${w}.instancePath === undefined`,()=>$.assign((0,t._)`${w}.instancePath`,(0,t.strConcat)(n.default.instancePath,D.errorPath))),$.assign((0,t._)`${w}.schemaPath`,(0,t.str)`${D.errSchemaPath}/${g}`),D.opts.verbose&&($.assign((0,t._)`${w}.schema`,y),$.assign((0,t._)`${w}.data`,P))})}e.extendErrors=c;function d($,g){const y=$.const("err",g);$.if((0,t._)`${n.default.vErrors} === null`,()=>$.assign(n.default.vErrors,(0,t._)`[${y}]`),(0,t._)`${n.default.vErrors}.push(${y})`),$.code((0,t._)`${n.default.errors}++`)}function u($,g){const{gen:y,validateName:P,schemaEnv:I}=$;I.$async?y.throw((0,t._)`new ${$.ValidationError}(${g})`):(y.assign((0,t._)`${P}.errors`,g),y.return(!1))}const p={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function _($,g,y){const{createErrors:P}=$.it;return P===!1?(0,t._)`{}`:T($,g,y)}function T($,g,y={}){const{gen:P,it:I}=$,D=[C(I,y),S($,y)];return k($,g,D),P.object(...D)}function C({errorPath:$},{instancePath:g}){const y=g?(0,t.str)`${$}${(0,r.getErrorPath)(g,r.Type.Str)}`:$;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,y)]}function S({keyword:$,it:{errSchemaPath:g}},{schemaPath:y,parentSchema:P}){let I=P?g:(0,t.str)`${g}/${$}`;return y&&(I=(0,t.str)`${I}${(0,r.getErrorPath)(y,r.Type.Str)}`),[p.schemaPath,I]}function k($,{params:g,message:y},P){const{keyword:I,data:D,schemaValue:w,it:O}=$,{opts:A,propertyName:H,topSchemaRef:z,schemaPath:re}=O;P.push([p.keyword,I],[p.params,typeof g=="function"?g($):g||(0,t._)`{}`]),A.messages&&P.push([p.message,typeof y=="function"?y($):y]),A.verbose&&P.push([p.schema,w],[p.parentSchema,(0,t._)`${z}${re}`],[n.default.data,D]),H&&P.push([p.propertyName,H])}})(errors);Object.defineProperty(boolSchema,"__esModule",{value:!0});boolSchema.boolOrEmptySchema=boolSchema.topBoolOrEmptySchema=void 0;const errors_1$2=errors,codegen_1$s=codegen,names_1$6=names$1,boolError={message:"boolean schema is false"};function topBoolOrEmptySchema(e){const{gen:t,schema:r,validateName:n}=e;r===!1?falseSchemaError(e,!1):typeof r=="object"&&r.$async===!0?t.return(names_1$6.default.data):(t.assign((0,codegen_1$s._)`${n}.errors`,null),t.return(!0))}boolSchema.topBoolOrEmptySchema=topBoolOrEmptySchema;function boolOrEmptySchema(e,t){const{gen:r,schema:n}=e;n===!1?(r.var(t,!1),falseSchemaError(e)):r.var(t,!0)}boolSchema.boolOrEmptySchema=boolOrEmptySchema;function falseSchemaError(e,t){const{gen:r,data:n}=e,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,errors_1$2.reportError)(s,boolError,void 0,t)}var dataType={},rules={};Object.defineProperty(rules,"__esModule",{value:!0});rules.getRules=rules.isJSONType=void 0;const _jsonTypes=["string","number","integer","boolean","null","object","array"],jsonTypes=new Set(_jsonTypes);function isJSONType(e){return typeof e=="string"&&jsonTypes.has(e)}rules.isJSONType=isJSONType;function getRules(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}rules.getRules=getRules;var applicability={};Object.defineProperty(applicability,"__esModule",{value:!0});applicability.shouldUseRule=applicability.shouldUseGroup=applicability.schemaHasRulesForType=void 0;function schemaHasRulesForType({schema:e,self:t},r){const n=t.RULES.types[r];return n&&n!==!0&&shouldUseGroup(e,n)}applicability.schemaHasRulesForType=schemaHasRulesForType;function shouldUseGroup(e,t){return t.rules.some(r=>shouldUseRule(e,r))}applicability.shouldUseGroup=shouldUseGroup;function shouldUseRule(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}applicability.shouldUseRule=shouldUseRule;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;const t=rules,r=applicability,n=errors,s=codegen,i=util;var o;(function(P){P[P.Correct=0]="Correct",P[P.Wrong=1]="Wrong"})(o=e.DataType||(e.DataType={}));function c(P){const I=d(P.type);if(I.includes("null")){if(P.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!I.length&&P.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');P.nullable===!0&&I.push("null")}return I}e.getSchemaTypes=c;function d(P){const I=Array.isArray(P)?P:P?[P]:[];if(I.every(t.isJSONType))return I;throw new Error("type must be JSONType or JSONType[]: "+I.join(","))}e.getJSONTypes=d;function u(P,I){const{gen:D,data:w,opts:O}=P,A=_(I,O.coerceTypes),H=I.length>0&&!(A.length===0&&I.length===1&&(0,r.schemaHasRulesForType)(P,I[0]));if(H){const z=k(I,w,O.strictNumbers,o.Wrong);D.if(z,()=>{A.length?T(P,I,A):g(P)})}return H}e.coerceAndCheckDataType=u;const p=new Set(["string","number","integer","boolean","null"]);function _(P,I){return I?P.filter(D=>p.has(D)||I==="array"&&D==="array"):[]}function T(P,I,D){const{gen:w,data:O,opts:A}=P,H=w.let("dataType",(0,s._)`typeof ${O}`),z=w.let("coerced",(0,s._)`undefined`);A.coerceTypes==="array"&&w.if((0,s._)`${H} == 'object' && Array.isArray(${O}) && ${O}.length == 1`,()=>w.assign(O,(0,s._)`${O}[0]`).assign(H,(0,s._)`typeof ${O}`).if(k(I,O,A.strictNumbers),()=>w.assign(z,O))),w.if((0,s._)`${z} !== undefined`);for(const K of D)(p.has(K)||K==="array"&&A.coerceTypes==="array")&&re(K);w.else(),g(P),w.endIf(),w.if((0,s._)`${z} !== undefined`,()=>{w.assign(O,z),C(P,z)});function re(K){switch(K){case"string":w.elseIf((0,s._)`${H} == "number" || ${H} == "boolean"`).assign(z,(0,s._)`"" + ${O}`).elseIf((0,s._)`${O} === null`).assign(z,(0,s._)`""`);return;case"number":w.elseIf((0,s._)`${H} == "boolean" || ${O} === null
|
|
621
621
|
|| (${H} == "string" && ${O} && ${O} == +${O})`).assign(z,(0,s._)`+${O}`);return;case"integer":w.elseIf((0,s._)`${H} === "boolean" || ${O} === null
|
|
622
622
|
|| (${H} === "string" && ${O} && ${O} == +${O} && !(${O} % 1))`).assign(z,(0,s._)`+${O}`);return;case"boolean":w.elseIf((0,s._)`${O} === "false" || ${O} === 0 || ${O} === null`).assign(z,!1).elseIf((0,s._)`${O} === "true" || ${O} === 1`).assign(z,!0);return;case"null":w.elseIf((0,s._)`${O} === "" || ${O} === 0 || ${O} === false`),w.assign(z,null);return;case"array":w.elseIf((0,s._)`${H} === "string" || ${H} === "number"
|
package/index.js
CHANGED
|
@@ -274,7 +274,7 @@ require_once( ${phpVar(s)}. "/wp-load.php" );
|
|
|
274
274
|
require_once( ${phpVar(s)}. "/wp-admin/includes/plugin.php" );
|
|
275
275
|
|
|
276
276
|
// Set current user to admin
|
|
277
|
-
|
|
277
|
+
wp_set_current_user( get_users(array('role' => 'Administrator') )[0]->ID );
|
|
278
278
|
|
|
279
279
|
$plugin_path = ${phpVar(t)};
|
|
280
280
|
|
|
@@ -304,7 +304,7 @@ define( 'WP_ADMIN', true );
|
|
|
304
304
|
require_once( ${phpVar(n)}. "/wp-load.php" );
|
|
305
305
|
|
|
306
306
|
// Set current user to admin
|
|
307
|
-
|
|
307
|
+
wp_set_current_user( get_users(array('role' => 'Administrator') )[0]->ID );
|
|
308
308
|
|
|
309
309
|
switch_theme( ${phpVar(t)} );
|
|
310
310
|
`
|
|
@@ -793,7 +793,7 @@ define( 'WP_ADMIN', true );
|
|
|
793
793
|
require_once(${phpVar(s)} . "/wp-load.php");
|
|
794
794
|
|
|
795
795
|
// Set current user to admin
|
|
796
|
-
|
|
796
|
+
( get_users(array('role' => 'Administrator') )[0] );
|
|
797
797
|
|
|
798
798
|
require_once(${phpVar(s)} . "/wp-admin/includes/plugin.php");
|
|
799
799
|
$plugins_root = ${phpVar(s)} . "/wp-content/plugins";
|
|
@@ -2015,17 +2015,24 @@ Pe = new WeakMap(), Ke = new WeakMap(), dt = new WeakMap(), De = new WeakMap(),
|
|
|
2015
2015
|
new TextEncoder().encode("404 File not found")
|
|
2016
2016
|
);
|
|
2017
2017
|
}
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2018
|
+
try {
|
|
2019
|
+
return await this.php.run({
|
|
2020
|
+
relativeUri: ensurePathPrefix(
|
|
2021
|
+
toRelativeUrl(r),
|
|
2022
|
+
H(this, ve)
|
|
2023
|
+
),
|
|
2024
|
+
protocol: H(this, Ke),
|
|
2025
|
+
method: t.method || i,
|
|
2026
|
+
body: c,
|
|
2027
|
+
scriptPath: d,
|
|
2028
|
+
headers: o
|
|
2029
|
+
});
|
|
2030
|
+
} catch (u) {
|
|
2031
|
+
const p = u;
|
|
2032
|
+
if (p != null && p.response)
|
|
2033
|
+
return p.response;
|
|
2034
|
+
throw u;
|
|
2035
|
+
}
|
|
2029
2036
|
} finally {
|
|
2030
2037
|
n();
|
|
2031
2038
|
}
|
|
@@ -2209,6 +2216,11 @@ var __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyD
|
|
|
2209
2216
|
return n && s && __defProp(t, r, s), s;
|
|
2210
2217
|
};
|
|
2211
2218
|
const STRING = "string", NUMBER = "number", __private__dont__use = Symbol("__private__dont__use");
|
|
2219
|
+
class PHPExecutionFailureError extends Error {
|
|
2220
|
+
constructor(t, r, n) {
|
|
2221
|
+
super(t), this.response = r, this.source = n;
|
|
2222
|
+
}
|
|
2223
|
+
}
|
|
2212
2224
|
var Me, Ze, Ye, Ee, Re, Te, be, Xe, yt, Gt, $t, Kt, vt, Jt, wt, Qt, Pt, Zt, Et, Yt, bt, Xt, St, er, Rt, tr, Tt, rr, kt, nr, Ct, sr;
|
|
2213
2225
|
class BasePHP {
|
|
2214
2226
|
/**
|
|
@@ -2357,10 +2369,12 @@ class BasePHP {
|
|
|
2357
2369
|
const o = await ce(this, Ct, sr).call(this);
|
|
2358
2370
|
if (o.exitCode !== 0) {
|
|
2359
2371
|
console.warn("PHP.run() output was:", o.text);
|
|
2360
|
-
const c = new
|
|
2361
|
-
`PHP.run() failed with exit code ${o.exitCode} and the following output: ` + o.errors
|
|
2372
|
+
const c = new PHPExecutionFailureError(
|
|
2373
|
+
`PHP.run() failed with exit code ${o.exitCode} and the following output: ` + o.errors,
|
|
2374
|
+
o,
|
|
2375
|
+
"request"
|
|
2362
2376
|
);
|
|
2363
|
-
throw
|
|
2377
|
+
throw console.error(c), c;
|
|
2364
2378
|
}
|
|
2365
2379
|
return o;
|
|
2366
2380
|
} catch (n) {
|
|
@@ -2689,7 +2703,7 @@ Me = new WeakMap(), Ze = new WeakMap(), Ye = new WeakMap(), Ee = new WeakMap(),
|
|
|
2689
2703
|
}
|
|
2690
2704
|
const { headers: r, httpStatusCode: n } = ce(this, $t, Kt).call(this);
|
|
2691
2705
|
return new PHPResponse(
|
|
2692
|
-
n,
|
|
2706
|
+
e === 0 ? n : 500,
|
|
2693
2707
|
r,
|
|
2694
2708
|
this.readFileAsBuffer("/internal/stdout"),
|
|
2695
2709
|
this.readFileAsText("/internal/stderr"),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wp-playground/client",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.16",
|
|
4
4
|
"description": "WordPress Playground client",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"main": "./index.cjs",
|
|
38
38
|
"module": "./index.js",
|
|
39
39
|
"types": "index.d.ts",
|
|
40
|
-
"gitHead": "
|
|
40
|
+
"gitHead": "1981567e7eacecbc4a18c870267c20bf489afd8f",
|
|
41
41
|
"engines": {
|
|
42
42
|
"node": ">=18.18.0",
|
|
43
43
|
"npm": ">=8.11.0"
|