@wp-playground/wordpress 0.9.12 → 0.9.14

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.
Files changed (2) hide show
  1. package/index.js +20 -22
  2. package/package.json +3 -3
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
- const SleepFinished=Symbol("SleepFinished");function sleep(e){return new Promise(t=>{setTimeout(()=>t(SleepFinished),e)})}class AcquireTimeoutError extends Error{constructor(){super("Acquiring lock timed out")}}class Semaphore{constructor({concurrency:t,timeout:s}){this._running=0,this.concurrency=t,this.timeout=s,this.queue=[]}get remaining(){return this.concurrency-this.running}get running(){return this._running}async acquire(){for(;;)if(this._running>=this.concurrency){const t=new Promise(s=>{this.queue.push(s)});this.timeout!==void 0?await Promise.race([t,sleep(this.timeout)]).then(s=>{if(s===SleepFinished)throw new AcquireTimeoutError}):await t}else{this._running++;let t=!1;return()=>{t||(t=!0,this._running--,this.queue.length>0&&this.queue.shift()())}}}async run(t){const s=await this.acquire();try{return await t()}finally{s()}}}function joinPaths(...e){let t=e.join("/");const s=t[0]==="/",r=t.substring(t.length-1)==="/";return t=normalizePath(t),!t&&!s&&(t="."),t&&r&&(t+="/"),t}function dirname(e){if(e==="/")return"/";e=normalizePath(e);const t=e.lastIndexOf("/");return t===-1?"":t===0?"/":e.substr(0,t)}function normalizePath(e){const t=e[0]==="/";return e=normalizePathsArray(e.split("/").filter(s=>!!s),!t).join("/"),(t?"/":"")+e.replace(/\/$/,"")}function normalizePathsArray(e,t){let s=0;for(let r=e.length-1;r>=0;r--){const n=e[r];n==="."?e.splice(r,1):n===".."?(e.splice(r,1),s++):s&&(e.splice(r,1),s--)}if(t)for(;s;s--)e.unshift("..");return e}function splitShellCommand(e){let r=0,n="";const i=[];let o="";for(let a=0;a<e.length;a++){const c=e[a];c==="\\"?((e[a+1]==='"'||e[a+1]==="'")&&a++,o+=e[a]):r===0?c==='"'||c==="'"?(r=1,n=c):c.match(/\s/)?(o.trim().length&&i.push(o.trim()),o=c):i.length&&!o?o=i.pop()+c:o+=c:r===1&&(c===n?(r=0,n=""):o+=c)}return o&&i.push(o.trim()),i}function createSpawnHandler(e){return function(t,s=[],r={}){const n=new ChildProcess,i=new ProcessApi(n);return setTimeout(async()=>{let o=[];if(s.length)o=[t,...s];else if(typeof t=="string")o=splitShellCommand(t);else if(Array.isArray(t))o=t;else throw new Error("Invalid command ",t);try{await e(o,i,r)}catch(a){n.emit("error",a),typeof a=="object"&&a!==null&&"message"in a&&typeof a.message=="string"&&i.stderr(a.message),i.exit(1)}n.emit("spawn",!0)}),n}}class EventEmitter{constructor(){this.listeners={}}emit(t,s){this.listeners[t]&&this.listeners[t].forEach(function(r){r(s)})}on(t,s){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(s)}}class ProcessApi extends EventEmitter{constructor(t){super(),this.childProcess=t,this.exited=!1,this.stdinData=[],t.on("stdin",s=>{this.stdinData?this.stdinData.push(s.slice()):this.emit("stdin",s)})}stdout(t){typeof t=="string"&&(t=new TextEncoder().encode(t)),this.childProcess.stdout.emit("data",t)}stdoutEnd(){this.childProcess.stdout.emit("end",{})}stderr(t){typeof t=="string"&&(t=new TextEncoder().encode(t)),this.childProcess.stderr.emit("data",t)}stderrEnd(){this.childProcess.stderr.emit("end",{})}exit(t){this.exited||(this.exited=!0,this.childProcess.emit("exit",t))}flushStdin(){if(this.stdinData)for(let t=0;t<this.stdinData.length;t++)this.emit("stdin",this.stdinData[t]);this.stdinData=null}}let lastPid=9743;class ChildProcess extends EventEmitter{constructor(t=lastPid++){super(),this.pid=t,this.stdout=new EventEmitter,this.stderr=new EventEmitter;const s=this;this.stdin={write:r=>{s.emit("stdin",r)}}}}function phpVar(e){return`json_decode(base64_decode('${stringToBase64(JSON.stringify(e))}'), true)`}function phpVars(e){const t={};for(const s in e)t[s]=phpVar(e[s]);return t}function stringToBase64(e){return bytesToBase64(new TextEncoder().encode(e))}function bytesToBase64(e){const t=String.fromCodePoint(...e);return btoa(t)}const tmpPath="/tmp/file.zip",unzipFile=async(e,t,s)=>{if(t instanceof File){const n=t;t=tmpPath,await e.writeFile(t,new Uint8Array(await n.arrayBuffer()))}const r=phpVars({zipPath:t,extractToPath:s});await e.run({code:`<?php
1
+ import{parse,stringify}from"/home/runner/work/wordpress-playground/wordpress-playground/node_modules/ini/lib/ini.js";const SleepFinished=Symbol("SleepFinished");function sleep(e){return new Promise(t=>{setTimeout(()=>t(SleepFinished),e)})}class AcquireTimeoutError extends Error{constructor(){super("Acquiring lock timed out")}}class Semaphore{constructor({concurrency:t,timeout:r}){this._running=0,this.concurrency=t,this.timeout=r,this.queue=[]}get remaining(){return this.concurrency-this.running}get running(){return this._running}async acquire(){for(;;)if(this._running>=this.concurrency){const t=new Promise(r=>{this.queue.push(r)});this.timeout!==void 0?await Promise.race([t,sleep(this.timeout)]).then(r=>{if(r===SleepFinished)throw new AcquireTimeoutError}):await t}else{this._running++;let t=!1;return()=>{t||(t=!0,this._running--,this.queue.length>0&&this.queue.shift()())}}}async run(t){const r=await this.acquire();try{return await t()}finally{r()}}}function joinPaths(...e){let t=e.join("/");const r=t[0]==="/",s=t.substring(t.length-1)==="/";return t=normalizePath(t),!t&&!r&&(t="."),t&&s&&(t+="/"),t}function dirname(e){if(e==="/")return"/";e=normalizePath(e);const t=e.lastIndexOf("/");return t===-1?"":t===0?"/":e.substr(0,t)}function normalizePath(e){const t=e[0]==="/";return e=normalizePathsArray(e.split("/").filter(r=>!!r),!t).join("/"),(t?"/":"")+e.replace(/\/$/,"")}function normalizePathsArray(e,t){let r=0;for(let s=e.length-1;s>=0;s--){const i=e[s];i==="."?e.splice(s,1):i===".."?(e.splice(s,1),r++):r&&(e.splice(s,1),r--)}if(t)for(;r;r--)e.unshift("..");return e}function splitShellCommand(e){let s=0,i="";const n=[];let o="";for(let a=0;a<e.length;a++){const l=e[a];l==="\\"?((e[a+1]==='"'||e[a+1]==="'")&&a++,o+=e[a]):s===0?l==='"'||l==="'"?(s=1,i=l):l.match(/\s/)?(o.trim().length&&n.push(o.trim()),o=l):n.length&&!o?o=n.pop()+l:o+=l:s===1&&(l===i?(s=0,i=""):o+=l)}return o&&n.push(o.trim()),n}function createSpawnHandler(e){return function(t,r=[],s={}){const i=new ChildProcess,n=new ProcessApi(i);return setTimeout(async()=>{let o=[];if(r.length)o=[t,...r];else if(typeof t=="string")o=splitShellCommand(t);else if(Array.isArray(t))o=t;else throw new Error("Invalid command ",t);try{await e(o,n,s)}catch(a){i.emit("error",a),typeof a=="object"&&a!==null&&"message"in a&&typeof a.message=="string"&&n.stderr(a.message),n.exit(1)}i.emit("spawn",!0)}),i}}class EventEmitter{constructor(){this.listeners={}}emit(t,r){this.listeners[t]&&this.listeners[t].forEach(function(s){s(r)})}on(t,r){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(r)}}class ProcessApi extends EventEmitter{constructor(t){super(),this.childProcess=t,this.exited=!1,this.stdinData=[],t.on("stdin",r=>{this.stdinData?this.stdinData.push(r.slice()):this.emit("stdin",r)})}stdout(t){typeof t=="string"&&(t=new TextEncoder().encode(t)),this.childProcess.stdout.emit("data",t)}stdoutEnd(){this.childProcess.stdout.emit("end",{})}stderr(t){typeof t=="string"&&(t=new TextEncoder().encode(t)),this.childProcess.stderr.emit("data",t)}stderrEnd(){this.childProcess.stderr.emit("end",{})}exit(t){this.exited||(this.exited=!0,this.childProcess.emit("exit",t))}flushStdin(){if(this.stdinData)for(let t=0;t<this.stdinData.length;t++)this.emit("stdin",this.stdinData[t]);this.stdinData=null}}let lastPid=9743;class ChildProcess extends EventEmitter{constructor(t=lastPid++){super(),this.pid=t,this.stdout=new EventEmitter,this.stderr=new EventEmitter;const r=this;this.stdin={write:s=>{r.emit("stdin",s)}}}}function phpVar(e){return`json_decode(base64_decode('${stringToBase64(JSON.stringify(e))}'), true)`}function phpVars(e){const t={};for(const r in e)t[r]=phpVar(e[r]);return t}function stringToBase64(e){return bytesToBase64(new TextEncoder().encode(e))}function bytesToBase64(e){const t=String.fromCodePoint(...e);return btoa(t)}const tmpPath="/tmp/file.zip",unzipFile=async(e,t,r)=>{if(t instanceof File){const i=t;t=tmpPath,await e.writeFile(t,new Uint8Array(await i.arrayBuffer()))}const s=phpVars({zipPath:t,extractToPath:r});await e.run({code:`<?php
2
2
  function unzip($zipPath, $extractTo, $overwrite = true)
3
3
  {
4
4
  if (!is_dir($extractTo)) {
@@ -14,17 +14,17 @@ const SleepFinished=Symbol("SleepFinished");function sleep(e){return new Promise
14
14
  throw new Exception("Could not unzip file");
15
15
  }
16
16
  }
17
- unzip(${r.zipPath}, ${r.extractToPath});
18
- `}),await e.fileExists(tmpPath)&&await e.unlink(tmpPath)},currentJsRuntime=function(){return typeof process<"u"&&process.release?.name==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}();if(currentJsRuntime==="NODE"){let e=function(s){return new Promise(function(r,n){s.onload=s.onerror=function(i){s.onload=s.onerror=null,i.type==="load"?r(s.result):n(new Error("Failed to read the blob/file"))}})},t=function(){const s=new Uint8Array([1,2,3,4]),n=new File([s],"test").stream();try{return n.getReader({mode:"byob"}),!0}catch{return!1}};if(typeof File>"u"){class s extends Blob{constructor(n,i,o){super(n);let a;o?.lastModified&&(a=new Date),(!a||isNaN(a.getFullYear()))&&(a=new Date),this.lastModifiedDate=a,this.lastModified=a.getMilliseconds(),this.name=i||""}}global.File=s}typeof Blob.prototype.arrayBuffer>"u"&&(Blob.prototype.arrayBuffer=function(){const r=new FileReader;return r.readAsArrayBuffer(this),e(r)}),typeof Blob.prototype.text>"u"&&(Blob.prototype.text=function(){const r=new FileReader;return r.readAsText(this),e(r)}),(typeof Blob.prototype.stream>"u"||!t())&&(Blob.prototype.stream=function(){let s=0;const r=this;return new ReadableStream({type:"bytes",autoAllocateChunkSize:512*1024,async pull(n){const i=n.byobRequest.view,a=await r.slice(s,s+i.byteLength).arrayBuffer(),c=new Uint8Array(a);new Uint8Array(i.buffer).set(c);const l=c.byteLength;n.byobRequest.respond(l),s+=l,s>=r.size&&n.close()}})})}if(currentJsRuntime==="NODE"&&typeof CustomEvent>"u"){class e extends Event{constructor(s,r={}){super(s,r),this.detail=r.detail}initCustomEvent(){}}globalThis.CustomEvent=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?.errno:null;if(t in FileErrorCodes)return FileErrorCodes[t]}function rethrowFileSystemError(e=""){return function(s,r,n){const i=n.value;n.value=function(...o){try{return i.apply(this,o)}catch(a){const c=typeof a=="object"?a?.errno:null;if(c in FileErrorCodes){const l=FileErrorCodes[c],d=typeof o[1]=="string"?o[1]:null,p=d!==null?e.replaceAll("{path}",d):e;throw new Error(`${p}: ${l}`,{cause:a})}throw a}}}}const logEventType="playground-log",logEvent=(e,...t)=>{logger.dispatchEvent(new CustomEvent(logEventType,{detail:{log:e,args:t}}))},logToConsole=(e,...t)=>{switch(typeof e.message=="string"?e.message=prepareLogMessage(e.message):e.message.message&&typeof e.message.message=="string"&&(e.message.message=prepareLogMessage(e.message.message)),e.severity){case"Debug":console.debug(e.message,...t);break;case"Info":console.info(e.message,...t);break;case"Warn":console.warn(e.message,...t);break;case"Error":console.error(e.message,...t);break;case"Fatal":console.error(e.message,...t);break;default:console.log(e.message,...t)}},prepareLogMessage$1=e=>e instanceof Error?[e.message,e.stack].join(`
17
+ unzip(${s.zipPath}, ${s.extractToPath});
18
+ `}),await e.fileExists(tmpPath)&&await e.unlink(tmpPath)},currentJsRuntime=function(){return typeof process<"u"&&process.release?.name==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}();if(currentJsRuntime==="NODE"){let e=function(r){return new Promise(function(s,i){r.onload=r.onerror=function(n){r.onload=r.onerror=null,n.type==="load"?s(r.result):i(new Error("Failed to read the blob/file"))}})},t=function(){const r=new Uint8Array([1,2,3,4]),i=new File([r],"test").stream();try{return i.getReader({mode:"byob"}),!0}catch{return!1}};if(typeof File>"u"){class r extends Blob{constructor(i,n,o){super(i);let a;o?.lastModified&&(a=new Date),(!a||isNaN(a.getFullYear()))&&(a=new Date),this.lastModifiedDate=a,this.lastModified=a.getMilliseconds(),this.name=n||""}}global.File=r}typeof Blob.prototype.arrayBuffer>"u"&&(Blob.prototype.arrayBuffer=function(){const s=new FileReader;return s.readAsArrayBuffer(this),e(s)}),typeof Blob.prototype.text>"u"&&(Blob.prototype.text=function(){const s=new FileReader;return s.readAsText(this),e(s)}),(typeof Blob.prototype.stream>"u"||!t())&&(Blob.prototype.stream=function(){let r=0;const s=this;return new ReadableStream({type:"bytes",autoAllocateChunkSize:512*1024,async pull(i){const n=i.byobRequest.view,a=await s.slice(r,r+n.byteLength).arrayBuffer(),l=new Uint8Array(a);new Uint8Array(n.buffer).set(l);const c=l.byteLength;i.byobRequest.respond(c),r+=c,r>=s.size&&i.close()}})})}if(currentJsRuntime==="NODE"&&typeof CustomEvent>"u"){class e extends Event{constructor(r,s={}){super(r,s),this.detail=s.detail}initCustomEvent(){}}globalThis.CustomEvent=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?.errno:null;if(t in FileErrorCodes)return FileErrorCodes[t]}function rethrowFileSystemError(e=""){return function(r,s,i){const n=i.value;i.value=function(...o){try{return n.apply(this,o)}catch(a){const l=typeof a=="object"?a?.errno:null;if(l in FileErrorCodes){const c=FileErrorCodes[l],p=typeof o[1]=="string"?o[1]:null,u=p!==null?e.replaceAll("{path}",p):e;throw new Error(`${u}: ${c}`,{cause:a})}throw a}}}}const logEventType="playground-log",logEvent=(e,...t)=>{logger.dispatchEvent(new CustomEvent(logEventType,{detail:{log:e,args:t}}))},logToConsole=(e,...t)=>{switch(typeof e.message=="string"?e.message=prepareLogMessage(e.message):e.message.message&&typeof e.message.message=="string"&&(e.message.message=prepareLogMessage(e.message.message)),e.severity){case"Debug":console.debug(e.message,...t);break;case"Info":console.info(e.message,...t);break;case"Warn":console.warn(e.message,...t);break;case"Error":console.error(e.message,...t);break;case"Fatal":console.error(e.message,...t);break;default:console.log(e.message,...t)}},prepareLogMessage$1=e=>e instanceof Error?[e.message,e.stack].join(`
19
19
  `):JSON.stringify(e,null,2),logs=[],addToLogArray=e=>{logs.push(e)},logToMemory=e=>{if(e.raw===!0)addToLogArray(e.message);else{const t=formatLogEntry(typeof e.message=="object"?prepareLogMessage$1(e.message):e.message,e.severity??"Info",e.prefix??"JavaScript");addToLogArray(t)}};class Logger extends EventTarget{constructor(t=[]){super(),this.handlers=t,this.fatalErrorEvent="playground-fatal-error"}getLogs(){return this.handlers.includes(logToMemory)?[...logs]:(this.error(`Logs aren't stored because the logToMemory handler isn't registered.
20
20
  If you're using a custom logger instance, make sure to register logToMemory handler.
21
- `),[])}logMessage(t,...s){for(const r of this.handlers)r(t,...s)}log(t,...s){this.logMessage({message:t,severity:void 0,prefix:"JavaScript",raw:!1},...s)}debug(t,...s){this.logMessage({message:t,severity:"Debug",prefix:"JavaScript",raw:!1},...s)}info(t,...s){this.logMessage({message:t,severity:"Info",prefix:"JavaScript",raw:!1},...s)}warn(t,...s){this.logMessage({message:t,severity:"Warn",prefix:"JavaScript",raw:!1},...s)}error(t,...s){this.logMessage({message:t,severity:"Error",prefix:"JavaScript",raw:!1},...s)}}const getDefaultHandlers=()=>{try{if(process.env.NODE_ENV==="test")return[logToMemory,logEvent]}catch{}return[logToMemory,logToConsole,logEvent]},logger=new Logger(getDefaultHandlers()),prepareLogMessage=e=>e.replace(/\t/g,""),formatLogEntry=(e,t,s)=>{const r=new Date,n=new Intl.DateTimeFormat("en-GB",{year:"numeric",month:"short",day:"2-digit",timeZone:"UTC"}).format(r).replace(/ /g,"-"),i=new Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZone:"UTC",timeZoneName:"short"}).format(r),o=n+" "+i;return e=prepareLogMessage(e),`[${o}] ${s} ${t}: ${e}`};var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(e,t,s,r)=>{for(var n=r>1?void 0:r?__getOwnPropDesc(t,s):t,i=e.length-1,o;i>=0;i--)(o=e[i])&&(n=(r?o(t,s,n):o(n))||n);return r&&n&&__defProp(t,s,n),n};const _FSHelpers=class h{static readFileAsText(t,s){return new TextDecoder().decode(h.readFileAsBuffer(t,s))}static readFileAsBuffer(t,s){return t.readFile(s)}static writeFile(t,s,r){t.writeFile(s,r)}static unlink(t,s){t.unlink(s)}static mv(t,s,r){try{const n=t.lookupPath(s).node.mount,i=h.fileExists(t,r)?t.lookupPath(r).node.mount:t.lookupPath(dirname(r)).node.mount;n.mountpoint!==i.mountpoint?(h.copyRecursive(t,s,r),h.rmdir(t,s,{recursive:!0})):t.rename(s,r)}catch(n){const i=getEmscriptenFsError(n);throw i?new Error(`Could not move ${s} to ${r}: ${i}`,{cause:n}):n}}static rmdir(t,s,r={recursive:!0}){r?.recursive&&h.listFiles(t,s).forEach(n=>{const i=`${s}/${n}`;h.isDir(t,i)?h.rmdir(t,i,r):h.unlink(t,i)}),t.rmdir(s)}static listFiles(t,s,r={prependPath:!1}){if(!h.fileExists(t,s))return[];try{const n=t.readdir(s).filter(i=>i!=="."&&i!=="..");if(r.prependPath){const i=s.replace(/\/$/,"");return n.map(o=>`${i}/${o}`)}return n}catch(n){return logger.error(n,{path:s}),[]}}static isDir(t,s){return h.fileExists(t,s)?t.isDir(t.lookupPath(s).node.mode):!1}static fileExists(t,s){try{return t.lookupPath(s),!0}catch{return!1}}static mkdir(t,s){t.mkdirTree(s)}static copyRecursive(t,s,r){const n=t.lookupPath(s).node;if(t.isDir(n.mode)){t.mkdirTree(r);const i=t.readdir(s).filter(o=>o!=="."&&o!=="..");for(const o of i)h.copyRecursive(t,joinPaths(s,o),joinPaths(r,o))}else t.writeFile(r,t.readFile(s))}};__decorateClass([rethrowFileSystemError('Could not read "{path}"')],_FSHelpers,"readFileAsText",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],_FSHelpers,"readFileAsBuffer",1);__decorateClass([rethrowFileSystemError('Could not write to "{path}"')],_FSHelpers,"writeFile",1);__decorateClass([rethrowFileSystemError('Could not unlink "{path}"')],_FSHelpers,"unlink",1);__decorateClass([rethrowFileSystemError('Could not remove directory "{path}"')],_FSHelpers,"rmdir",1);__decorateClass([rethrowFileSystemError('Could not list files in "{path}"')],_FSHelpers,"listFiles",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],_FSHelpers,"isDir",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],_FSHelpers,"fileExists",1);__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],_FSHelpers,"mkdir",1);__decorateClass([rethrowFileSystemError('Could not copy files from "{path}"')],_FSHelpers,"copyRecursive",1);let FSHelpers=_FSHelpers;const responseTexts={500:"Internal Server Error",502:"Bad Gateway",404:"Not Found",403:"Forbidden",401:"Unauthorized",400:"Bad Request",301:"Moved Permanently",302:"Found",307:"Temporary Redirect",308:"Permanent Redirect",204:"No Content",201:"Created",200:"OK"};class PHPResponse{constructor(t,s,r,n="",i=0){this.httpStatusCode=t,this.headers=s,this.bytes=r,this.exitCode=i,this.errors=n}static forHttpCode(t,s=""){return new PHPResponse(t,{},new TextEncoder().encode(s||responseTexts[t]||""))}static fromRawData(t){return new PHPResponse(t.httpStatusCode,t.headers,t.bytes,t.errors,t.exitCode)}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}const loadedRuntimes=new Map;function getLoadedRuntime(e){return loadedRuntimes.get(e)}(function(){return typeof process<"u"&&process.release?.name==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends Event{constructor(t,s={}){super(t),this[kError]=s.error===void 0?null:s.error,this[kMessage]=s.message===void 0?"":s.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent2.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent2.prototype,"message",{enumerable:!0});const ErrorEvent=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:ErrorEvent2;function isExitCodeZero(e){return e instanceof Error?"exitCode"in e&&e?.exitCode===0||e?.name==="ExitStatus"&&"status"in e&&e.status===0:!1}class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(t,s){++this.listenersCount,super.addEventListener(t,s)}removeEventListener(t,s){--this.listenersCount,super.removeEventListener(t,s)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(e){const t=new UnhandledRejectionsTarget;for(const s in e.wasmExports)if(typeof e.wasmExports[s]=="function"){const r=e.wasmExports[s];e.wasmExports[s]=function(...n){try{return r(...n)}catch(i){if(!(i instanceof Error))throw i;const o=clarifyErrorMessage(i,e.lastAsyncifyStackSource?.stack);if(e.lastAsyncifyStackSource&&(i.cause=e.lastAsyncifyStackSource),t.hasListeners()){t.dispatchEvent(new ErrorEvent("error",{error:i,message:o}));return}throw isExitCodeZero(i)||showCriticalErrorBox(o),i}}}return t}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(e,t){if(e.message==="unreachable"){let s=UNREACHABLE_ERROR;t||(s+=`
21
+ `),[])}logMessage(t,...r){for(const s of this.handlers)s(t,...r)}log(t,...r){this.logMessage({message:t,severity:void 0,prefix:"JavaScript",raw:!1},...r)}debug(t,...r){this.logMessage({message:t,severity:"Debug",prefix:"JavaScript",raw:!1},...r)}info(t,...r){this.logMessage({message:t,severity:"Info",prefix:"JavaScript",raw:!1},...r)}warn(t,...r){this.logMessage({message:t,severity:"Warn",prefix:"JavaScript",raw:!1},...r)}error(t,...r){this.logMessage({message:t,severity:"Error",prefix:"JavaScript",raw:!1},...r)}}const getDefaultHandlers=()=>{try{if(process.env.NODE_ENV==="test")return[logToMemory,logEvent]}catch{}return[logToMemory,logToConsole,logEvent]},logger=new Logger(getDefaultHandlers()),prepareLogMessage=e=>e.replace(/\t/g,""),formatLogEntry=(e,t,r)=>{const s=new Date,i=new Intl.DateTimeFormat("en-GB",{year:"numeric",month:"short",day:"2-digit",timeZone:"UTC"}).format(s).replace(/ /g,"-"),n=new Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZone:"UTC",timeZoneName:"short"}).format(s),o=i+" "+n;return e=prepareLogMessage(e),`[${o}] ${r} ${t}: ${e}`};var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(e,t,r,s)=>{for(var i=s>1?void 0:s?__getOwnPropDesc(t,r):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(i=(s?o(t,r,i):o(i))||i);return s&&i&&__defProp(t,r,i),i};const _FSHelpers=class d{static readFileAsText(t,r){return new TextDecoder().decode(d.readFileAsBuffer(t,r))}static readFileAsBuffer(t,r){return t.readFile(r)}static writeFile(t,r,s){t.writeFile(r,s)}static unlink(t,r){t.unlink(r)}static mv(t,r,s){try{const i=t.lookupPath(r).node.mount,n=d.fileExists(t,s)?t.lookupPath(s).node.mount:t.lookupPath(dirname(s)).node.mount;i.mountpoint!==n.mountpoint?(d.copyRecursive(t,r,s),d.rmdir(t,r,{recursive:!0})):t.rename(r,s)}catch(i){const n=getEmscriptenFsError(i);throw n?new Error(`Could not move ${r} to ${s}: ${n}`,{cause:i}):i}}static rmdir(t,r,s={recursive:!0}){s?.recursive&&d.listFiles(t,r).forEach(i=>{const n=`${r}/${i}`;d.isDir(t,n)?d.rmdir(t,n,s):d.unlink(t,n)}),t.rmdir(r)}static listFiles(t,r,s={prependPath:!1}){if(!d.fileExists(t,r))return[];try{const i=t.readdir(r).filter(n=>n!=="."&&n!=="..");if(s.prependPath){const n=r.replace(/\/$/,"");return i.map(o=>`${n}/${o}`)}return i}catch(i){return logger.error(i,{path:r}),[]}}static isDir(t,r){return d.fileExists(t,r)?t.isDir(t.lookupPath(r).node.mode):!1}static fileExists(t,r){try{return t.lookupPath(r),!0}catch{return!1}}static mkdir(t,r){t.mkdirTree(r)}static copyRecursive(t,r,s){const i=t.lookupPath(r).node;if(t.isDir(i.mode)){t.mkdirTree(s);const n=t.readdir(r).filter(o=>o!=="."&&o!=="..");for(const o of n)d.copyRecursive(t,joinPaths(r,o),joinPaths(s,o))}else t.writeFile(s,t.readFile(r))}};__decorateClass([rethrowFileSystemError('Could not read "{path}"')],_FSHelpers,"readFileAsText",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],_FSHelpers,"readFileAsBuffer",1);__decorateClass([rethrowFileSystemError('Could not write to "{path}"')],_FSHelpers,"writeFile",1);__decorateClass([rethrowFileSystemError('Could not unlink "{path}"')],_FSHelpers,"unlink",1);__decorateClass([rethrowFileSystemError('Could not remove directory "{path}"')],_FSHelpers,"rmdir",1);__decorateClass([rethrowFileSystemError('Could not list files in "{path}"')],_FSHelpers,"listFiles",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],_FSHelpers,"isDir",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],_FSHelpers,"fileExists",1);__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],_FSHelpers,"mkdir",1);__decorateClass([rethrowFileSystemError('Could not copy files from "{path}"')],_FSHelpers,"copyRecursive",1);let FSHelpers=_FSHelpers;const responseTexts={500:"Internal Server Error",502:"Bad Gateway",404:"Not Found",403:"Forbidden",401:"Unauthorized",400:"Bad Request",301:"Moved Permanently",302:"Found",307:"Temporary Redirect",308:"Permanent Redirect",204:"No Content",201:"Created",200:"OK"};class PHPResponse{constructor(t,r,s,i="",n=0){this.httpStatusCode=t,this.headers=r,this.bytes=s,this.exitCode=n,this.errors=i}static forHttpCode(t,r=""){return new PHPResponse(t,{},new TextEncoder().encode(r||responseTexts[t]||""))}static fromRawData(t){return new PHPResponse(t.httpStatusCode,t.headers,t.bytes,t.errors,t.exitCode)}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}const loadedRuntimes=new Map;function getLoadedRuntime(e){return loadedRuntimes.get(e)}(function(){return typeof process<"u"&&process.release?.name==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends Event{constructor(t,r={}){super(t),this[kError]=r.error===void 0?null:r.error,this[kMessage]=r.message===void 0?"":r.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent2.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent2.prototype,"message",{enumerable:!0});const ErrorEvent=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:ErrorEvent2;function isExitCodeZero(e){return e instanceof Error?"exitCode"in e&&e?.exitCode===0||e?.name==="ExitStatus"&&"status"in e&&e.status===0:!1}class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(t,r){++this.listenersCount,super.addEventListener(t,r)}removeEventListener(t,r){--this.listenersCount,super.removeEventListener(t,r)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(e){const t=new UnhandledRejectionsTarget;for(const r in e.wasmExports)if(typeof e.wasmExports[r]=="function"){const s=e.wasmExports[r];e.wasmExports[r]=function(...i){try{return s(...i)}catch(n){if(!(n instanceof Error))throw n;const o=clarifyErrorMessage(n,e.lastAsyncifyStackSource?.stack);if(e.lastAsyncifyStackSource&&(n.cause=e.lastAsyncifyStackSource),t.hasListeners()){t.dispatchEvent(new ErrorEvent("error",{error:n,message:o}));return}throw isExitCodeZero(n)||showCriticalErrorBox(o),n}}}return t}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(e,t){if(e.message==="unreachable"){let r=UNREACHABLE_ERROR;t||(r+=`
22
22
 
23
23
  This stack trace is lacking. For a better one initialize
24
24
  the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
25
25
 
26
- `),functionsMaybeMissingFromAsyncify=extractPHPFunctionsFromStack(t||e.stack||"");for(const r of functionsMaybeMissingFromAsyncify)s+=` * ${r}
27
- `;return s}return e.message}const UNREACHABLE_ERROR=`
26
+ `),functionsMaybeMissingFromAsyncify=extractPHPFunctionsFromStack(t||e.stack||"");for(const s of functionsMaybeMissingFromAsyncify)r+=` * ${s}
27
+ `;return r}return e.message}const UNREACHABLE_ERROR=`
28
28
  "unreachable" WASM instruction executed.
29
29
 
30
30
  The typical reason is a PHP function missing from the ASYNCIFY_ONLY
@@ -52,7 +52,7 @@ CLI option:
52
52
  ${eol}
53
53
  ${bold} WASM ERROR${reset}${redBg}`);for(const t of e.split(`
54
54
  `))logger.log(`${eol} ${t} `);logger.log(`${reset}`)}}function extractPHPFunctionsFromStack(e){try{const t=e.split(`
55
- `).slice(1).map(s=>{const r=s.trim().substring(3).split(" ");return{fn:r.length>=2?r[0]:"<unknown>",isWasm:s.includes("wasm://")}}).filter(({fn:s,isWasm:r})=>r&&!s.startsWith("dynCall_")&&!s.startsWith("invoke_")).map(({fn:s})=>s);return Array.from(new Set(t))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(t,s,r){super(t),this.response=s,this.source=r}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php";class PHP{constructor(e){this.#webSapiInitialized=!1,this.#wasmErrorsTarget=null,this.#eventListeners=new Map,this.#messageListeners=[],this.semaphore=new Semaphore({concurrency:1}),e!==void 0&&this.initializeRuntime(e)}#sapiName;#webSapiInitialized;#wasmErrorsTarget;#eventListeners;#messageListeners;addEventListener(e,t){this.#eventListeners.has(e)||this.#eventListeners.set(e,new Set),this.#eventListeners.get(e).add(t)}removeEventListener(e,t){this.#eventListeners.get(e)?.delete(t)}dispatchEvent(e){const t=this.#eventListeners.get(e.type);if(t)for(const s of t)s(e)}onMessage(e){this.#messageListeners.push(e)}async setSpawnHandler(handler){typeof handler=="string"&&(handler=createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}pathToInternalUrl(e){return this.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.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,this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[PHP_INI_PATH]),this.fileExists(PHP_INI_PATH)||this.writeFile(PHP_INI_PATH,["auto_prepend_file="+AUTO_PREPEND_SCRIPT,"memory_limit=256M","ignore_repeated_errors = 1","error_reporting = E_ALL","display_errors = 1","html_errors = 1","display_startup_errors = On","log_errors = 1","always_populate_raw_post_data = -1","upload_max_filesize = 2000M","post_max_size = 2000M","disable_functions = curl_exec,curl_multi_exec","allow_url_fopen = Off","allow_url_include = Off","session.save_path = /home/web_user","implicit_flush = 1","output_buffering = 0","max_execution_time = 0","max_input_time = -1"].join(`
55
+ `).slice(1).map(r=>{const s=r.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:r.includes("wasm://")}}).filter(({fn:r,isWasm:s})=>s&&!r.startsWith("dynCall_")&&!r.startsWith("invoke_")).map(({fn:r})=>r);return Array.from(new Set(t))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(t,r,s){super(t),this.response=r,this.source=s}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php";class PHP{constructor(e){this.#webSapiInitialized=!1,this.#wasmErrorsTarget=null,this.#eventListeners=new Map,this.#messageListeners=[],this.semaphore=new Semaphore({concurrency:1}),e!==void 0&&this.initializeRuntime(e)}#sapiName;#webSapiInitialized;#wasmErrorsTarget;#eventListeners;#messageListeners;addEventListener(e,t){this.#eventListeners.has(e)||this.#eventListeners.set(e,new Set),this.#eventListeners.get(e).add(t)}removeEventListener(e,t){this.#eventListeners.get(e)?.delete(t)}dispatchEvent(e){const t=this.#eventListeners.get(e.type);if(t)for(const r of t)r(e)}onMessage(e){this.#messageListeners.push(e)}async setSpawnHandler(handler){typeof handler=="string"&&(handler=createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}pathToInternalUrl(e){return this.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.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,this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[PHP_INI_PATH]),this.fileExists(PHP_INI_PATH)||this.writeFile(PHP_INI_PATH,["auto_prepend_file="+AUTO_PREPEND_SCRIPT,"memory_limit=256M","ignore_repeated_errors = 1","error_reporting = E_ALL","display_errors = 1","html_errors = 1","display_startup_errors = On","log_errors = 1","always_populate_raw_post_data = -1","upload_max_filesize = 2000M","post_max_size = 2000M","disable_functions = curl_exec,curl_multi_exec","allow_url_fopen = Off","allow_url_include = Off","session.save_path = /home/web_user","implicit_flush = 1","output_buffering = 0","max_execution_time = 0","max_input_time = -1"].join(`
56
56
  `)),this.fileExists(AUTO_PREPEND_SCRIPT)||this.writeFile(AUTO_PREPEND_SCRIPT,`<?php
57
57
  // Define constants set via defineConstant() calls
58
58
  if(file_exists('/internal/shared/consts.json')) {
@@ -67,21 +67,19 @@ ${bold} WASM ERROR${reset}${redBg}`);for(const t of e.split(`
67
67
  foreach (glob('/internal/shared/preload/*.php') as $file) {
68
68
  require_once $file;
69
69
  }
70
- `),t.onMessage=async s=>{for(const r of this.#messageListeners){const n=await r(s);if(n)return n}return""},this.#wasmErrorsTarget=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?");this.#sapiName=e}chdir(e){this[__private__dont__use].FS.chdir(e)}async request(e){if(logger.warn("PHP.request() is deprecated. Please use new PHPRequestHandler() instead."),!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(e)}async run(e){const t=await this.semaphore.acquire();let s;try{if(this.#webSapiInitialized||(this.#initWebRuntime(),this.#webSapiInitialized=!0),e.scriptPath&&!this.fileExists(e.scriptPath))throw new Error(`The script path "${e.scriptPath}" does not exist.`);this.#setRelativeRequestUri(e.relativeUri||""),this.#setRequestMethod(e.method||"GET");const r=normalizeHeaders(e.headers||{}),n=r.host||"example.com:443",i=this.#inferPortFromHostAndProtocol(n,e.protocol||"http");this.#setRequestHost(n),this.#setRequestPort(i),this.#setRequestHeaders(r),e.body&&(s=this.#setRequestBody(e.body)),typeof e.code=="string"?(this.writeFile("/internal/eval.php",e.code),this.#setScriptPath("/internal/eval.php")):this.#setScriptPath(e.scriptPath||"");const o=this.#prepareServerEntries(e.$_SERVER,r,i);for(const l in o)this.#setServerGlobalEntry(l,o[l]);const a=e.env||{};for(const l in a)this.#setEnv(l,a[l]);const c=await this.#handleRequest();if(c.exitCode!==0){logger.warn("PHP.run() output was:",c.text);const l=new PHPExecutionFailureError(`PHP.run() failed with exit code ${c.exitCode} and the following output: `+c.errors,c,"request");throw logger.error(l),l}return c}catch(r){throw this.dispatchEvent({type:"request.error",error:r,source:r.source??"php-wasm"}),r}finally{try{s&&this[__private__dont__use].free(s)}finally{t(),this.dispatchEvent({type:"request.end"})}}}#prepareServerEntries(e,t,s){const r={...e||{}};r.HTTPS=r.HTTPS||s===443?"on":"off";for(const n in t){let i="HTTP_";["content-type","content-length"].includes(n.toLowerCase())&&(i=""),r[`${i}${n.toUpperCase().replace(/-/g,"_")}`]=t[n]}return r}#initWebRuntime(){this[__private__dont__use].ccall("php_wasm_init",null,[],[])}#getResponseHeaders(){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)),s={};for(const r of t.headers){if(!r.includes(": "))continue;const n=r.indexOf(": "),i=r.substring(0,n).toLowerCase(),o=r.substring(n+2);i in s||(s[i]=[]),s[i].push(o)}return{headers:s,httpStatusCode:t.status}}#setRelativeRequestUri(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])}}#setRequestHost(e){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[e])}#setRequestPort(e){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[e])}#inferPortFromHostAndProtocol(e,t){let s;try{s=parseInt(new URL(e).port,10)}catch{}return(!s||isNaN(s)||s===80)&&(s=t==="https"?443:80),s}#setRequestMethod(e){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[e])}#setRequestHeaders(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)])}#setRequestBody(e){let t,s;typeof e=="string"?(logger.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"),s=this[__private__dont__use].lengthBytesUTF8(e),t=s+1):(s=e.byteLength,t=e.byteLength);const r=this[__private__dont__use].malloc(t);if(!r)throw new Error("Could not allocate memory for the request body.");return typeof e=="string"?this[__private__dont__use].stringToUTF8(e,r,t+1):this[__private__dont__use].HEAPU8.set(e,r),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[r]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[s]),r}#setScriptPath(e){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[e])}#setServerGlobalEntry(e,t){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[e,t])}#setEnv(e,t){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[e,t])}defineConstant(e,t){let s={};try{s=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...s,[e]:t}))}async#handleRequest(){let e,t;try{e=await new Promise((n,i)=>{t=a=>{logger.error(a),logger.error(a.error);const c=new Error("Rethrown");c.cause=a.error,c.betterMessage=a.message,i(c)},this.#wasmErrorsTarget?.addEventListener("error",t);const o=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return o instanceof Promise?o.then(n,i):n(o)})}catch(n){for(const c in this)typeof this[c]=="function"&&(this[c]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify();const i=n,o="betterMessage"in i?i.betterMessage:i.message,a=new Error(o);throw a.cause=i,logger.error(a),a}finally{this.#wasmErrorsTarget?.removeEventListener("error",t)}const{headers:s,httpStatusCode:r}=this.#getResponseHeaders();return new PHPResponse(e===0?r:500,s,this.readFileAsBuffer("/internal/stdout"),this.readFileAsText("/internal/stderr"),e)}mkdir(e){return FSHelpers.mkdir(this[__private__dont__use].FS,e)}mkdirTree(e){return FSHelpers.mkdir(this[__private__dont__use].FS,e)}readFileAsText(e){return FSHelpers.readFileAsText(this[__private__dont__use].FS,e)}readFileAsBuffer(e){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,e)}writeFile(e,t){return FSHelpers.writeFile(this[__private__dont__use].FS,e,t)}unlink(e){return FSHelpers.unlink(this[__private__dont__use].FS,e)}mv(e,t){return FSHelpers.mv(this[__private__dont__use].FS,e,t)}rmdir(e,t={recursive:!0}){return FSHelpers.rmdir(this[__private__dont__use].FS,e,t)}listFiles(e,t={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,e,t)}isDir(e){return FSHelpers.isDir(this[__private__dont__use].FS,e)}fileExists(e){return FSHelpers.fileExists(this[__private__dont__use].FS,e)}hotSwapPHPRuntime(e,t){const s=this[__private__dont__use].FS;try{this.exit()}catch{}this.initializeRuntime(e),this.#sapiName&&this.setSapiName(this.#sapiName),t&&copyFS(s,this[__private__dont__use].FS,t)}async mount(e,t){return await t(this,this[__private__dont__use].FS,e)}async cli(e){for(const t of e)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[t]);try{return await this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}catch(t){if(isExitCodeZero(t))return 0;throw t}}setSkipShebang(e){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[e?1:0])}exit(e=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(e)}catch{}this.#webSapiInitialized=!1,this.#wasmErrorsTarget=null,delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}[Symbol.dispose](){this.#webSapiInitialized&&this.exit(0)}}function normalizeHeaders(e){const t={};for(const s in e)t[s.toLowerCase()]=e[s];return t}function copyFS(e,t,s){let r;try{r=e.lookupPath(s)}catch{return}if(!("contents"in r.node))return;if(!e.isDir(r.node.mode)){t.writeFile(s,e.readFile(s));return}t.mkdirTree(s);const n=e.readdir(s).filter(i=>i!=="."&&i!=="..");for(const i of n)copyFS(e,t,joinPaths(s,i))}const{hasOwnProperty}=Object.prototype,encode=(e,t={})=>{typeof t=="string"&&(t={section:t}),t.align=t.align===!0,t.newline=t.newline===!0,t.sort=t.sort===!0,t.whitespace=t.whitespace===!0||t.align===!0,t.platform=t.platform||typeof process<"u"&&process.platform,t.bracketedArray=t.bracketedArray!==!1;const s=t.platform==="win32"?`\r
71
- `:`
72
- `,r=t.whitespace?" = ":"=",n=[],i=t.sort?Object.keys(e).sort():Object.keys(e);let o=0;t.align&&(o=safe(i.filter(l=>e[l]===null||Array.isArray(e[l])||typeof e[l]!="object").map(l=>Array.isArray(e[l])?`${l}[]`:l).concat([""]).reduce((l,d)=>safe(l).length>=safe(d).length?l:d)).length);let a="";const c=t.bracketedArray?"[]":"";for(const l of i){const d=e[l];if(d&&Array.isArray(d))for(const p of d)a+=safe(`${l}${c}`).padEnd(o," ")+r+safe(p)+s;else d&&typeof d=="object"?n.push(l):a+=safe(l).padEnd(o," ")+r+safe(d)+s}t.section&&a.length&&(a="["+safe(t.section)+"]"+(t.newline?s+s:s)+a);for(const l of n){const d=splitSections(l,".").join("\\."),p=(t.section?t.section+".":"")+d,f=encode(e[l],{...t,section:p});a.length&&f.length&&(a+=s),a+=f}return a};function splitSections(e,t){var s=0,r=0,n=0,i=[];do if(n=e.indexOf(t,s),n!==-1){if(s=n+t.length,n>0&&e[n-1]==="\\")continue;i.push(e.slice(r,n)),r=n+t.length}while(n!==-1);return i.push(e.slice(r)),i}const decode=(e,t={})=>{t.bracketedArray=t.bracketedArray!==!1;const s=Object.create(null);let r=s,n=null;const i=/^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i,o=e.split(/[\r\n]+/g),a={};for(const l of o){if(!l||l.match(/^\s*[;#]/)||l.match(/^\s*$/))continue;const d=l.match(i);if(!d)continue;if(d[1]!==void 0){if(n=unsafe(d[1]),n==="__proto__"){r=Object.create(null);continue}r=s[n]=s[n]||Object.create(null);continue}const p=unsafe(d[2]);let f;t.bracketedArray?f=p.length>2&&p.slice(-2)==="[]":(a[p]=(a?.[p]||0)+1,f=a[p]>1);const u=f?p.slice(0,-2):p;if(u==="__proto__")continue;const m=d[3]?unsafe(d[4]):!0,_=m==="true"||m==="false"||m==="null"?JSON.parse(m):m;f&&(hasOwnProperty.call(r,u)?Array.isArray(r[u])||(r[u]=[r[u]]):r[u]=[]),Array.isArray(r[u])?r[u].push(_):r[u]=_}const c=[];for(const l of Object.keys(s)){if(!hasOwnProperty.call(s,l)||typeof s[l]!="object"||Array.isArray(s[l]))continue;const d=splitSections(l,".");r=s;const p=d.pop(),f=p.replace(/\\\./g,".");for(const u of d)u!=="__proto__"&&((!hasOwnProperty.call(r,u)||typeof r[u]!="object")&&(r[u]=Object.create(null)),r=r[u]);r===s&&f===p||(r[f]=s[l],c.push(l))}for(const l of c)delete s[l];return s},isQuoted=e=>e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"),safe=e=>typeof e!="string"||e.match(/[=\r\n]/)||e.match(/^\[/)||e.length>1&&isQuoted(e)||e!==e.trim()?JSON.stringify(e):e.split(";").join("\\;").split("#").join("\\#"),unsafe=e=>{if(e=(e||"").trim(),isQuoted(e)){e.charAt(0)==="'"&&(e=e.slice(1,-1));try{e=JSON.parse(e)}catch{}}else{let t=!1,s="";for(let r=0,n=e.length;r<n;r++){const i=e.charAt(r);if(t)"\\;#".indexOf(i)!==-1?s+=i:s+="\\"+i,t=!1;else{if(";#".indexOf(i)!==-1)break;i==="\\"?t=!0:s+=i}}return t&&(s+="\\"),s.trim()}return e};var ini={parse:decode,decode,stringify:encode,encode,safe,unsafe};async function setPhpIniEntries(e,t){const s=ini.parse(await e.readFileAsText(PHP_INI_PATH));for(const[r,n]of Object.entries(t))n==null?delete s[r]:s[r]=n;await e.writeFile(PHP_INI_PATH,ini.stringify(s))}async function withPHPIniValues(e,t,s){const r=await e.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(e,t),await s()}finally{await e.writeFile(PHP_INI_PATH,r)}}class HttpCookieStore{constructor(){this.cookies={}}rememberCookiesFromResponseHeaders(t){if(t?.["set-cookie"])for(const s of t["set-cookie"])try{if(!s.includes("="))continue;const r=s.indexOf("="),n=s.substring(0,r),i=s.substring(r+1).split(";")[0];this.cookies[n]=i}catch(r){logger.error(r)}}getCookieRequestHeader(){const t=[];for(const s in this.cookies)t.push(`${s}=${this.cookies[s]}`);return t.join("; ")}}ReadableStream.prototype[Symbol.asyncIterator]||(ReadableStream.prototype[Symbol.asyncIterator]=async function*(){const e=this.getReader();try{for(;;){const{done:t,value:s}=await e.read();if(t)return;yield s}}finally{e.releaseLock()}},ReadableStream.prototype.iterate=ReadableStream.prototype[Symbol.asyncIterator]);class MaxPhpInstancesError extends Error{constructor(t){super(`Requested more concurrent PHP instances than the limit (${t}).`),this.name=this.constructor.name}}class PHPProcessManager{constructor(t){this.primaryIdle=!0,this.nextInstance=null,this.allInstances=[],this.maxPhpInstances=t?.maxPhpInstances??5,this.phpFactory=t?.phpFactory,this.primaryPhp=t?.primaryPhp,this.semaphore=new Semaphore({concurrency:this.maxPhpInstances,timeout:t?.timeout||5e3})}async getPrimaryPhp(){if(!this.phpFactory&&!this.primaryPhp)throw new Error("phpFactory or primaryPhp must be set before calling getPrimaryPhp().");if(!this.primaryPhp){const t=await this.spawn({isPrimary:!0});this.primaryPhp=t.php}return this.primaryPhp}async acquirePHPInstance(){if(this.primaryIdle)return this.primaryIdle=!1,{php:await this.getPrimaryPhp(),reap:()=>this.primaryIdle=!0};const t=this.nextInstance||this.spawn({isPrimary:!1});return this.semaphore.remaining>0?this.nextInstance=this.spawn({isPrimary:!1}):this.nextInstance=null,await t}spawn(t){if(t.isPrimary&&this.allInstances.length>0)throw new Error("Requested spawning a primary PHP instance when another primary instance already started spawning.");const s=this.doSpawn(t);this.allInstances.push(s);const r=()=>{this.allInstances=this.allInstances.filter(n=>n!==s)};return s.catch(n=>{throw r(),n}).then(n=>({...n,reap:()=>{r(),n.reap()}}))}async doSpawn(t){let s;try{s=await this.semaphore.acquire()}catch(r){throw r instanceof AcquireTimeoutError?new MaxPhpInstancesError(this.maxPhpInstances):r}try{const r=await this.phpFactory(t);return{php:r,reap(){r.exit(),s()}}}catch(r){throw s(),r}}async[Symbol.asyncDispose](){this.primaryPhp&&this.primaryPhp.exit(),await Promise.all(this.allInstances.map(t=>t.then(({reap:s})=>s())))}}const DEFAULT_BASE_URL="http://example.com";function toRelativeUrl(e){return e.toString().substring(e.origin.length)}function removePathPrefix(e,t){return!t||!e.startsWith(t)?e:e.substring(t.length)}function ensurePathPrefix(e,t){return!t||e.startsWith(t)?e:t+e}async function encodeAsMultipart(e){const t=`----${Math.random().toString(36).slice(2)}`,s=`multipart/form-data; boundary=${t}`,r=new TextEncoder,n=[];for(const[c,l]of Object.entries(e))n.push(`--${t}\r
73
- `),n.push(`Content-Disposition: form-data; name="${c}"`),l instanceof File&&n.push(`; filename="${l.name}"`),n.push(`\r
74
- `),l instanceof File&&(n.push("Content-Type: application/octet-stream"),n.push(`\r
75
- `)),n.push(`\r
76
- `),l instanceof File?n.push(await fileToUint8Array(l)):n.push(l),n.push(`\r
77
- `);n.push(`--${t}--\r
78
- `);const i=n.reduce((c,l)=>c+l.length,0),o=new Uint8Array(i);let a=0;for(const c of n)o.set(typeof c=="string"?r.encode(c):c,a),a+=c.length;return{bytes:o,contentType:s}}function fileToUint8Array(e){return new Promise(t=>{const s=new FileReader;s.onload=()=>{t(new Uint8Array(s.result))},s.readAsArrayBuffer(e)})}const _default="application/octet-stream",asx="video/x-ms-asf",atom="application/atom+xml",avi="video/x-msvideo",avif="image/avif",bin="application/octet-stream",bmp="image/x-ms-bmp",cco="application/x-cocoa",css="text/css",data="application/octet-stream",deb="application/octet-stream",der="application/x-x509-ca-cert",dmg="application/octet-stream",doc="application/msword",docx="application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot="application/vnd.ms-fontobject",flv="video/x-flv",gif="image/gif",gz="application/gzip",hqx="application/mac-binhex40",htc="text/x-component",html="text/html",ico="image/x-icon",iso="application/octet-stream",jad="text/vnd.sun.j2me.app-descriptor",jar="application/java-archive",jardiff="application/x-java-archive-diff",jng="image/x-jng",jnlp="application/x-java-jnlp-file",jpg="image/jpeg",jpeg="image/jpeg",js="application/javascript",json="application/json",kml="application/vnd.google-earth.kml+xml",kmz="application/vnd.google-earth.kmz",m3u8="application/vnd.apple.mpegurl",m4a="audio/x-m4a",m4v="video/x-m4v",md="text/plain",mid="audio/midi",mml="text/mathml",mng="video/x-mng",mov="video/quicktime",mp3="audio/mpeg",mp4="video/mp4",mpeg="video/mpeg",msi="application/octet-stream",odg="application/vnd.oasis.opendocument.graphics",odp="application/vnd.oasis.opendocument.presentation",ods="application/vnd.oasis.opendocument.spreadsheet",odt="application/vnd.oasis.opendocument.text",ogg="audio/ogg",otf="font/otf",pdf="application/pdf",pl="application/x-perl",png="image/png",ppt="application/vnd.ms-powerpoint",pptx="application/vnd.openxmlformats-officedocument.presentationml.presentation",prc="application/x-pilot",ps="application/postscript",ra="audio/x-realaudio",rar="application/x-rar-compressed",rpm="application/x-redhat-package-manager",rss="application/rss+xml",rtf="application/rtf",run="application/x-makeself",sea="application/x-sea",sit="application/x-stuffit",svg="image/svg+xml",swf="application/x-shockwave-flash",tcl="application/x-tcl",tar="application/x-tar",tif="image/tiff",ts="video/mp2t",ttf="font/ttf",txt="text/plain",wasm="application/wasm",wbmp="image/vnd.wap.wbmp",webm="video/webm",webp="image/webp",wml="text/vnd.wap.wml",wmlc="application/vnd.wap.wmlc",wmv="video/x-ms-wmv",woff="font/woff",woff2="font/woff2",xhtml="application/xhtml+xml",xls="application/vnd.ms-excel",xlsx="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml="text/xml",xpi="application/x-xpinstall",xspf="application/xspf+xml",zip="application/zip",mimeTypes={_default,"3gpp":"video/3gpp","7z":"application/x-7z-compressed",asx,atom,avi,avif,bin,bmp,cco,css,data,deb,der,dmg,doc,docx,eot,flv,gif,gz,hqx,htc,html,ico,iso,jad,jar,jardiff,jng,jnlp,jpg,jpeg,js,json,kml,kmz,m3u8,m4a,m4v,md,mid,mml,mng,mov,mp3,mp4,mpeg,msi,odg,odp,ods,odt,ogg,otf,pdf,pl,png,ppt,pptx,prc,ps,ra,rar,rpm,rss,rtf,run,sea,sit,svg,swf,tcl,tar,tif,ts,ttf,txt,wasm,wbmp,webm,webp,wml,wmlc,wmv,woff,woff2,xhtml,xls,xlsx,xml,xpi,xspf,zip};class PHPRequestHandler{#e;#r;#a;#s;#n;#t;#i;#o;constructor(t){const{documentRoot:s="/www/",absoluteUrl:r=typeof location=="object"?location?.href:"",rewriteRules:n=[]}=t;"processManager"in t?this.processManager=t.processManager:this.processManager=new PHPProcessManager({phpFactory:async a=>{const c=await t.phpFactory({...a,requestHandler:this});return c.requestHandler=this,c},maxPhpInstances:t.maxPhpInstances}),this.#o=new HttpCookieStore,this.#e=s;const i=new URL(r);this.#a=i.hostname,this.#s=i.port?Number(i.port):i.protocol==="https:"?443:80,this.#r=(i.protocol||"").replace(":","");const o=this.#s!==443&&this.#s!==80;this.#n=[this.#a,o?`:${this.#s}`:""].join(""),this.#t=i.pathname.replace(/\/+$/,""),this.#i=[`${this.#r}://`,this.#n,this.#t].join(""),this.rewriteRules=n}async getPrimaryPhp(){return await this.processManager.getPrimaryPhp()}pathToInternalUrl(t){return`${this.absoluteUrl}${t}`}internalUrlToPath(t){const s=new URL(t);return s.pathname.startsWith(this.#t)&&(s.pathname=s.pathname.slice(this.#t.length)),toRelativeUrl(s)}get absoluteUrl(){return this.#i}get documentRoot(){return this.#e}async request(t){const s=t.url.startsWith("http://")||t.url.startsWith("https://"),r=new URL(t.url.split("#")[0],s?void 0:DEFAULT_BASE_URL),n=applyRewriteRules(removePathPrefix(decodeURIComponent(r.pathname),this.#t),this.rewriteRules),i=joinPaths(this.#e,n);return seemsLikeAPHPRequestHandlerPath(i)?this.#c(t,r):this.#l(await this.processManager.getPrimaryPhp(),i)}#l(t,s){if(!t.fileExists(s))return new PHPResponse(404,{"x-file-type":["static"]},new TextEncoder().encode("404 File not found"));const r=t.readFileAsBuffer(s);return new PHPResponse(200,{"content-length":[`${r.byteLength}`],"content-type":[inferMimeType(s)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},r)}async#c(t,s){let r;try{r=await this.processManager.acquirePHPInstance()}catch(n){return n instanceof MaxPhpInstancesError?PHPResponse.forHttpCode(502):PHPResponse.forHttpCode(500)}try{return await this.#d(r.php,t,s)}finally{r.reap()}}async#d(t,s,r){let n="GET";const i={host:this.#n,...normalizeHeaders(s.headers||{}),cookie:this.#o.getCookieRequestHeader()};let o=s.body;if(typeof o=="object"&&!(o instanceof Uint8Array)){n="POST";const{bytes:c,contentType:l}=await encodeAsMultipart(o);o=c,i["content-type"]=l}let a;try{a=this.#p(t,decodeURIComponent(r.pathname))}catch{return PHPResponse.forHttpCode(404)}try{const c=await t.run({relativeUri:ensurePathPrefix(toRelativeUrl(r),this.#t),protocol:this.#r,method:s.method||n,$_SERVER:{REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:this.#e,HTTPS:this.#i.startsWith("https://")?"on":""},body:o,scriptPath:a,headers:i});return this.#o.rememberCookiesFromResponseHeaders(c.headers),c}catch(c){const l=c;if(l?.response)return l.response;throw c}}#p(t,s){let r=removePathPrefix(s,this.#t);r=applyRewriteRules(r,this.rewriteRules),r.includes(".php")?r=r.split(".php")[0]+".php":t.isDir(`${this.#e}${r}`)?(r.endsWith("/")||(r=`${r}/`),r=`${r}index.php`):r="/index.php";let n=`${this.#e}${r}`;if(t.fileExists(n)||(n=`${this.#e}/index.php`),t.fileExists(n))return n;throw new Error(`File not found: ${n}`)}}function inferMimeType(e){const t=e.split(".").pop();return mimeTypes[t]||mimeTypes._default}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 s of t)if(new RegExp(s.match).test(e))return e.replace(s.match,s.replacement);return e}function rotatePHPRuntime({php:e,cwd:t,recreateRuntime:s,maxRequests:r=400}){let n=0;async function i(){if(++n<r)return;n=0;const o=await e.semaphore.acquire();try{e.hotSwapPHPRuntime(await s(),t)}finally{o()}}return e.addEventListener("request.end",i),function(){e.removeEventListener("request.end",i)}}async function writeFiles(e,t,s,{rmRoot:r=!1}={}){r&&await e.isDir(t)&&await e.rmdir(t,{recursive:!0});for(const[n,i]of Object.entries(s)){const o=joinPaths(t,n);await e.fileExists(dirname(o))||await e.mkdir(dirname(o)),i instanceof Uint8Array||typeof i=="string"?await e.writeFile(o,i):await writeFiles(e,o,i)}}function proxyFileSystem(e,t,s){const r=Object.getOwnPropertySymbols(e)[0];for(const n of s)t.fileExists(n)||t.mkdir(n),e.fileExists(n)||e.mkdir(n),t[r].FS.mount(t[r].PROXYFS,{root:n,fs:e[r].FS},n)}async function bootWordPress(e){async function t(n,i){const o=new PHP(await e.createPhpRuntime());return e.sapiName&&o.setSapiName(e.sapiName),n&&(o.requestHandler=n),e.phpIniEntries&&setPhpIniEntries(o,e.phpIniEntries),i?(await setupPlatformLevelMuPlugins(o),await writeFiles(o,"/",e.createFiles||{}),await preloadPhpInfoRoute(o,joinPaths(new URL(e.siteUrl).pathname,"phpinfo.php"))):proxyFileSystem(await n.getPrimaryPhp(),o,["/tmp",n.documentRoot,"/internal/shared"]),e.spawnHandler&&await o.setSpawnHandler(e.spawnHandler(n.processManager)),rotatePHPRuntime({php:o,cwd:n.documentRoot,recreateRuntime:e.createPhpRuntime,maxRequests:400}),o}const s=new PHPRequestHandler({phpFactory:async({isPrimary:n})=>t(s,n),documentRoot:e.documentRoot||"/wordpress",absoluteUrl:e.siteUrl,rewriteRules:wordPressRewriteRules}),r=await s.getPrimaryPhp();if(e.hooks?.beforeWordPressFiles&&await e.hooks.beforeWordPressFiles(r),e.wordPressZip&&await unzipWordPress(r,await e.wordPressZip),e.constants)for(const n in e.constants)r.defineConstant(n,e.constants[n]);if(r.defineConstant("WP_HOME",e.siteUrl),r.defineConstant("WP_SITEURL",e.siteUrl),e.hooks?.beforeDatabaseSetup&&await e.hooks.beforeDatabaseSetup(r),e.sqliteIntegrationPluginZip&&await preloadSqliteIntegration(r,await e.sqliteIntegrationPluginZip),await isWordPressInstalled(r)||await installWordPress(r),!await isWordPressInstalled(r))throw new Error("WordPress installation has failed.");return s}async function isWordPressInstalled(e){return(await e.run({code:`<?php
70
+ `),t.onMessage=async r=>{for(const s of this.#messageListeners){const i=await s(r);if(i)return i}return""},this.#wasmErrorsTarget=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?");this.#sapiName=e}chdir(e){this[__private__dont__use].FS.chdir(e)}async request(e){if(logger.warn("PHP.request() is deprecated. Please use new PHPRequestHandler() instead."),!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(e)}async run(e){const t=await this.semaphore.acquire();let r;try{if(this.#webSapiInitialized||(this.#initWebRuntime(),this.#webSapiInitialized=!0),e.scriptPath&&!this.fileExists(e.scriptPath))throw new Error(`The script path "${e.scriptPath}" does not exist.`);this.#setRelativeRequestUri(e.relativeUri||""),this.#setRequestMethod(e.method||"GET");const s=normalizeHeaders(e.headers||{}),i=s.host||"example.com:443",n=this.#inferPortFromHostAndProtocol(i,e.protocol||"http");this.#setRequestHost(i),this.#setRequestPort(n),this.#setRequestHeaders(s),e.body&&(r=this.#setRequestBody(e.body)),typeof e.code=="string"?(this.writeFile("/internal/eval.php",e.code),this.#setScriptPath("/internal/eval.php")):this.#setScriptPath(e.scriptPath||"");const o=this.#prepareServerEntries(e.$_SERVER,s,n);for(const c in o)this.#setServerGlobalEntry(c,o[c]);const a=e.env||{};for(const c in a)this.#setEnv(c,a[c]);const l=await this.#handleRequest();if(l.exitCode!==0){logger.warn("PHP.run() output was:",l.text);const c=new PHPExecutionFailureError(`PHP.run() failed with exit code ${l.exitCode} and the following output: `+l.errors,l,"request");throw logger.error(c),c}return l}catch(s){throw this.dispatchEvent({type:"request.error",error:s,source:s.source??"php-wasm"}),s}finally{try{r&&this[__private__dont__use].free(r)}finally{t(),this.dispatchEvent({type:"request.end"})}}}#prepareServerEntries(e,t,r){const s={...e||{}};s.HTTPS=s.HTTPS||r===443?"on":"off";for(const i in t){let n="HTTP_";["content-type","content-length"].includes(i.toLowerCase())&&(n=""),s[`${n}${i.toUpperCase().replace(/-/g,"_")}`]=t[i]}return s}#initWebRuntime(){this[__private__dont__use].ccall("php_wasm_init",null,[],[])}#getResponseHeaders(){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 s of t.headers){if(!s.includes(": "))continue;const i=s.indexOf(": "),n=s.substring(0,i).toLowerCase(),o=s.substring(i+2);n in r||(r[n]=[]),r[n].push(o)}return{headers:r,httpStatusCode:t.status}}#setRelativeRequestUri(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])}}#setRequestHost(e){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[e])}#setRequestPort(e){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[e])}#inferPortFromHostAndProtocol(e,t){let r;try{r=parseInt(new URL(e).port,10)}catch{}return(!r||isNaN(r)||r===80)&&(r=t==="https"?443:80),r}#setRequestMethod(e){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[e])}#setRequestHeaders(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)])}#setRequestBody(e){let t,r;typeof e=="string"?(logger.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 s=this[__private__dont__use].malloc(t);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof e=="string"?this[__private__dont__use].stringToUTF8(e,s,t+1):this[__private__dont__use].HEAPU8.set(e,s),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[s]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[r]),s}#setScriptPath(e){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[e])}#setServerGlobalEntry(e,t){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[e,t])}#setEnv(e,t){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[e,t])}defineConstant(e,t){let r={};try{r=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...r,[e]:t}))}async#handleRequest(){let e,t;try{e=await new Promise((i,n)=>{t=a=>{logger.error(a),logger.error(a.error);const l=new Error("Rethrown");l.cause=a.error,l.betterMessage=a.message,n(l)},this.#wasmErrorsTarget?.addEventListener("error",t);const o=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return o instanceof Promise?o.then(i,n):i(o)})}catch(i){for(const l in this)typeof this[l]=="function"&&(this[l]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify();const n=i,o="betterMessage"in n?n.betterMessage:n.message,a=new Error(o);throw a.cause=n,logger.error(a),a}finally{this.#wasmErrorsTarget?.removeEventListener("error",t)}const{headers:r,httpStatusCode:s}=this.#getResponseHeaders();return new PHPResponse(e===0?s:500,r,this.readFileAsBuffer("/internal/stdout"),this.readFileAsText("/internal/stderr"),e)}mkdir(e){return FSHelpers.mkdir(this[__private__dont__use].FS,e)}mkdirTree(e){return FSHelpers.mkdir(this[__private__dont__use].FS,e)}readFileAsText(e){return FSHelpers.readFileAsText(this[__private__dont__use].FS,e)}readFileAsBuffer(e){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,e)}writeFile(e,t){return FSHelpers.writeFile(this[__private__dont__use].FS,e,t)}unlink(e){return FSHelpers.unlink(this[__private__dont__use].FS,e)}mv(e,t){return FSHelpers.mv(this[__private__dont__use].FS,e,t)}rmdir(e,t={recursive:!0}){return FSHelpers.rmdir(this[__private__dont__use].FS,e,t)}listFiles(e,t={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,e,t)}isDir(e){return FSHelpers.isDir(this[__private__dont__use].FS,e)}fileExists(e){return FSHelpers.fileExists(this[__private__dont__use].FS,e)}hotSwapPHPRuntime(e,t){const r=this[__private__dont__use].FS;try{this.exit()}catch{}this.initializeRuntime(e),this.#sapiName&&this.setSapiName(this.#sapiName),t&&copyFS(r,this[__private__dont__use].FS,t)}async mount(e,t){return await t(this,this[__private__dont__use].FS,e)}async cli(e){for(const t of e)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[t]);try{return await this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}catch(t){if(isExitCodeZero(t))return 0;throw t}}setSkipShebang(e){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[e?1:0])}exit(e=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(e)}catch{}this.#webSapiInitialized=!1,this.#wasmErrorsTarget=null,delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}[Symbol.dispose](){this.#webSapiInitialized&&this.exit(0)}}function normalizeHeaders(e){const t={};for(const r in e)t[r.toLowerCase()]=e[r];return t}function copyFS(e,t,r){let s;try{s=e.lookupPath(r)}catch{return}if(!("contents"in s.node))return;if(!e.isDir(s.node.mode)){t.writeFile(r,e.readFile(r));return}t.mkdirTree(r);const i=e.readdir(r).filter(n=>n!=="."&&n!=="..");for(const n of i)copyFS(e,t,joinPaths(r,n))}async function setPhpIniEntries(e,t){const r=parse(await e.readFileAsText(PHP_INI_PATH));for(const[s,i]of Object.entries(t))i==null?delete r[s]:r[s]=i;await e.writeFile(PHP_INI_PATH,stringify(r))}async function withPHPIniValues(e,t,r){const s=await e.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(e,t),await r()}finally{await e.writeFile(PHP_INI_PATH,s)}}class HttpCookieStore{constructor(){this.cookies={}}rememberCookiesFromResponseHeaders(t){if(t?.["set-cookie"])for(const r of t["set-cookie"])try{if(!r.includes("="))continue;const s=r.indexOf("="),i=r.substring(0,s),n=r.substring(s+1).split(";")[0];this.cookies[i]=n}catch(s){logger.error(s)}}getCookieRequestHeader(){const t=[];for(const r in this.cookies)t.push(`${r}=${this.cookies[r]}`);return t.join("; ")}}ReadableStream.prototype[Symbol.asyncIterator]||(ReadableStream.prototype[Symbol.asyncIterator]=async function*(){const e=this.getReader();try{for(;;){const{done:t,value:r}=await e.read();if(t)return;yield r}}finally{e.releaseLock()}},ReadableStream.prototype.iterate=ReadableStream.prototype[Symbol.asyncIterator]);class MaxPhpInstancesError extends Error{constructor(t){super(`Requested more concurrent PHP instances than the limit (${t}).`),this.name=this.constructor.name}}class PHPProcessManager{constructor(t){this.primaryIdle=!0,this.nextInstance=null,this.allInstances=[],this.maxPhpInstances=t?.maxPhpInstances??5,this.phpFactory=t?.phpFactory,this.primaryPhp=t?.primaryPhp,this.semaphore=new Semaphore({concurrency:this.maxPhpInstances,timeout:t?.timeout||5e3})}async getPrimaryPhp(){if(!this.phpFactory&&!this.primaryPhp)throw new Error("phpFactory or primaryPhp must be set before calling getPrimaryPhp().");if(!this.primaryPhp){const t=await this.spawn({isPrimary:!0});this.primaryPhp=t.php}return this.primaryPhp}async acquirePHPInstance(){if(this.primaryIdle)return this.primaryIdle=!1,{php:await this.getPrimaryPhp(),reap:()=>this.primaryIdle=!0};const t=this.nextInstance||this.spawn({isPrimary:!1});return this.semaphore.remaining>0?this.nextInstance=this.spawn({isPrimary:!1}):this.nextInstance=null,await t}spawn(t){if(t.isPrimary&&this.allInstances.length>0)throw new Error("Requested spawning a primary PHP instance when another primary instance already started spawning.");const r=this.doSpawn(t);this.allInstances.push(r);const s=()=>{this.allInstances=this.allInstances.filter(i=>i!==r)};return r.catch(i=>{throw s(),i}).then(i=>({...i,reap:()=>{s(),i.reap()}}))}async doSpawn(t){let r;try{r=await this.semaphore.acquire()}catch(s){throw s instanceof AcquireTimeoutError?new MaxPhpInstancesError(this.maxPhpInstances):s}try{const s=await this.phpFactory(t);return{php:s,reap(){s.exit(),r()}}}catch(s){throw r(),s}}async[Symbol.asyncDispose](){this.primaryPhp&&this.primaryPhp.exit(),await Promise.all(this.allInstances.map(t=>t.then(({reap:r})=>r())))}}const DEFAULT_BASE_URL="http://example.com";function toRelativeUrl(e){return e.toString().substring(e.origin.length)}function removePathPrefix(e,t){return!t||!e.startsWith(t)?e:e.substring(t.length)}function ensurePathPrefix(e,t){return!t||e.startsWith(t)?e:t+e}async function encodeAsMultipart(e){const t=`----${Math.random().toString(36).slice(2)}`,r=`multipart/form-data; boundary=${t}`,s=new TextEncoder,i=[];for(const[l,c]of Object.entries(e))i.push(`--${t}\r
71
+ `),i.push(`Content-Disposition: form-data; name="${l}"`),c instanceof File&&i.push(`; filename="${c.name}"`),i.push(`\r
72
+ `),c instanceof File&&(i.push("Content-Type: application/octet-stream"),i.push(`\r
73
+ `)),i.push(`\r
74
+ `),c instanceof File?i.push(await fileToUint8Array(c)):i.push(c),i.push(`\r
75
+ `);i.push(`--${t}--\r
76
+ `);const n=i.reduce((l,c)=>l+c.length,0),o=new Uint8Array(n);let a=0;for(const l of i)o.set(typeof l=="string"?s.encode(l):l,a),a+=l.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)})}const _default="application/octet-stream",asx="video/x-ms-asf",atom="application/atom+xml",avi="video/x-msvideo",avif="image/avif",bin="application/octet-stream",bmp="image/x-ms-bmp",cco="application/x-cocoa",css="text/css",data="application/octet-stream",deb="application/octet-stream",der="application/x-x509-ca-cert",dmg="application/octet-stream",doc="application/msword",docx="application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot="application/vnd.ms-fontobject",flv="video/x-flv",gif="image/gif",gz="application/gzip",hqx="application/mac-binhex40",htc="text/x-component",html="text/html",ico="image/x-icon",iso="application/octet-stream",jad="text/vnd.sun.j2me.app-descriptor",jar="application/java-archive",jardiff="application/x-java-archive-diff",jng="image/x-jng",jnlp="application/x-java-jnlp-file",jpg="image/jpeg",jpeg="image/jpeg",js="application/javascript",json="application/json",kml="application/vnd.google-earth.kml+xml",kmz="application/vnd.google-earth.kmz",m3u8="application/vnd.apple.mpegurl",m4a="audio/x-m4a",m4v="video/x-m4v",md="text/plain",mid="audio/midi",mml="text/mathml",mng="video/x-mng",mov="video/quicktime",mp3="audio/mpeg",mp4="video/mp4",mpeg="video/mpeg",msi="application/octet-stream",odg="application/vnd.oasis.opendocument.graphics",odp="application/vnd.oasis.opendocument.presentation",ods="application/vnd.oasis.opendocument.spreadsheet",odt="application/vnd.oasis.opendocument.text",ogg="audio/ogg",otf="font/otf",pdf="application/pdf",pl="application/x-perl",png="image/png",ppt="application/vnd.ms-powerpoint",pptx="application/vnd.openxmlformats-officedocument.presentationml.presentation",prc="application/x-pilot",ps="application/postscript",ra="audio/x-realaudio",rar="application/x-rar-compressed",rpm="application/x-redhat-package-manager",rss="application/rss+xml",rtf="application/rtf",run="application/x-makeself",sea="application/x-sea",sit="application/x-stuffit",svg="image/svg+xml",swf="application/x-shockwave-flash",tcl="application/x-tcl",tar="application/x-tar",tif="image/tiff",ts="video/mp2t",ttf="font/ttf",txt="text/plain",wasm="application/wasm",wbmp="image/vnd.wap.wbmp",webm="video/webm",webp="image/webp",wml="text/vnd.wap.wml",wmlc="application/vnd.wap.wmlc",wmv="video/x-ms-wmv",woff="font/woff",woff2="font/woff2",xhtml="application/xhtml+xml",xls="application/vnd.ms-excel",xlsx="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml="text/xml",xpi="application/x-xpinstall",xspf="application/xspf+xml",zip="application/zip",mimeTypes={_default,"3gpp":"video/3gpp","7z":"application/x-7z-compressed",asx,atom,avi,avif,bin,bmp,cco,css,data,deb,der,dmg,doc,docx,eot,flv,gif,gz,hqx,htc,html,ico,iso,jad,jar,jardiff,jng,jnlp,jpg,jpeg,js,json,kml,kmz,m3u8,m4a,m4v,md,mid,mml,mng,mov,mp3,mp4,mpeg,msi,odg,odp,ods,odt,ogg,otf,pdf,pl,png,ppt,pptx,prc,ps,ra,rar,rpm,rss,rtf,run,sea,sit,svg,swf,tcl,tar,tif,ts,ttf,txt,wasm,wbmp,webm,webp,wml,wmlc,wmv,woff,woff2,xhtml,xls,xlsx,xml,xpi,xspf,zip};class PHPRequestHandler{#e;#s;#a;#r;#i;#t;#n;#o;constructor(t){const{documentRoot:r="/www/",absoluteUrl:s=typeof location=="object"?location?.href:"",rewriteRules:i=[]}=t;"processManager"in t?this.processManager=t.processManager:this.processManager=new PHPProcessManager({phpFactory:async a=>{const l=await t.phpFactory({...a,requestHandler:this});return l.requestHandler=this,l},maxPhpInstances:t.maxPhpInstances}),this.#o=new HttpCookieStore,this.#e=r;const n=new URL(s);this.#a=n.hostname,this.#r=n.port?Number(n.port):n.protocol==="https:"?443:80,this.#s=(n.protocol||"").replace(":","");const o=this.#r!==443&&this.#r!==80;this.#i=[this.#a,o?`:${this.#r}`:""].join(""),this.#t=n.pathname.replace(/\/+$/,""),this.#n=[`${this.#s}://`,this.#i,this.#t].join(""),this.rewriteRules=i}async getPrimaryPhp(){return await this.processManager.getPrimaryPhp()}pathToInternalUrl(t){return`${this.absoluteUrl}${t}`}internalUrlToPath(t){const r=new URL(t);return r.pathname.startsWith(this.#t)&&(r.pathname=r.pathname.slice(this.#t.length)),toRelativeUrl(r)}get absoluteUrl(){return this.#n}get documentRoot(){return this.#e}async request(t){const r=t.url.startsWith("http://")||t.url.startsWith("https://"),s=new URL(t.url.split("#")[0],r?void 0:DEFAULT_BASE_URL),i=applyRewriteRules(removePathPrefix(decodeURIComponent(s.pathname),this.#t),this.rewriteRules),n=joinPaths(this.#e,i);return seemsLikeAPHPRequestHandlerPath(n)?this.#c(t,s):this.#l(await this.processManager.getPrimaryPhp(),n)}#l(t,r){if(!t.fileExists(r))return new PHPResponse(404,{"x-file-type":["static"]},new TextEncoder().encode("404 File not found"));const s=t.readFileAsBuffer(r);return new PHPResponse(200,{"content-length":[`${s.byteLength}`],"content-type":[inferMimeType(r)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)}async#c(t,r){let s;try{s=await this.processManager.acquirePHPInstance()}catch(i){return i instanceof MaxPhpInstancesError?PHPResponse.forHttpCode(502):PHPResponse.forHttpCode(500)}try{return await this.#d(s.php,t,r)}finally{s.reap()}}async#d(t,r,s){let i="GET";const n={host:this.#i,...normalizeHeaders(r.headers||{}),cookie:this.#o.getCookieRequestHeader()};let o=r.body;if(typeof o=="object"&&!(o instanceof Uint8Array)){i="POST";const{bytes:l,contentType:c}=await encodeAsMultipart(o);o=l,n["content-type"]=c}let a;try{a=this.#p(t,decodeURIComponent(s.pathname))}catch{return PHPResponse.forHttpCode(404)}try{const l=await t.run({relativeUri:ensurePathPrefix(toRelativeUrl(s),this.#t),protocol:this.#s,method:r.method||i,$_SERVER:{REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:this.#e,HTTPS:this.#n.startsWith("https://")?"on":""},body:o,scriptPath:a,headers:n});return this.#o.rememberCookiesFromResponseHeaders(l.headers),l}catch(l){const c=l;if(c?.response)return c.response;throw l}}#p(t,r){let s=removePathPrefix(r,this.#t);s=applyRewriteRules(s,this.rewriteRules),s.includes(".php")?s=s.split(".php")[0]+".php":t.isDir(`${this.#e}${s}`)?(s.endsWith("/")||(s=`${s}/`),s=`${s}index.php`):s="/index.php";let i=`${this.#e}${s}`;if(t.fileExists(i)||(i=`${this.#e}/index.php`),t.fileExists(i))return i;throw new Error(`File not found: ${i}`)}}function inferMimeType(e){const t=e.split(".").pop();return mimeTypes[t]||mimeTypes._default}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}function rotatePHPRuntime({php:e,cwd:t,recreateRuntime:r,maxRequests:s=400}){let i=0;async function n(){if(++i<s)return;i=0;const o=await e.semaphore.acquire();try{e.hotSwapPHPRuntime(await r(),t)}finally{o()}}return e.addEventListener("request.end",n),function(){e.removeEventListener("request.end",n)}}async function writeFiles(e,t,r,{rmRoot:s=!1}={}){s&&await e.isDir(t)&&await e.rmdir(t,{recursive:!0});for(const[i,n]of Object.entries(r)){const o=joinPaths(t,i);await e.fileExists(dirname(o))||await e.mkdir(dirname(o)),n instanceof Uint8Array||typeof n=="string"?await e.writeFile(o,n):await writeFiles(e,o,n)}}function proxyFileSystem(e,t,r){const s=Object.getOwnPropertySymbols(e)[0];for(const i of r)t.fileExists(i)||t.mkdir(i),e.fileExists(i)||e.mkdir(i),t[s].FS.mount(t[s].PROXYFS,{root:i,fs:e[s].FS},i)}async function bootWordPress(e){async function t(i,n){const o=new PHP(await e.createPhpRuntime());return e.sapiName&&o.setSapiName(e.sapiName),i&&(o.requestHandler=i),e.phpIniEntries&&setPhpIniEntries(o,e.phpIniEntries),n?(await setupPlatformLevelMuPlugins(o),await writeFiles(o,"/",e.createFiles||{}),await preloadPhpInfoRoute(o,joinPaths(new URL(e.siteUrl).pathname,"phpinfo.php"))):proxyFileSystem(await i.getPrimaryPhp(),o,["/tmp",i.documentRoot,"/internal/shared"]),e.spawnHandler&&await o.setSpawnHandler(e.spawnHandler(i.processManager)),rotatePHPRuntime({php:o,cwd:i.documentRoot,recreateRuntime:e.createPhpRuntime,maxRequests:400}),o}const r=new PHPRequestHandler({phpFactory:async({isPrimary:i})=>t(r,i),documentRoot:e.documentRoot||"/wordpress",absoluteUrl:e.siteUrl,rewriteRules:wordPressRewriteRules}),s=await r.getPrimaryPhp();if(e.hooks?.beforeWordPressFiles&&await e.hooks.beforeWordPressFiles(s),e.wordPressZip&&await unzipWordPress(s,await e.wordPressZip),e.constants)for(const i in e.constants)s.defineConstant(i,e.constants[i]);if(s.defineConstant("WP_HOME",e.siteUrl),s.defineConstant("WP_SITEURL",e.siteUrl),e.hooks?.beforeDatabaseSetup&&await e.hooks.beforeDatabaseSetup(s),e.sqliteIntegrationPluginZip&&await preloadSqliteIntegration(s,await e.sqliteIntegrationPluginZip),await isWordPressInstalled(s)||await installWordPress(s),!await isWordPressInstalled(s))throw new Error("WordPress installation has failed.");return r}async function isWordPressInstalled(e){return(await e.run({code:`<?php
79
77
  require '${e.documentRoot}/wp-load.php';
80
78
  echo is_blog_installed() ? '1' : '0';
81
- `})).text==="1"}async function installWordPress(e){await withPHPIniValues(e,{disable_functions:"fsockopen",allow_url_fopen:"0"},async()=>await e.request({url:"/wp-admin/install.php?step=2",method:"POST",body:{language:"en",prefix:"wp_",weblog_title:"My WordPress Website",user_name:"admin",admin_password:"password",admin_password2:"password",Submit:"Install WordPress",pw_weak:"1",admin_email:"admin@localhost.com"}}))}const nightly="nightly",beta="6.6-RC2",SupportedWordPressVersions={nightly,beta,"6.5":"6.5.5","6.4":"6.4.5","6.3":"6.3.5","6.2":"6.2.6"},SupportedWordPressVersionsList=Object.keys(SupportedWordPressVersions);SupportedWordPressVersionsList.filter(e=>e.match(/^\d/))[0];async function getLoadedWordPressVersion(e){const r=(await(await e.getPrimaryPhp()).run({code:`<?php
79
+ `})).text==="1"}async function installWordPress(e){await withPHPIniValues(e,{disable_functions:"fsockopen",allow_url_fopen:"0"},async()=>await e.request({url:"/wp-admin/install.php?step=2",method:"POST",body:{language:"en",prefix:"wp_",weblog_title:"My WordPress Website",user_name:"admin",admin_password:"password",admin_password2:"password",Submit:"Install WordPress",pw_weak:"1",admin_email:"admin@localhost.com"}}))}const nightly="nightly",beta="6.6-RC2",SupportedWordPressVersions={nightly,beta,"6.5":"6.5.5","6.4":"6.4.5","6.3":"6.3.5","6.2":"6.2.6"},SupportedWordPressVersionsList=Object.keys(SupportedWordPressVersions);SupportedWordPressVersionsList.filter(e=>e.match(/^\d/))[0];async function getLoadedWordPressVersion(e){const s=(await(await e.getPrimaryPhp()).run({code:`<?php
82
80
  require '${e.documentRoot}/wp-includes/version.php';
83
81
  echo $wp_version;
84
- `})).text;if(!r)throw new Error("Unable to read loaded WordPress version.");return versionStringToLoadedWordPressVersion(r)}function versionStringToLoadedWordPressVersion(e){if(/-(alpha|beta|RC)\d*-\d+$/.test(e))return"nightly";if(/-(beta|RC)\d*$/.test(e))return"beta";const r=e.match(/^(\d+\.\d+)(?:\.\d+)?$/);return r!==null?r[1]:e}function isSupportedWordPressVersion(e){return Object.keys(SupportedWordPressVersions).includes(e)}const wordPressRewriteRules=[{match:/^\/(.*?)(\/wp-(content|admin|includes)\/.*)/g,replacement:"$2"}];async function setupPlatformLevelMuPlugins(e){await e.mkdir("/internal/shared/mu-plugins"),await e.writeFile("/internal/shared/preload/env.php",`<?php
82
+ `})).text;if(!s)throw new Error("Unable to read loaded WordPress version.");return versionStringToLoadedWordPressVersion(s)}function versionStringToLoadedWordPressVersion(e){if(/-(alpha|beta|RC)\d*-\d+$/.test(e))return"nightly";if(/-(beta|RC)\d*$/.test(e))return"beta";const s=e.match(/^(\d+\.\d+)(?:\.\d+)?$/);return s!==null?s[1]:e}function isSupportedWordPressVersion(e){return Object.keys(SupportedWordPressVersions).includes(e)}const wordPressRewriteRules=[{match:/^\/(.*?)(\/wp-(content|admin|includes)\/.*)/g,replacement:"$2"}];async function setupPlatformLevelMuPlugins(e){await e.mkdir("/internal/shared/mu-plugins"),await e.writeFile("/internal/shared/preload/env.php",`<?php
85
83
 
86
84
  // Allow adding filters/actions prior to loading WordPress.
87
85
  // $function_to_add MUST be a string.
@@ -191,12 +189,12 @@ ${bold} WASM ERROR${reset}${redBg}`);for(const t of e.split(`
191
189
  phpinfo();
192
190
  exit;
193
191
  }
194
- `)}async function preloadSqliteIntegration(e,t){await e.isDir("/tmp/sqlite-database-integration")&&await e.rmdir("/tmp/sqlite-database-integration",{recursive:!0}),await e.mkdir("/tmp/sqlite-database-integration"),await unzipFile(e,t,"/tmp/sqlite-database-integration");const s="/internal/shared/sqlite-database-integration";await e.mv("/tmp/sqlite-database-integration/sqlite-database-integration-main",s),await e.defineConstant("SQLITE_MAIN_FILE","1");const n=(await e.readFileAsText(joinPaths(s,"db.copy"))).replace("'{SQLITE_IMPLEMENTATION_FOLDER_PATH}'",phpVar(s)).replace("'{SQLITE_PLUGIN}'",phpVar(joinPaths(s,"load.php"))),i=joinPaths(await e.documentRoot,"wp-content/db.php"),o=`<?php
192
+ `)}async function preloadSqliteIntegration(e,t){await e.isDir("/tmp/sqlite-database-integration")&&await e.rmdir("/tmp/sqlite-database-integration",{recursive:!0}),await e.mkdir("/tmp/sqlite-database-integration"),await unzipFile(e,t,"/tmp/sqlite-database-integration");const r="/internal/shared/sqlite-database-integration";await e.mv("/tmp/sqlite-database-integration/sqlite-database-integration-main",r),await e.defineConstant("SQLITE_MAIN_FILE","1");const i=(await e.readFileAsText(joinPaths(r,"db.copy"))).replace("'{SQLITE_IMPLEMENTATION_FOLDER_PATH}'",phpVar(r)).replace("'{SQLITE_PLUGIN}'",phpVar(joinPaths(r,"load.php"))),n=joinPaths(await e.documentRoot,"wp-content/db.php"),o=`<?php
195
193
  // Do not preload this if WordPress comes with a custom db.php file.
196
- if(file_exists(${phpVar(i)})) {
194
+ if(file_exists(${phpVar(n)})) {
197
195
  return;
198
196
  }
199
- ?>`,a="/internal/shared/mu-plugins/sqlite-database-integration.php";await e.writeFile(a,o+n),await e.writeFile("/internal/shared/preload/0-sqlite.php",o+`<?php
197
+ ?>`,a="/internal/shared/mu-plugins/sqlite-database-integration.php";await e.writeFile(a,o+i),await e.writeFile("/internal/shared/preload/0-sqlite.php",o+`<?php
200
198
 
201
199
  /**
202
200
  * Loads the SQLite integration plugin before WordPress is loaded
@@ -268,4 +266,4 @@ if(!function_exists('mysqli_connect')) {
268
266
  var_dump(isset($wpdb));
269
267
  die("SQLite integration not loaded " . get_class($wpdb));
270
268
  }
271
- `)}async function unzipWordPress(e,t){e.mkdir("/tmp/unzipped-wordpress"),await unzipFile(e,t,"/tmp/unzipped-wordpress"),e.fileExists("/tmp/unzipped-wordpress/wordpress.zip")&&await unzipFile(e,"/tmp/unzipped-wordpress/wordpress.zip","/tmp/unzipped-wordpress");const s=e.fileExists("/tmp/unzipped-wordpress/wordpress")?"/tmp/unzipped-wordpress/wordpress":e.fileExists("/tmp/unzipped-wordpress/build")?"/tmp/unzipped-wordpress/build":"/tmp/unzipped-wordpress";e.mv(s,e.documentRoot),!e.fileExists(joinPaths(e.documentRoot,"wp-config.php"))&&e.fileExists(joinPaths(e.documentRoot,"wp-config-sample.php"))&&e.writeFile(joinPaths(e.documentRoot,"wp-config.php"),e.readFileAsText(joinPaths(e.documentRoot,"/wp-config-sample.php")))}export{bootWordPress,getLoadedWordPressVersion,isSupportedWordPressVersion,preloadPhpInfoRoute,preloadSqliteIntegration,setupPlatformLevelMuPlugins,unzipWordPress,wordPressRewriteRules};
269
+ `)}async function unzipWordPress(e,t){e.mkdir("/tmp/unzipped-wordpress"),await unzipFile(e,t,"/tmp/unzipped-wordpress"),e.fileExists("/tmp/unzipped-wordpress/wordpress.zip")&&await unzipFile(e,"/tmp/unzipped-wordpress/wordpress.zip","/tmp/unzipped-wordpress");const r=e.fileExists("/tmp/unzipped-wordpress/wordpress")?"/tmp/unzipped-wordpress/wordpress":e.fileExists("/tmp/unzipped-wordpress/build")?"/tmp/unzipped-wordpress/build":"/tmp/unzipped-wordpress";e.mv(r,e.documentRoot),!e.fileExists(joinPaths(e.documentRoot,"wp-config.php"))&&e.fileExists(joinPaths(e.documentRoot,"wp-config-sample.php"))&&e.writeFile(joinPaths(e.documentRoot,"wp-config.php"),e.readFileAsText(joinPaths(e.documentRoot,"/wp-config-sample.php")))}export{bootWordPress,getLoadedWordPressVersion,isSupportedWordPressVersion,preloadPhpInfoRoute,preloadSqliteIntegration,setupPlatformLevelMuPlugins,unzipWordPress,wordPressRewriteRules};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wp-playground/wordpress",
3
- "version": "0.9.12",
3
+ "version": "0.9.14",
4
4
  "description": "WordPress-related plumbing for WordPress Playground",
5
5
  "repository": {
6
6
  "type": "git",
@@ -15,10 +15,10 @@
15
15
  "url": "https://github.com/adamziel"
16
16
  }
17
17
  ],
18
+ "type": "module",
18
19
  "main": "./index.js",
19
20
  "typings": "./index.d.ts",
20
21
  "license": "GPL-2.0-or-later",
21
- "type": "module",
22
22
  "engines": {
23
23
  "node": ">=18.18.0",
24
24
  "npm": ">=8.11.0"
@@ -27,5 +27,5 @@
27
27
  "access": "public",
28
28
  "directory": "../../../dist/packages/playground/wordpress"
29
29
  },
30
- "gitHead": "d915634c21a5af607a7201395920d0a81f842e96"
30
+ "gitHead": "787eee56fce781d74765e3012786e3f83f58b278"
31
31
  }