@php-wasm/universal 0.9.13 → 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 (3) hide show
  1. package/index.cjs +10 -12
  2. package/index.js +313 -425
  3. package/package.json +2 -2
package/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";var Y=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)};var u=(t,e,r)=>(Y(t,e,"read from private field"),r?r.call(t):e.get(t)),p=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},f=(t,e,r,s)=>(Y(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r);var h=(t,e,r)=>(Y(t,e,"access private method"),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const currentJsRuntime$1=function(){var t;return typeof process<"u"&&((t=process.release)==null?void 0:t.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}();if(currentJsRuntime$1==="NODE"){let t=function(r){return new Promise(function(s,n){r.onload=r.onerror=function(i){r.onload=r.onerror=null,i.type==="load"?s(r.result):n(new Error("Failed to read the blob/file"))}})},e=function(){const r=new Uint8Array([1,2,3,4]),n=new File([r],"test").stream();try{return n.getReader({mode:"byob"}),!0}catch{return!1}};if(typeof File>"u"){class r extends Blob{constructor(n,i,o){super(n);let l;o!=null&&o.lastModified&&(l=new Date),(!l||isNaN(l.getFullYear()))&&(l=new Date),this.lastModifiedDate=l,this.lastModified=l.getMilliseconds(),this.name=i||""}}global.File=r}typeof Blob.prototype.arrayBuffer>"u"&&(Blob.prototype.arrayBuffer=function(){const s=new FileReader;return s.readAsArrayBuffer(this),t(s)}),typeof Blob.prototype.text>"u"&&(Blob.prototype.text=function(){const s=new FileReader;return s.readAsText(this),t(s)}),(typeof Blob.prototype.stream>"u"||!e())&&(Blob.prototype.stream=function(){let r=0;const s=this;return new ReadableStream({type:"bytes",autoAllocateChunkSize:512*1024,async pull(n){const i=n.byobRequest.view,l=await s.slice(r,r+i.byteLength).arrayBuffer(),c=new Uint8Array(l);new Uint8Array(i.buffer).set(c);const a=c.byteLength;n.byobRequest.respond(a),r+=a,r>=s.size&&n.close()}})})}if(currentJsRuntime$1==="NODE"&&typeof CustomEvent>"u"){class t extends Event{constructor(r,s={}){super(r,s),this.detail=s.detail}initCustomEvent(){}}globalThis.CustomEvent=t}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(t){const e=typeof t=="object"?t==null?void 0:t.errno:null;if(e in FileErrorCodes)return FileErrorCodes[e]}function rethrowFileSystemError(t=""){return function(r,s,n){const i=n.value;n.value=function(...o){try{return i.apply(this,o)}catch(l){const c=typeof l=="object"?l==null?void 0:l.errno:null;if(c in FileErrorCodes){const a=FileErrorCodes[c],d=typeof o[1]=="string"?o[1]:null,m=d!==null?t.replaceAll("{path}",d):t;throw new Error(`${m}: ${a}`,{cause:l})}throw l}}}}const logEventType="playground-log",logEvent=(t,...e)=>{logger.dispatchEvent(new CustomEvent(logEventType,{detail:{log:t,args:e}}))},logToConsole=(t,...e)=>{switch(typeof t.message=="string"?t.message=prepareLogMessage(t.message):t.message.message&&typeof t.message.message=="string"&&(t.message.message=prepareLogMessage(t.message.message)),t.severity){case"Debug":console.debug(t.message,...e);break;case"Info":console.info(t.message,...e);break;case"Warn":console.warn(t.message,...e);break;case"Error":console.error(t.message,...e);break;case"Fatal":console.error(t.message,...e);break;default:console.log(t.message,...e)}},prepareLogMessage$1=t=>t instanceof Error?[t.message,t.stack].join(`
1
+ "use strict";var V=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)};var p=(t,e,r)=>(V(t,e,"read from private field"),r?r.call(t):e.get(t)),u=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},h=(t,e,r,s)=>(V(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r);var d=(t,e,r)=>(V(t,e,"access private method"),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ini_js=require("/home/runner/work/wordpress-playground/wordpress-playground/node_modules/ini/lib/ini.js"),currentJsRuntime$1=function(){var t;return typeof process<"u"&&((t=process.release)==null?void 0:t.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}();if(currentJsRuntime$1==="NODE"){let t=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"))}})},e=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!=null&&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),t(s)}),typeof Blob.prototype.text>"u"&&(Blob.prototype.text=function(){const s=new FileReader;return s.readAsText(this),t(s)}),(typeof Blob.prototype.stream>"u"||!e())&&(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$1==="NODE"&&typeof CustomEvent>"u"){class t extends Event{constructor(r,s={}){super(r,s),this.detail=s.detail}initCustomEvent(){}}globalThis.CustomEvent=t}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(t){const e=typeof t=="object"?t==null?void 0:t.errno:null;if(e in FileErrorCodes)return FileErrorCodes[e]}function rethrowFileSystemError(t=""){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==null?void 0:a.errno:null;if(l in FileErrorCodes){const c=FileErrorCodes[l],P=typeof o[1]=="string"?o[1]:null,de=P!==null?t.replaceAll("{path}",P):t;throw new Error(`${de}: ${c}`,{cause:a})}throw a}}}}const logEventType="playground-log",logEvent=(t,...e)=>{logger.dispatchEvent(new CustomEvent(logEventType,{detail:{log:t,args:e}}))},logToConsole=(t,...e)=>{switch(typeof t.message=="string"?t.message=prepareLogMessage(t.message):t.message.message&&typeof t.message.message=="string"&&(t.message.message=prepareLogMessage(t.message.message)),t.severity){case"Debug":console.debug(t.message,...e);break;case"Info":console.info(t.message,...e);break;case"Warn":console.warn(t.message,...e);break;case"Error":console.error(t.message,...e);break;case"Fatal":console.error(t.message,...e);break;default:console.log(t.message,...e)}},prepareLogMessage$1=t=>t instanceof Error?[t.message,t.stack].join(`
2
2
  `):JSON.stringify(t,null,2),logs=[],addToLogArray=t=>{logs.push(t)},logToMemory=t=>{if(t.raw===!0)addToLogArray(t.message);else{const e=formatLogEntry(typeof t.message=="object"?prepareLogMessage$1(t.message):t.message,t.severity??"Info",t.prefix??"JavaScript");addToLogArray(e)}};class Logger extends EventTarget{constructor(e=[]){super(),this.handlers=e,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.
3
3
  If you're using a custom logger instance, make sure to register logToMemory handler.
4
- `),[])}logMessage(e,...r){for(const s of this.handlers)s(e,...r)}log(e,...r){this.logMessage({message:e,severity:void 0,prefix:"JavaScript",raw:!1},...r)}debug(e,...r){this.logMessage({message:e,severity:"Debug",prefix:"JavaScript",raw:!1},...r)}info(e,...r){this.logMessage({message:e,severity:"Info",prefix:"JavaScript",raw:!1},...r)}warn(e,...r){this.logMessage({message:e,severity:"Warn",prefix:"JavaScript",raw:!1},...r)}error(e,...r){this.logMessage({message:e,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=t=>t.replace(/\t/g,""),formatLogEntry=(t,e,r)=>{const s=new Date,n=new Intl.DateTimeFormat("en-GB",{year:"numeric",month:"short",day:"2-digit",timeZone:"UTC"}).format(s).replace(/ /g,"-"),i=new Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZone:"UTC",timeZoneName:"short"}).format(s),o=n+" "+i;return t=prepareLogMessage(t),`[${o}] ${r} ${e}: ${t}`},SleepFinished=Symbol("SleepFinished");function sleep(t){return new Promise(e=>{setTimeout(()=>e(SleepFinished),t)})}class AcquireTimeoutError extends Error{constructor(){super("Acquiring lock timed out")}}class Semaphore{constructor({concurrency:e,timeout:r}){this._running=0,this.concurrency=e,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 e=new Promise(r=>{this.queue.push(r)});this.timeout!==void 0?await Promise.race([e,sleep(this.timeout)]).then(r=>{if(r===SleepFinished)throw new AcquireTimeoutError}):await e}else{this._running++;let e=!1;return()=>{e||(e=!0,this._running--,this.queue.length>0&&this.queue.shift()())}}}async run(e){const r=await this.acquire();try{return await e()}finally{r()}}}function joinPaths(...t){let e=t.join("/");const r=e[0]==="/",s=e.substring(e.length-1)==="/";return e=normalizePath(e),!e&&!r&&(e="."),e&&s&&(e+="/"),e}function dirname(t){if(t==="/")return"/";t=normalizePath(t);const e=t.lastIndexOf("/");return e===-1?"":e===0?"/":t.substr(0,e)}function normalizePath(t){const e=t[0]==="/";return t=normalizePathsArray(t.split("/").filter(r=>!!r),!e).join("/"),(e?"/":"")+t.replace(/\/$/,"")}function normalizePathsArray(t,e){let r=0;for(let s=t.length-1;s>=0;s--){const n=t[s];n==="."?t.splice(s,1):n===".."?(t.splice(s,1),r++):r&&(t.splice(s,1),r--)}if(e)for(;r;r--)t.unshift("..");return t}function splitShellCommand(t){let s=0,n="";const i=[];let o="";for(let l=0;l<t.length;l++){const c=t[l];c==="\\"?((t[l+1]==='"'||t[l+1]==="'")&&l++,o+=t[l]):s===0?c==='"'||c==="'"?(s=1,n=c):c.match(/\s/)?(o.trim().length&&i.push(o.trim()),o=c):i.length&&!o?o=i.pop()+c:o+=c:s===1&&(c===n?(s=0,n=""):o+=c)}return o&&i.push(o.trim()),i}function createSpawnHandler(t){return function(e,r=[],s={}){const n=new ChildProcess,i=new ProcessApi(n);return setTimeout(async()=>{let o=[];if(r.length)o=[e,...r];else if(typeof e=="string")o=splitShellCommand(e);else if(Array.isArray(e))o=e;else throw new Error("Invalid command ",e);try{await t(o,i,s)}catch(l){n.emit("error",l),typeof l=="object"&&l!==null&&"message"in l&&typeof l.message=="string"&&i.stderr(l.message),i.exit(1)}n.emit("spawn",!0)}),n}}class EventEmitter{constructor(){this.listeners={}}emit(e,r){this.listeners[e]&&this.listeners[e].forEach(function(s){s(r)})}on(e,r){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(r)}}class ProcessApi extends EventEmitter{constructor(e){super(),this.childProcess=e,this.exited=!1,this.stdinData=[],e.on("stdin",r=>{this.stdinData?this.stdinData.push(r.slice()):this.emit("stdin",r)})}stdout(e){typeof e=="string"&&(e=new TextEncoder().encode(e)),this.childProcess.stdout.emit("data",e)}stdoutEnd(){this.childProcess.stdout.emit("end",{})}stderr(e){typeof e=="string"&&(e=new TextEncoder().encode(e)),this.childProcess.stderr.emit("data",e)}stderrEnd(){this.childProcess.stderr.emit("end",{})}exit(e){this.exited||(this.exited=!0,this.childProcess.emit("exit",e))}flushStdin(){if(this.stdinData)for(let e=0;e<this.stdinData.length;e++)this.emit("stdin",this.stdinData[e]);this.stdinData=null}}let lastPid=9743;class ChildProcess extends EventEmitter{constructor(e=lastPid++){super(),this.pid=e,this.stdout=new EventEmitter,this.stderr=new EventEmitter;const r=this;this.stdin={write:s=>{r.emit("stdin",s)}}}}var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(t,e,r,s)=>{for(var n=s>1?void 0:s?__getOwnPropDesc(e,r):e,i=t.length-1,o;i>=0;i--)(o=t[i])&&(n=(s?o(e,r,n):o(n))||n);return s&&n&&__defProp(e,r,n),n};const _FSHelpers=class g{static readFileAsText(e,r){return new TextDecoder().decode(g.readFileAsBuffer(e,r))}static readFileAsBuffer(e,r){return e.readFile(r)}static writeFile(e,r,s){e.writeFile(r,s)}static unlink(e,r){e.unlink(r)}static mv(e,r,s){try{const n=e.lookupPath(r).node.mount,i=g.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(dirname(s)).node.mount;n.mountpoint!==i.mountpoint?(g.copyRecursive(e,r,s),g.rmdir(e,r,{recursive:!0})):e.rename(r,s)}catch(n){const i=getEmscriptenFsError(n);throw i?new Error(`Could not move ${r} to ${s}: ${i}`,{cause:n}):n}}static rmdir(e,r,s={recursive:!0}){s!=null&&s.recursive&&g.listFiles(e,r).forEach(n=>{const i=`${r}/${n}`;g.isDir(e,i)?g.rmdir(e,i,s):g.unlink(e,i)}),e.rmdir(r)}static listFiles(e,r,s={prependPath:!1}){if(!g.fileExists(e,r))return[];try{const n=e.readdir(r).filter(i=>i!=="."&&i!=="..");if(s.prependPath){const i=r.replace(/\/$/,"");return n.map(o=>`${i}/${o}`)}return n}catch(n){return logger.error(n,{path:r}),[]}}static isDir(e,r){return g.fileExists(e,r)?e.isDir(e.lookupPath(r).node.mode):!1}static fileExists(e,r){try{return e.lookupPath(r),!0}catch{return!1}}static mkdir(e,r){e.mkdirTree(r)}static copyRecursive(e,r,s){const n=e.lookupPath(r).node;if(e.isDir(n.mode)){e.mkdirTree(s);const i=e.readdir(r).filter(o=>o!=="."&&o!=="..");for(const o of i)g.copyRecursive(e,joinPaths(r,o),joinPaths(s,o))}else e.writeFile(s,e.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 _private=new WeakMap;class PHPWorker{constructor(e,r){this.absoluteUrl="",this.documentRoot="",_private.set(this,{monitor:r}),e&&this.__internal_setRequestHandler(e)}__internal_setRequestHandler(e){this.absoluteUrl=e.absoluteUrl,this.documentRoot=e.documentRoot,_private.set(this,{..._private.get(this),requestHandler:e})}__internal_getPHP(){return _private.get(this).php}async setPrimaryPHP(e){_private.set(this,{..._private.get(this),php:e})}pathToInternalUrl(e){return _private.get(this).requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return _private.get(this).requestHandler.internalUrlToPath(e)}async onDownloadProgress(e){var r;return(r=_private.get(this).monitor)==null?void 0:r.addEventListener("progress",e)}async mv(e,r){return _private.get(this).php.mv(e,r)}async rmdir(e,r){return _private.get(this).php.rmdir(e,r)}async request(e){return await _private.get(this).requestHandler.request(e)}async run(e){const{php:r,reap:s}=await _private.get(this).requestHandler.processManager.acquirePHPInstance();try{return await r.run(e)}finally{s()}}chdir(e){return _private.get(this).php.chdir(e)}setSapiName(e){_private.get(this).php.setSapiName(e)}mkdir(e){return _private.get(this).php.mkdir(e)}mkdirTree(e){return _private.get(this).php.mkdirTree(e)}readFileAsText(e){return _private.get(this).php.readFileAsText(e)}readFileAsBuffer(e){return _private.get(this).php.readFileAsBuffer(e)}writeFile(e,r){return _private.get(this).php.writeFile(e,r)}unlink(e){return _private.get(this).php.unlink(e)}listFiles(e,r){return _private.get(this).php.listFiles(e,r)}isDir(e){return _private.get(this).php.isDir(e)}fileExists(e){return _private.get(this).php.fileExists(e)}onMessage(e){_private.get(this).php.onMessage(e)}defineConstant(e,r){_private.get(this).php.defineConstant(e,r)}addEventListener(e,r){_private.get(this).php.addEventListener(e,r)}removeEventListener(e,r){_private.get(this).php.removeEventListener(e,r)}}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(e,r,s,n="",i=0){this.httpStatusCode=e,this.headers=r,this.bytes=s,this.exitCode=i,this.errors=n}static forHttpCode(e,r=""){return new PHPResponse(e,{},new TextEncoder().encode(r||responseTexts[e]||""))}static fromRawData(e){return new PHPResponse(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}const RuntimeId=Symbol("RuntimeId"),loadedRuntimes=new Map;let lastRuntimeId=0;async function loadPHPRuntime(t,e={}){const[r,s,n]=makePromise(),i=t.init(currentJsRuntime,{onAbort(l){n(l),logger.error(l)},ENV:{},locateFile:l=>l,...e,noInitialRun:!0,onRuntimeInitialized(){e.onRuntimeInitialized&&e.onRuntimeInitialized(),s()}});await r;const o=++lastRuntimeId;return i.id=o,i.originalExit=i._exit,i._exit=function(l){return loadedRuntimes.delete(o),i.originalExit(l)},i[RuntimeId]=o,loadedRuntimes.set(o,i),o}function getLoadedRuntime(t){return loadedRuntimes.get(t)}const currentJsRuntime=function(){var t;return typeof process<"u"&&((t=process.release)==null?void 0:t.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}(),makePromise=()=>{const t=[],e=new Promise((r,s)=>{t.push(r,s)});return t.unshift(e),t},kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends Event{constructor(e,r={}){super(e),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(t){return t instanceof Error?"exitCode"in t&&(t==null?void 0:t.exitCode)===0||(t==null?void 0:t.name)==="ExitStatus"&&"status"in t&&t.status===0:!1}class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,r){++this.listenersCount,super.addEventListener(e,r)}removeEventListener(e,r){--this.listenersCount,super.removeEventListener(e,r)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(t){const e=new UnhandledRejectionsTarget;for(const r in t.wasmExports)if(typeof t.wasmExports[r]=="function"){const s=t.wasmExports[r];t.wasmExports[r]=function(...n){var i;try{return s(...n)}catch(o){if(!(o instanceof Error))throw o;const l=clarifyErrorMessage(o,(i=t.lastAsyncifyStackSource)==null?void 0:i.stack);if(t.lastAsyncifyStackSource&&(o.cause=t.lastAsyncifyStackSource),e.hasListeners()){e.dispatchEvent(new ErrorEvent("error",{error:o,message:l}));return}throw isExitCodeZero(o)||showCriticalErrorBox(l),o}}}return e}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(t,e){if(t.message==="unreachable"){let r=UNREACHABLE_ERROR;e||(r+=`
4
+ `),[])}logMessage(e,...r){for(const s of this.handlers)s(e,...r)}log(e,...r){this.logMessage({message:e,severity:void 0,prefix:"JavaScript",raw:!1},...r)}debug(e,...r){this.logMessage({message:e,severity:"Debug",prefix:"JavaScript",raw:!1},...r)}info(e,...r){this.logMessage({message:e,severity:"Info",prefix:"JavaScript",raw:!1},...r)}warn(e,...r){this.logMessage({message:e,severity:"Warn",prefix:"JavaScript",raw:!1},...r)}error(e,...r){this.logMessage({message:e,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=t=>t.replace(/\t/g,""),formatLogEntry=(t,e,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 t=prepareLogMessage(t),`[${o}] ${r} ${e}: ${t}`},SleepFinished=Symbol("SleepFinished");function sleep(t){return new Promise(e=>{setTimeout(()=>e(SleepFinished),t)})}class AcquireTimeoutError extends Error{constructor(){super("Acquiring lock timed out")}}class Semaphore{constructor({concurrency:e,timeout:r}){this._running=0,this.concurrency=e,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 e=new Promise(r=>{this.queue.push(r)});this.timeout!==void 0?await Promise.race([e,sleep(this.timeout)]).then(r=>{if(r===SleepFinished)throw new AcquireTimeoutError}):await e}else{this._running++;let e=!1;return()=>{e||(e=!0,this._running--,this.queue.length>0&&this.queue.shift()())}}}async run(e){const r=await this.acquire();try{return await e()}finally{r()}}}function joinPaths(...t){let e=t.join("/");const r=e[0]==="/",s=e.substring(e.length-1)==="/";return e=normalizePath(e),!e&&!r&&(e="."),e&&s&&(e+="/"),e}function dirname(t){if(t==="/")return"/";t=normalizePath(t);const e=t.lastIndexOf("/");return e===-1?"":e===0?"/":t.substr(0,e)}function normalizePath(t){const e=t[0]==="/";return t=normalizePathsArray(t.split("/").filter(r=>!!r),!e).join("/"),(e?"/":"")+t.replace(/\/$/,"")}function normalizePathsArray(t,e){let r=0;for(let s=t.length-1;s>=0;s--){const i=t[s];i==="."?t.splice(s,1):i===".."?(t.splice(s,1),r++):r&&(t.splice(s,1),r--)}if(e)for(;r;r--)t.unshift("..");return t}function splitShellCommand(t){let s=0,i="";const n=[];let o="";for(let a=0;a<t.length;a++){const l=t[a];l==="\\"?((t[a+1]==='"'||t[a+1]==="'")&&a++,o+=t[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(t){return function(e,r=[],s={}){const i=new ChildProcess,n=new ProcessApi(i);return setTimeout(async()=>{let o=[];if(r.length)o=[e,...r];else if(typeof e=="string")o=splitShellCommand(e);else if(Array.isArray(e))o=e;else throw new Error("Invalid command ",e);try{await t(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(e,r){this.listeners[e]&&this.listeners[e].forEach(function(s){s(r)})}on(e,r){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(r)}}class ProcessApi extends EventEmitter{constructor(e){super(),this.childProcess=e,this.exited=!1,this.stdinData=[],e.on("stdin",r=>{this.stdinData?this.stdinData.push(r.slice()):this.emit("stdin",r)})}stdout(e){typeof e=="string"&&(e=new TextEncoder().encode(e)),this.childProcess.stdout.emit("data",e)}stdoutEnd(){this.childProcess.stdout.emit("end",{})}stderr(e){typeof e=="string"&&(e=new TextEncoder().encode(e)),this.childProcess.stderr.emit("data",e)}stderrEnd(){this.childProcess.stderr.emit("end",{})}exit(e){this.exited||(this.exited=!0,this.childProcess.emit("exit",e))}flushStdin(){if(this.stdinData)for(let e=0;e<this.stdinData.length;e++)this.emit("stdin",this.stdinData[e]);this.stdinData=null}}let lastPid=9743;class ChildProcess extends EventEmitter{constructor(e=lastPid++){super(),this.pid=e,this.stdout=new EventEmitter,this.stderr=new EventEmitter;const r=this;this.stdin={write:s=>{r.emit("stdin",s)}}}}var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(t,e,r,s)=>{for(var i=s>1?void 0:s?__getOwnPropDesc(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(i=(s?o(e,r,i):o(i))||i);return s&&i&&__defProp(e,r,i),i};const _FSHelpers=class f{static readFileAsText(e,r){return new TextDecoder().decode(f.readFileAsBuffer(e,r))}static readFileAsBuffer(e,r){return e.readFile(r)}static writeFile(e,r,s){e.writeFile(r,s)}static unlink(e,r){e.unlink(r)}static mv(e,r,s){try{const i=e.lookupPath(r).node.mount,n=f.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(dirname(s)).node.mount;i.mountpoint!==n.mountpoint?(f.copyRecursive(e,r,s),f.rmdir(e,r,{recursive:!0})):e.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(e,r,s={recursive:!0}){s!=null&&s.recursive&&f.listFiles(e,r).forEach(i=>{const n=`${r}/${i}`;f.isDir(e,n)?f.rmdir(e,n,s):f.unlink(e,n)}),e.rmdir(r)}static listFiles(e,r,s={prependPath:!1}){if(!f.fileExists(e,r))return[];try{const i=e.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(e,r){return f.fileExists(e,r)?e.isDir(e.lookupPath(r).node.mode):!1}static fileExists(e,r){try{return e.lookupPath(r),!0}catch{return!1}}static mkdir(e,r){e.mkdirTree(r)}static copyRecursive(e,r,s){const i=e.lookupPath(r).node;if(e.isDir(i.mode)){e.mkdirTree(s);const n=e.readdir(r).filter(o=>o!=="."&&o!=="..");for(const o of n)f.copyRecursive(e,joinPaths(r,o),joinPaths(s,o))}else e.writeFile(s,e.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 _private=new WeakMap;class PHPWorker{constructor(e,r){this.absoluteUrl="",this.documentRoot="",_private.set(this,{monitor:r}),e&&this.__internal_setRequestHandler(e)}__internal_setRequestHandler(e){this.absoluteUrl=e.absoluteUrl,this.documentRoot=e.documentRoot,_private.set(this,{..._private.get(this),requestHandler:e})}__internal_getPHP(){return _private.get(this).php}async setPrimaryPHP(e){_private.set(this,{..._private.get(this),php:e})}pathToInternalUrl(e){return _private.get(this).requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return _private.get(this).requestHandler.internalUrlToPath(e)}async onDownloadProgress(e){var r;return(r=_private.get(this).monitor)==null?void 0:r.addEventListener("progress",e)}async mv(e,r){return _private.get(this).php.mv(e,r)}async rmdir(e,r){return _private.get(this).php.rmdir(e,r)}async request(e){return await _private.get(this).requestHandler.request(e)}async run(e){const{php:r,reap:s}=await _private.get(this).requestHandler.processManager.acquirePHPInstance();try{return await r.run(e)}finally{s()}}chdir(e){return _private.get(this).php.chdir(e)}setSapiName(e){_private.get(this).php.setSapiName(e)}mkdir(e){return _private.get(this).php.mkdir(e)}mkdirTree(e){return _private.get(this).php.mkdirTree(e)}readFileAsText(e){return _private.get(this).php.readFileAsText(e)}readFileAsBuffer(e){return _private.get(this).php.readFileAsBuffer(e)}writeFile(e,r){return _private.get(this).php.writeFile(e,r)}unlink(e){return _private.get(this).php.unlink(e)}listFiles(e,r){return _private.get(this).php.listFiles(e,r)}isDir(e){return _private.get(this).php.isDir(e)}fileExists(e){return _private.get(this).php.fileExists(e)}onMessage(e){_private.get(this).php.onMessage(e)}defineConstant(e,r){_private.get(this).php.defineConstant(e,r)}addEventListener(e,r){_private.get(this).php.addEventListener(e,r)}removeEventListener(e,r){_private.get(this).php.removeEventListener(e,r)}}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(e,r,s,i="",n=0){this.httpStatusCode=e,this.headers=r,this.bytes=s,this.exitCode=n,this.errors=i}static forHttpCode(e,r=""){return new PHPResponse(e,{},new TextEncoder().encode(r||responseTexts[e]||""))}static fromRawData(e){return new PHPResponse(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}const RuntimeId=Symbol("RuntimeId"),loadedRuntimes=new Map;let lastRuntimeId=0;async function loadPHPRuntime(t,e={}){const[r,s,i]=makePromise(),n=t.init(currentJsRuntime,{onAbort(a){i(a),logger.error(a)},ENV:{},locateFile:a=>a,...e,noInitialRun:!0,onRuntimeInitialized(){e.onRuntimeInitialized&&e.onRuntimeInitialized(),s()}});await r;const o=++lastRuntimeId;return n.id=o,n.originalExit=n._exit,n._exit=function(a){return loadedRuntimes.delete(o),n.originalExit(a)},n[RuntimeId]=o,loadedRuntimes.set(o,n),o}function getLoadedRuntime(t){return loadedRuntimes.get(t)}const currentJsRuntime=function(){var t;return typeof process<"u"&&((t=process.release)==null?void 0:t.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}(),makePromise=()=>{const t=[],e=new Promise((r,s)=>{t.push(r,s)});return t.unshift(e),t},kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends Event{constructor(e,r={}){super(e),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(t){return t instanceof Error?"exitCode"in t&&(t==null?void 0:t.exitCode)===0||(t==null?void 0:t.name)==="ExitStatus"&&"status"in t&&t.status===0:!1}class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,r){++this.listenersCount,super.addEventListener(e,r)}removeEventListener(e,r){--this.listenersCount,super.removeEventListener(e,r)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(t){const e=new UnhandledRejectionsTarget;for(const r in t.wasmExports)if(typeof t.wasmExports[r]=="function"){const s=t.wasmExports[r];t.wasmExports[r]=function(...i){var n;try{return s(...i)}catch(o){if(!(o instanceof Error))throw o;const a=clarifyErrorMessage(o,(n=t.lastAsyncifyStackSource)==null?void 0:n.stack);if(t.lastAsyncifyStackSource&&(o.cause=t.lastAsyncifyStackSource),e.hasListeners()){e.dispatchEvent(new ErrorEvent("error",{error:o,message:a}));return}throw isExitCodeZero(o)||showCriticalErrorBox(a),o}}}return e}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(t,e){if(t.message==="unreachable"){let r=UNREACHABLE_ERROR;e||(r+=`
5
5
 
6
6
  This stack trace is lacking. For a better one initialize
7
7
  the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
@@ -35,7 +35,7 @@ CLI option:
35
35
  ${eol}
36
36
  ${bold} WASM ERROR${reset}${redBg}`);for(const e of t.split(`
37
37
  `))logger.log(`${eol} ${e} `);logger.log(`${reset}`)}}function extractPHPFunctionsFromStack(t){try{const e=t.split(`
38
- `).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(e))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(e,r,s){super(e),this.response=r,this.source=s}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php";var b,x,E,v,R,M,ee,N,te,U,re,L,se,O,ne,j,ie,D,oe,B,ae,$,le,q,ce,I,K,z,ue,W,pe,G,de;class PHP{constructor(t){p(this,M);p(this,N);p(this,U);p(this,L);p(this,O);p(this,j);p(this,D);p(this,B);p(this,$);p(this,q);p(this,I);p(this,z);p(this,W);p(this,G);p(this,b,void 0);p(this,x,void 0);p(this,E,void 0);p(this,v,void 0);p(this,R,void 0);f(this,x,!1),f(this,E,null),f(this,v,new Map),f(this,R,[]),this.semaphore=new Semaphore({concurrency:1}),t!==void 0&&this.initializeRuntime(t)}addEventListener(t,e){u(this,v).has(t)||u(this,v).set(t,new Set),u(this,v).get(t).add(e)}removeEventListener(t,e){var r;(r=u(this,v).get(t))==null||r.delete(e)}dispatchEvent(t){const e=u(this,v).get(t.type);if(e)for(const r of e)r(t)}onMessage(t){u(this,R).push(t)}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(t){return this.requestHandler.pathToInternalUrl(t)}internalUrlToPath(t){return this.requestHandler.internalUrlToPath(t)}initializeRuntime(t){if(this[__private__dont__use])throw new Error("PHP runtime already initialized.");const e=getLoadedRuntime(t);if(!e)throw new Error("Invalid PHP runtime id.");this[__private__dont__use]=e,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(`
38
+ `).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(e))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(e,r,s){super(e),this.response=r,this.source=s}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php";var x,y,w,g,E,k,Z,A,Q,I,Y,C,K,M,X,N,ee,U,te,L,re,D,se,j,ie,H,J,B,ne,q,oe,O,ae;class PHP{constructor(t){u(this,k);u(this,A);u(this,I);u(this,C);u(this,M);u(this,N);u(this,U);u(this,L);u(this,D);u(this,j);u(this,H);u(this,B);u(this,q);u(this,O);u(this,x,void 0);u(this,y,void 0);u(this,w,void 0);u(this,g,void 0);u(this,E,void 0);h(this,y,!1),h(this,w,null),h(this,g,new Map),h(this,E,[]),this.semaphore=new Semaphore({concurrency:1}),t!==void 0&&this.initializeRuntime(t)}addEventListener(t,e){p(this,g).has(t)||p(this,g).set(t,new Set),p(this,g).get(t).add(e)}removeEventListener(t,e){var r;(r=p(this,g).get(t))==null||r.delete(e)}dispatchEvent(t){const e=p(this,g).get(t.type);if(e)for(const r of e)r(t)}onMessage(t){p(this,E).push(t)}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(t){return this.requestHandler.pathToInternalUrl(t)}internalUrlToPath(t){return this.requestHandler.internalUrlToPath(t)}initializeRuntime(t){if(this[__private__dont__use])throw new Error("PHP runtime already initialized.");const e=getLoadedRuntime(t);if(!e)throw new Error("Invalid PHP runtime id.");this[__private__dont__use]=e,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(`
39
39
  `)),this.fileExists(AUTO_PREPEND_SCRIPT)||this.writeFile(AUTO_PREPEND_SCRIPT,`<?php
40
40
  // Define constants set via defineConstant() calls
41
41
  if(file_exists('/internal/shared/consts.json')) {
@@ -50,12 +50,10 @@ ${bold} WASM ERROR${reset}${redBg}`);for(const e of t.split(`
50
50
  foreach (glob('/internal/shared/preload/*.php') as $file) {
51
51
  require_once $file;
52
52
  }
53
- `),e.onMessage=async r=>{for(const s of u(this,R)){const n=await s(r);if(n)return n}return""},f(this,E,improveWASMErrorReporting(e)),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(t){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[t])!==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?");f(this,b,t)}chdir(t){this[__private__dont__use].FS.chdir(t)}async request(t){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(t)}async run(t){const e=await this.semaphore.acquire();let r;try{if(u(this,x)||(h(this,N,te).call(this),f(this,x,!0)),t.scriptPath&&!this.fileExists(t.scriptPath))throw new Error(`The script path "${t.scriptPath}" does not exist.`);h(this,L,se).call(this,t.relativeUri||""),h(this,B,ae).call(this,t.method||"GET");const s=normalizeHeaders(t.headers||{}),n=s.host||"example.com:443",i=h(this,D,oe).call(this,n,t.protocol||"http");h(this,O,ne).call(this,n),h(this,j,ie).call(this,i),h(this,$,le).call(this,s),t.body&&(r=h(this,q,ce).call(this,t.body)),typeof t.code=="string"?(this.writeFile("/internal/eval.php",t.code),h(this,I,K).call(this,"/internal/eval.php")):h(this,I,K).call(this,t.scriptPath||"");const o=h(this,M,ee).call(this,t.$_SERVER,s,i);for(const a in o)h(this,z,ue).call(this,a,o[a]);const l=t.env||{};for(const a in l)h(this,W,pe).call(this,a,l[a]);const c=await h(this,G,de).call(this);if(c.exitCode!==0){logger.warn("PHP.run() output was:",c.text);const a=new PHPExecutionFailureError(`PHP.run() failed with exit code ${c.exitCode} and the following output: `+c.errors,c,"request");throw logger.error(a),a}return c}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{e(),this.dispatchEvent({type:"request.end"})}}}defineConstant(t,e){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,[t]:e}))}mkdir(t){return FSHelpers.mkdir(this[__private__dont__use].FS,t)}mkdirTree(t){return FSHelpers.mkdir(this[__private__dont__use].FS,t)}readFileAsText(t){return FSHelpers.readFileAsText(this[__private__dont__use].FS,t)}readFileAsBuffer(t){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,t)}writeFile(t,e){return FSHelpers.writeFile(this[__private__dont__use].FS,t,e)}unlink(t){return FSHelpers.unlink(this[__private__dont__use].FS,t)}mv(t,e){return FSHelpers.mv(this[__private__dont__use].FS,t,e)}rmdir(t,e={recursive:!0}){return FSHelpers.rmdir(this[__private__dont__use].FS,t,e)}listFiles(t,e={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,t,e)}isDir(t){return FSHelpers.isDir(this[__private__dont__use].FS,t)}fileExists(t){return FSHelpers.fileExists(this[__private__dont__use].FS,t)}hotSwapPHPRuntime(t,e){const r=this[__private__dont__use].FS;try{this.exit()}catch{}this.initializeRuntime(t),u(this,b)&&this.setSapiName(u(this,b)),e&&copyFS(r,this[__private__dont__use].FS,e)}async mount(t,e){return await e(this,this[__private__dont__use].FS,t)}async cli(t){for(const e of t)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[e]);try{return await this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}catch(e){if(isExitCodeZero(e))return 0;throw e}}setSkipShebang(t){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[t?1:0])}exit(t=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(t)}catch{}f(this,x,!1),f(this,E,null),delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}[Symbol.dispose](){u(this,x)&&this.exit(0)}}b=new WeakMap,x=new WeakMap,E=new WeakMap,v=new WeakMap,R=new WeakMap,M=new WeakSet,ee=function(t,e,r){const s={...t||{}};s.HTTPS=s.HTTPS||r===443?"on":"off";for(const n in e){let i="HTTP_";["content-type","content-length"].includes(n.toLowerCase())&&(i=""),s[`${i}${n.toUpperCase().replace(/-/g,"_")}`]=e[n]}return s},N=new WeakSet,te=function(){this[__private__dont__use].ccall("php_wasm_init",null,[],[])},U=new WeakSet,re=function(){const t="/internal/headers.json";if(!this.fileExists(t))throw new Error("SAPI Error: Could not find response headers file.");const e=JSON.parse(this.readFileAsText(t)),r={};for(const s of e.headers){if(!s.includes(": "))continue;const n=s.indexOf(": "),i=s.substring(0,n).toLowerCase(),o=s.substring(n+2);i in r||(r[i]=[]),r[i].push(o)}return{headers:r,httpStatusCode:e.status}},L=new WeakSet,se=function(t){if(this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[t]),t.includes("?")){const e=t.substring(t.indexOf("?")+1);this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])}},O=new WeakSet,ne=function(t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[t])},j=new WeakSet,ie=function(t){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[t])},D=new WeakSet,oe=function(t,e){let r;try{r=parseInt(new URL(t).port,10)}catch{}return(!r||isNaN(r)||r===80)&&(r=e==="https"?443:80),r},B=new WeakSet,ae=function(t){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[t])},$=new WeakSet,le=function(t){t.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[t.cookie]),t["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[t["content-type"]]),t["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(t["content-length"],10)])},q=new WeakSet,ce=function(t){let e,r;typeof t=="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(t),e=r+1):(r=t.byteLength,e=t.byteLength);const s=this[__private__dont__use].malloc(e);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof t=="string"?this[__private__dont__use].stringToUTF8(t,s,e+1):this[__private__dont__use].HEAPU8.set(t,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},I=new WeakSet,K=function(t){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[t])},z=new WeakSet,ue=function(t,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[t,e])},W=new WeakSet,pe=function(t,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[t,e])},G=new WeakSet,de=async function(){var n;let t,e;try{t=await new Promise((i,o)=>{var c;e=a=>{logger.error(a),logger.error(a.error);const d=new Error("Rethrown");d.cause=a.error,d.betterMessage=a.message,o(d)},(c=u(this,E))==null||c.addEventListener("error",e);const l=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return l instanceof Promise?l.then(i,o):i(l)})}catch(i){for(const a in this)typeof this[a]=="function"&&(this[a]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify();const o=i,l="betterMessage"in o?o.betterMessage:o.message,c=new Error(l);throw c.cause=o,logger.error(c),c}finally{(n=u(this,E))==null||n.removeEventListener("error",e)}const{headers:r,httpStatusCode:s}=h(this,U,re).call(this);return new PHPResponse(t===0?s:500,r,this.readFileAsBuffer("/internal/stdout"),this.readFileAsText("/internal/stderr"),t)};function normalizeHeaders(t){const e={};for(const r in t)e[r.toLowerCase()]=t[r];return e}function copyFS(t,e,r){let s;try{s=t.lookupPath(r)}catch{return}if(!("contents"in s.node))return;if(!t.isDir(s.node.mode)){e.writeFile(r,t.readFile(r));return}e.mkdirTree(r);const n=t.readdir(r).filter(i=>i!=="."&&i!=="..");for(const i of n)copyFS(t,e,joinPaths(r,i))}const{hasOwnProperty}=Object.prototype,encode=(t,e={})=>{typeof e=="string"&&(e={section:e}),e.align=e.align===!0,e.newline=e.newline===!0,e.sort=e.sort===!0,e.whitespace=e.whitespace===!0||e.align===!0,e.platform=e.platform||typeof process<"u"&&process.platform,e.bracketedArray=e.bracketedArray!==!1;const r=e.platform==="win32"?`\r
54
- `:`
55
- `,s=e.whitespace?" = ":"=",n=[],i=e.sort?Object.keys(t).sort():Object.keys(t);let o=0;e.align&&(o=safe(i.filter(a=>t[a]===null||Array.isArray(t[a])||typeof t[a]!="object").map(a=>Array.isArray(t[a])?`${a}[]`:a).concat([""]).reduce((a,d)=>safe(a).length>=safe(d).length?a:d)).length);let l="";const c=e.bracketedArray?"[]":"";for(const a of i){const d=t[a];if(d&&Array.isArray(d))for(const m of d)l+=safe(`${a}${c}`).padEnd(o," ")+s+safe(m)+r;else d&&typeof d=="object"?n.push(a):l+=safe(a).padEnd(o," ")+s+safe(d)+r}e.section&&l.length&&(l="["+safe(e.section)+"]"+(e.newline?r+r:r)+l);for(const a of n){const d=splitSections(a,".").join("\\."),m=(e.section?e.section+".":"")+d,y=encode(t[a],{...e,section:m});l.length&&y.length&&(l+=r),l+=y}return l};function splitSections(t,e){var r=0,s=0,n=0,i=[];do if(n=t.indexOf(e,r),n!==-1){if(r=n+e.length,n>0&&t[n-1]==="\\")continue;i.push(t.slice(s,n)),s=n+e.length}while(n!==-1);return i.push(t.slice(s)),i}const decode=(t,e={})=>{e.bracketedArray=e.bracketedArray!==!1;const r=Object.create(null);let s=r,n=null;const i=/^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i,o=t.split(/[\r\n]+/g),l={};for(const a of o){if(!a||a.match(/^\s*[;#]/)||a.match(/^\s*$/))continue;const d=a.match(i);if(!d)continue;if(d[1]!==void 0){if(n=unsafe(d[1]),n==="__proto__"){s=Object.create(null);continue}s=r[n]=r[n]||Object.create(null);continue}const m=unsafe(d[2]);let y;e.bracketedArray?y=m.length>2&&m.slice(-2)==="[]":(l[m]=((l==null?void 0:l[m])||0)+1,y=l[m]>1);const _=y?m.slice(0,-2):m;if(_==="__proto__")continue;const A=d[3]?unsafe(d[4]):!0,X=A==="true"||A==="false"||A==="null"?JSON.parse(A):A;y&&(hasOwnProperty.call(s,_)?Array.isArray(s[_])||(s[_]=[s[_]]):s[_]=[]),Array.isArray(s[_])?s[_].push(X):s[_]=X}const c=[];for(const a of Object.keys(r)){if(!hasOwnProperty.call(r,a)||typeof r[a]!="object"||Array.isArray(r[a]))continue;const d=splitSections(a,".");s=r;const m=d.pop(),y=m.replace(/\\\./g,".");for(const _ of d)_!=="__proto__"&&((!hasOwnProperty.call(s,_)||typeof s[_]!="object")&&(s[_]=Object.create(null)),s=s[_]);s===r&&y===m||(s[y]=r[a],c.push(a))}for(const a of c)delete r[a];return r},isQuoted=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),safe=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&isQuoted(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),unsafe=t=>{if(t=(t||"").trim(),isQuoted(t)){t.charAt(0)==="'"&&(t=t.slice(1,-1));try{t=JSON.parse(t)}catch{}}else{let e=!1,r="";for(let s=0,n=t.length;s<n;s++){const i=t.charAt(s);if(e)"\\;#".indexOf(i)!==-1?r+=i:r+="\\"+i,e=!1;else{if(";#".indexOf(i)!==-1)break;i==="\\"?e=!0:r+=i}}return e&&(r+="\\"),r.trim()}return t};var ini={parse:decode,decode,stringify:encode,encode,safe,unsafe};async function getPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));if(e===void 0)return r;const s={};for(const n of e)s[n]=r[n];return s}async function setPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));for(const[s,n]of Object.entries(e))n==null?delete r[s]:r[s]=n;await t.writeFile(PHP_INI_PATH,ini.stringify(r))}async function withPHPIniValues(t,e,r){const s=await t.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(t,e),await r()}finally{await t.writeFile(PHP_INI_PATH,s)}}class HttpCookieStore{constructor(){this.cookies={}}rememberCookiesFromResponseHeaders(e){if(e!=null&&e["set-cookie"])for(const r of e["set-cookie"])try{if(!r.includes("="))continue;const s=r.indexOf("="),n=r.substring(0,s),i=r.substring(s+1).split(";")[0];this.cookies[n]=i}catch(s){logger.error(s)}}getCookieRequestHeader(){const e=[];for(const r in this.cookies)e.push(`${r}=${this.cookies[r]}`);return e.join("; ")}}function concatUint8Array(...t){const e=new Uint8Array(t.reduce((s,n)=>s+n.length,0));let r=0;for(const s of t)e.set(s,r),r+=s.length;return e}function concatBytes(t){if(t===void 0){let e=new Uint8Array;return new TransformStream({transform(r){e=concatUint8Array(e,r)},flush(r){r.enqueue(e)}})}else{const e=new ArrayBuffer(t||0);let r=0;return new TransformStream({transform(s){new Uint8Array(e).set(s,r),r+=s.byteLength},flush(s){s.enqueue(new Uint8Array(e))}})}}function limitBytes(t,e){if(e===0)return new ReadableStream({start(n){n.close()}});const r=t.getReader({mode:"byob"});let s=0;return new ReadableStream({async pull(n){const{value:i,done:o}=await r.read(new Uint8Array(e-s));if(o){r.releaseLock(),n.close();return}s+=i.length,n.enqueue(i),s>=e&&(r.releaseLock(),n.close())},cancel(){r.cancel()}})}async function collectBytes(t,e){return e!==void 0&&(t=limitBytes(t,e)),await t.pipeThrough(concatBytes(e)).getReader().read().then(({value:r})=>r)}class StreamedFile extends File{constructor(e,r,s){super([],r,{type:s}),this.readableStream=e}slice(){throw new Error("slice() is not possible on a StreamedFile")}stream(){return this.readableStream}async text(){return new TextDecoder().decode(await this.arrayBuffer())}async arrayBuffer(){return await collectBytes(this.stream())}}ReadableStream.prototype[Symbol.asyncIterator]||(ReadableStream.prototype[Symbol.asyncIterator]=async function*(){const t=this.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)return;yield r}}finally{t.releaseLock()}},ReadableStream.prototype.iterate=ReadableStream.prototype[Symbol.asyncIterator]);function streamReadFileFromPHP(t,e){return new ReadableStream({async pull(r){const s=await t.readFileAsBuffer(e);r.enqueue(s),r.close()}})}async function*iteratePhpFiles(t,e,{relativePaths:r=!0,pathPrefix:s,exceptPaths:n=[]}={}){e=normalizePath(e);const i=[e];for(;i.length;){const o=i.pop();if(!o)return;const l=await t.listFiles(o);for(const c of l){const a=`${o}/${c}`;if(n.includes(a.substring(e.length+1)))continue;await t.isDir(a)?i.push(a):yield new StreamedFile(streamReadFileFromPHP(t,a),r?joinPaths(s||"",a.substring(e.length+1)):a)}}}function writeFilesStreamToPhp(t,e){return new WritableStream({async write(r){const s=joinPaths(e,r.name);r.type==="directory"?await t.mkdir(s):(await t.mkdir(dirname(s)),await t.writeFile(s,new Uint8Array(await r.arrayBuffer())))}})}class MaxPhpInstancesError extends Error{constructor(e){super(`Requested more concurrent PHP instances than the limit (${e}).`),this.name=this.constructor.name}}class PHPProcessManager{constructor(e){this.primaryIdle=!0,this.nextInstance=null,this.allInstances=[],this.maxPhpInstances=(e==null?void 0:e.maxPhpInstances)??5,this.phpFactory=e==null?void 0:e.phpFactory,this.primaryPhp=e==null?void 0:e.primaryPhp,this.semaphore=new Semaphore({concurrency:this.maxPhpInstances,timeout:(e==null?void 0:e.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 e=await this.spawn({isPrimary:!0});this.primaryPhp=e.php}return this.primaryPhp}async acquirePHPInstance(){if(this.primaryIdle)return this.primaryIdle=!1,{php:await this.getPrimaryPhp(),reap:()=>this.primaryIdle=!0};const e=this.nextInstance||this.spawn({isPrimary:!1});return this.semaphore.remaining>0?this.nextInstance=this.spawn({isPrimary:!1}):this.nextInstance=null,await e}spawn(e){if(e.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(e);this.allInstances.push(r);const s=()=>{this.allInstances=this.allInstances.filter(n=>n!==r)};return r.catch(n=>{throw s(),n}).then(n=>({...n,reap:()=>{s(),n.reap()}}))}async doSpawn(e){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(e);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(e=>e.then(({reap:r})=>r())))}}const SupportedPHPVersions=["8.3","8.2","8.1","8.0","7.4","7.3","7.2","7.1","7.0"],LatestSupportedPHPVersion=SupportedPHPVersions[0],SupportedPHPVersionsList=SupportedPHPVersions,SupportedPHPExtensionsList=["iconv","mbstring","xml-bundle","gd"],SupportedPHPExtensionBundles={"kitchen-sink":SupportedPHPExtensionsList,light:[]},DEFAULT_BASE_URL="http://example.com";function toRelativeUrl(t){return t.toString().substring(t.origin.length)}function removePathPrefix(t,e){return!e||!t.startsWith(e)?t:t.substring(e.length)}function ensurePathPrefix(t,e){return!e||t.startsWith(e)?t:e+t}async function encodeAsMultipart(t){const e=`----${Math.random().toString(36).slice(2)}`,r=`multipart/form-data; boundary=${e}`,s=new TextEncoder,n=[];for(const[c,a]of Object.entries(t))n.push(`--${e}\r
56
- `),n.push(`Content-Disposition: form-data; name="${c}"`),a instanceof File&&n.push(`; filename="${a.name}"`),n.push(`\r
57
- `),a instanceof File&&(n.push("Content-Type: application/octet-stream"),n.push(`\r
58
- `)),n.push(`\r
59
- `),a instanceof File?n.push(await fileToUint8Array(a)):n.push(a),n.push(`\r
60
- `);n.push(`--${e}--\r
61
- `);const i=n.reduce((c,a)=>c+a.length,0),o=new Uint8Array(i);let l=0;for(const c of n)o.set(typeof c=="string"?s.encode(c):c,l),l+=c.length;return{bytes:o,contentType:r}}function fileToUint8Array(t){return new Promise(e=>{const r=new FileReader;r.onload=()=>{e(new Uint8Array(r.result))},r.readAsArrayBuffer(t)})}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};var w,F,C,S,H,P,T,k,V,he,J,fe,Q,me,Z,_e;class PHPRequestHandler{constructor(e){p(this,V);p(this,J);p(this,Q);p(this,Z);p(this,w,void 0);p(this,F,void 0);p(this,C,void 0);p(this,S,void 0);p(this,H,void 0);p(this,P,void 0);p(this,T,void 0);p(this,k,void 0);const{documentRoot:r="/www/",absoluteUrl:s=typeof location=="object"?location==null?void 0:location.href:"",rewriteRules:n=[]}=e;"processManager"in e?this.processManager=e.processManager:this.processManager=new PHPProcessManager({phpFactory:async l=>{const c=await e.phpFactory({...l,requestHandler:this});return c.requestHandler=this,c},maxPhpInstances:e.maxPhpInstances}),f(this,k,new HttpCookieStore),f(this,w,r);const i=new URL(s);f(this,C,i.hostname),f(this,S,i.port?Number(i.port):i.protocol==="https:"?443:80),f(this,F,(i.protocol||"").replace(":",""));const o=u(this,S)!==443&&u(this,S)!==80;f(this,H,[u(this,C),o?`:${u(this,S)}`:""].join("")),f(this,P,i.pathname.replace(/\/+$/,"")),f(this,T,[`${u(this,F)}://`,u(this,H),u(this,P)].join("")),this.rewriteRules=n}async getPrimaryPhp(){return await this.processManager.getPrimaryPhp()}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const r=new URL(e);return r.pathname.startsWith(u(this,P))&&(r.pathname=r.pathname.slice(u(this,P).length)),toRelativeUrl(r)}get absoluteUrl(){return u(this,T)}get documentRoot(){return u(this,w)}async request(e){const r=e.url.startsWith("http://")||e.url.startsWith("https://"),s=new URL(e.url.split("#")[0],r?void 0:DEFAULT_BASE_URL),n=applyRewriteRules(removePathPrefix(decodeURIComponent(s.pathname),u(this,P)),this.rewriteRules),i=joinPaths(u(this,w),n);return seemsLikeAPHPRequestHandlerPath(i)?h(this,J,fe).call(this,e,s):h(this,V,he).call(this,await this.processManager.getPrimaryPhp(),i)}}w=new WeakMap,F=new WeakMap,C=new WeakMap,S=new WeakMap,H=new WeakMap,P=new WeakMap,T=new WeakMap,k=new WeakMap,V=new WeakSet,he=function(e,r){if(!e.fileExists(r))return new PHPResponse(404,{"x-file-type":["static"]},new TextEncoder().encode("404 File not found"));const s=e.readFileAsBuffer(r);return new PHPResponse(200,{"content-length":[`${s.byteLength}`],"content-type":[inferMimeType(r)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)},J=new WeakSet,fe=async function(e,r){let s;try{s=await this.processManager.acquirePHPInstance()}catch(n){return n instanceof MaxPhpInstancesError?PHPResponse.forHttpCode(502):PHPResponse.forHttpCode(500)}try{return await h(this,Q,me).call(this,s.php,e,r)}finally{s.reap()}},Q=new WeakSet,me=async function(e,r,s){let n="GET";const i={host:u(this,H),...normalizeHeaders(r.headers||{}),cookie:u(this,k).getCookieRequestHeader()};let o=r.body;if(typeof o=="object"&&!(o instanceof Uint8Array)){n="POST";const{bytes:c,contentType:a}=await encodeAsMultipart(o);o=c,i["content-type"]=a}let l;try{l=h(this,Z,_e).call(this,e,decodeURIComponent(s.pathname))}catch{return PHPResponse.forHttpCode(404)}try{const c=await e.run({relativeUri:ensurePathPrefix(toRelativeUrl(s),u(this,P)),protocol:u(this,F),method:r.method||n,$_SERVER:{REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:u(this,w),HTTPS:u(this,T).startsWith("https://")?"on":""},body:o,scriptPath:l,headers:i});return u(this,k).rememberCookiesFromResponseHeaders(c.headers),c}catch(c){const a=c;if(a!=null&&a.response)return a.response;throw c}},Z=new WeakSet,_e=function(e,r){let s=removePathPrefix(r,u(this,P));s=applyRewriteRules(s,this.rewriteRules),s.includes(".php")?s=s.split(".php")[0]+".php":e.isDir(`${u(this,w)}${s}`)?(s.endsWith("/")||(s=`${s}/`),s=`${s}index.php`):s="/index.php";let n=`${u(this,w)}${s}`;if(e.fileExists(n)||(n=`${u(this,w)}/index.php`),e.fileExists(n))return n;throw new Error(`File not found: ${n}`)};function inferMimeType(t){const e=t.split(".").pop();return mimeTypes[e]||mimeTypes._default}function seemsLikeAPHPRequestHandlerPath(t){return seemsLikeAPHPFile(t)||seemsLikeADirectoryRoot(t)}function seemsLikeAPHPFile(t){return t.endsWith(".php")||t.includes(".php/")}function seemsLikeADirectoryRoot(t){return!t.split("/").pop().includes(".")}function applyRewriteRules(t,e){for(const r of e)if(new RegExp(r.match).test(t))return t.replace(r.match,r.replacement);return t}function rotatePHPRuntime({php:t,cwd:e,recreateRuntime:r,maxRequests:s=400}){let n=0;async function i(){if(++n<s)return;n=0;const o=await t.semaphore.acquire();try{t.hotSwapPHPRuntime(await r(),e)}finally{o()}}return t.addEventListener("request.end",i),function(){t.removeEventListener("request.end",i)}}async function writeFiles(t,e,r,{rmRoot:s=!1}={}){s&&await t.isDir(e)&&await t.rmdir(e,{recursive:!0});for(const[n,i]of Object.entries(r)){const o=joinPaths(e,n);await t.fileExists(dirname(o))||await t.mkdir(dirname(o)),i instanceof Uint8Array||typeof i=="string"?await t.writeFile(o,i):await writeFiles(t,o,i)}}function proxyFileSystem(t,e,r){const s=Object.getOwnPropertySymbols(t)[0];for(const n of r)e.fileExists(n)||e.mkdir(n),t.fileExists(n)||t.mkdir(n),e[s].FS.mount(e[s].PROXYFS,{root:n,fs:t[s].FS},n)}exports.DEFAULT_BASE_URL=DEFAULT_BASE_URL;exports.FSHelpers=FSHelpers;exports.HttpCookieStore=HttpCookieStore;exports.LatestSupportedPHPVersion=LatestSupportedPHPVersion;exports.PHP=PHP;exports.PHPProcessManager=PHPProcessManager;exports.PHPRequestHandler=PHPRequestHandler;exports.PHPResponse=PHPResponse;exports.PHPWorker=PHPWorker;exports.SupportedPHPExtensionBundles=SupportedPHPExtensionBundles;exports.SupportedPHPExtensionsList=SupportedPHPExtensionsList;exports.SupportedPHPVersions=SupportedPHPVersions;exports.SupportedPHPVersionsList=SupportedPHPVersionsList;exports.UnhandledRejectionsTarget=UnhandledRejectionsTarget;exports.__private__dont__use=__private__dont__use;exports.applyRewriteRules=applyRewriteRules;exports.ensurePathPrefix=ensurePathPrefix;exports.getPhpIniEntries=getPhpIniEntries;exports.isExitCodeZero=isExitCodeZero;exports.iterateFiles=iteratePhpFiles;exports.loadPHPRuntime=loadPHPRuntime;exports.proxyFileSystem=proxyFileSystem;exports.removePathPrefix=removePathPrefix;exports.rotatePHPRuntime=rotatePHPRuntime;exports.setPhpIniEntries=setPhpIniEntries;exports.toRelativeUrl=toRelativeUrl;exports.withPHPIniValues=withPHPIniValues;exports.writeFiles=writeFiles;exports.writeFilesStreamToPhp=writeFilesStreamToPhp;
53
+ `),e.onMessage=async r=>{for(const s of p(this,E)){const i=await s(r);if(i)return i}return""},h(this,w,improveWASMErrorReporting(e)),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(t){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[t])!==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?");h(this,x,t)}chdir(t){this[__private__dont__use].FS.chdir(t)}async request(t){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(t)}async run(t){const e=await this.semaphore.acquire();let r;try{if(p(this,y)||(d(this,A,Q).call(this),h(this,y,!0)),t.scriptPath&&!this.fileExists(t.scriptPath))throw new Error(`The script path "${t.scriptPath}" does not exist.`);d(this,C,K).call(this,t.relativeUri||""),d(this,L,re).call(this,t.method||"GET");const s=normalizeHeaders(t.headers||{}),i=s.host||"example.com:443",n=d(this,U,te).call(this,i,t.protocol||"http");d(this,M,X).call(this,i),d(this,N,ee).call(this,n),d(this,D,se).call(this,s),t.body&&(r=d(this,j,ie).call(this,t.body)),typeof t.code=="string"?(this.writeFile("/internal/eval.php",t.code),d(this,H,J).call(this,"/internal/eval.php")):d(this,H,J).call(this,t.scriptPath||"");const o=d(this,k,Z).call(this,t.$_SERVER,s,n);for(const c in o)d(this,B,ne).call(this,c,o[c]);const a=t.env||{};for(const c in a)d(this,q,oe).call(this,c,a[c]);const l=await d(this,O,ae).call(this);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{e(),this.dispatchEvent({type:"request.end"})}}}defineConstant(t,e){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,[t]:e}))}mkdir(t){return FSHelpers.mkdir(this[__private__dont__use].FS,t)}mkdirTree(t){return FSHelpers.mkdir(this[__private__dont__use].FS,t)}readFileAsText(t){return FSHelpers.readFileAsText(this[__private__dont__use].FS,t)}readFileAsBuffer(t){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,t)}writeFile(t,e){return FSHelpers.writeFile(this[__private__dont__use].FS,t,e)}unlink(t){return FSHelpers.unlink(this[__private__dont__use].FS,t)}mv(t,e){return FSHelpers.mv(this[__private__dont__use].FS,t,e)}rmdir(t,e={recursive:!0}){return FSHelpers.rmdir(this[__private__dont__use].FS,t,e)}listFiles(t,e={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,t,e)}isDir(t){return FSHelpers.isDir(this[__private__dont__use].FS,t)}fileExists(t){return FSHelpers.fileExists(this[__private__dont__use].FS,t)}hotSwapPHPRuntime(t,e){const r=this[__private__dont__use].FS;try{this.exit()}catch{}this.initializeRuntime(t),p(this,x)&&this.setSapiName(p(this,x)),e&&copyFS(r,this[__private__dont__use].FS,e)}async mount(t,e){return await e(this,this[__private__dont__use].FS,t)}async cli(t){for(const e of t)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[e]);try{return await this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}catch(e){if(isExitCodeZero(e))return 0;throw e}}setSkipShebang(t){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[t?1:0])}exit(t=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(t)}catch{}h(this,y,!1),h(this,w,null),delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}[Symbol.dispose](){p(this,y)&&this.exit(0)}}x=new WeakMap,y=new WeakMap,w=new WeakMap,g=new WeakMap,E=new WeakMap,k=new WeakSet,Z=function(t,e,r){const s={...t||{}};s.HTTPS=s.HTTPS||r===443?"on":"off";for(const i in e){let n="HTTP_";["content-type","content-length"].includes(i.toLowerCase())&&(n=""),s[`${n}${i.toUpperCase().replace(/-/g,"_")}`]=e[i]}return s},A=new WeakSet,Q=function(){this[__private__dont__use].ccall("php_wasm_init",null,[],[])},I=new WeakSet,Y=function(){const t="/internal/headers.json";if(!this.fileExists(t))throw new Error("SAPI Error: Could not find response headers file.");const e=JSON.parse(this.readFileAsText(t)),r={};for(const s of e.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:e.status}},C=new WeakSet,K=function(t){if(this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[t]),t.includes("?")){const e=t.substring(t.indexOf("?")+1);this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])}},M=new WeakSet,X=function(t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[t])},N=new WeakSet,ee=function(t){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[t])},U=new WeakSet,te=function(t,e){let r;try{r=parseInt(new URL(t).port,10)}catch{}return(!r||isNaN(r)||r===80)&&(r=e==="https"?443:80),r},L=new WeakSet,re=function(t){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[t])},D=new WeakSet,se=function(t){t.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[t.cookie]),t["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[t["content-type"]]),t["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(t["content-length"],10)])},j=new WeakSet,ie=function(t){let e,r;typeof t=="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(t),e=r+1):(r=t.byteLength,e=t.byteLength);const s=this[__private__dont__use].malloc(e);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof t=="string"?this[__private__dont__use].stringToUTF8(t,s,e+1):this[__private__dont__use].HEAPU8.set(t,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},H=new WeakSet,J=function(t){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[t])},B=new WeakSet,ne=function(t,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[t,e])},q=new WeakSet,oe=function(t,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[t,e])},O=new WeakSet,ae=async function(){var i;let t,e;try{t=await new Promise((n,o)=>{var l;e=c=>{logger.error(c),logger.error(c.error);const P=new Error("Rethrown");P.cause=c.error,P.betterMessage=c.message,o(P)},(l=p(this,w))==null||l.addEventListener("error",e);const a=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return a instanceof Promise?a.then(n,o):n(a)})}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 o=n,a="betterMessage"in o?o.betterMessage:o.message,l=new Error(a);throw l.cause=o,logger.error(l),l}finally{(i=p(this,w))==null||i.removeEventListener("error",e)}const{headers:r,httpStatusCode:s}=d(this,I,Y).call(this);return new PHPResponse(t===0?s:500,r,this.readFileAsBuffer("/internal/stdout"),this.readFileAsText("/internal/stderr"),t)};function normalizeHeaders(t){const e={};for(const r in t)e[r.toLowerCase()]=t[r];return e}function copyFS(t,e,r){let s;try{s=t.lookupPath(r)}catch{return}if(!("contents"in s.node))return;if(!t.isDir(s.node.mode)){e.writeFile(r,t.readFile(r));return}e.mkdirTree(r);const i=t.readdir(r).filter(n=>n!=="."&&n!=="..");for(const n of i)copyFS(t,e,joinPaths(r,n))}async function getPhpIniEntries(t,e){const r=ini_js.parse(await t.readFileAsText(PHP_INI_PATH));if(e===void 0)return r;const s={};for(const i of e)s[i]=r[i];return s}async function setPhpIniEntries(t,e){const r=ini_js.parse(await t.readFileAsText(PHP_INI_PATH));for(const[s,i]of Object.entries(e))i==null?delete r[s]:r[s]=i;await t.writeFile(PHP_INI_PATH,ini_js.stringify(r))}async function withPHPIniValues(t,e,r){const s=await t.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(t,e),await r()}finally{await t.writeFile(PHP_INI_PATH,s)}}class HttpCookieStore{constructor(){this.cookies={}}rememberCookiesFromResponseHeaders(e){if(e!=null&&e["set-cookie"])for(const r of e["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 e=[];for(const r in this.cookies)e.push(`${r}=${this.cookies[r]}`);return e.join("; ")}}function concatUint8Array(...t){const e=new Uint8Array(t.reduce((s,i)=>s+i.length,0));let r=0;for(const s of t)e.set(s,r),r+=s.length;return e}function concatBytes(t){if(t===void 0){let e=new Uint8Array;return new TransformStream({transform(r){e=concatUint8Array(e,r)},flush(r){r.enqueue(e)}})}else{const e=new ArrayBuffer(t||0);let r=0;return new TransformStream({transform(s){new Uint8Array(e).set(s,r),r+=s.byteLength},flush(s){s.enqueue(new Uint8Array(e))}})}}function limitBytes(t,e){if(e===0)return new ReadableStream({start(i){i.close()}});const r=t.getReader({mode:"byob"});let s=0;return new ReadableStream({async pull(i){const{value:n,done:o}=await r.read(new Uint8Array(e-s));if(o){r.releaseLock(),i.close();return}s+=n.length,i.enqueue(n),s>=e&&(r.releaseLock(),i.close())},cancel(){r.cancel()}})}async function collectBytes(t,e){return e!==void 0&&(t=limitBytes(t,e)),await t.pipeThrough(concatBytes(e)).getReader().read().then(({value:r})=>r)}class StreamedFile extends File{constructor(e,r,s){super([],r,{type:s}),this.readableStream=e}slice(){throw new Error("slice() is not possible on a StreamedFile")}stream(){return this.readableStream}async text(){return new TextDecoder().decode(await this.arrayBuffer())}async arrayBuffer(){return await collectBytes(this.stream())}}ReadableStream.prototype[Symbol.asyncIterator]||(ReadableStream.prototype[Symbol.asyncIterator]=async function*(){const t=this.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)return;yield r}}finally{t.releaseLock()}},ReadableStream.prototype.iterate=ReadableStream.prototype[Symbol.asyncIterator]);function streamReadFileFromPHP(t,e){return new ReadableStream({async pull(r){const s=await t.readFileAsBuffer(e);r.enqueue(s),r.close()}})}async function*iteratePhpFiles(t,e,{relativePaths:r=!0,pathPrefix:s,exceptPaths:i=[]}={}){e=normalizePath(e);const n=[e];for(;n.length;){const o=n.pop();if(!o)return;const a=await t.listFiles(o);for(const l of a){const c=`${o}/${l}`;if(i.includes(c.substring(e.length+1)))continue;await t.isDir(c)?n.push(c):yield new StreamedFile(streamReadFileFromPHP(t,c),r?joinPaths(s||"",c.substring(e.length+1)):c)}}}function writeFilesStreamToPhp(t,e){return new WritableStream({async write(r){const s=joinPaths(e,r.name);r.type==="directory"?await t.mkdir(s):(await t.mkdir(dirname(s)),await t.writeFile(s,new Uint8Array(await r.arrayBuffer())))}})}class MaxPhpInstancesError extends Error{constructor(e){super(`Requested more concurrent PHP instances than the limit (${e}).`),this.name=this.constructor.name}}class PHPProcessManager{constructor(e){this.primaryIdle=!0,this.nextInstance=null,this.allInstances=[],this.maxPhpInstances=(e==null?void 0:e.maxPhpInstances)??5,this.phpFactory=e==null?void 0:e.phpFactory,this.primaryPhp=e==null?void 0:e.primaryPhp,this.semaphore=new Semaphore({concurrency:this.maxPhpInstances,timeout:(e==null?void 0:e.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 e=await this.spawn({isPrimary:!0});this.primaryPhp=e.php}return this.primaryPhp}async acquirePHPInstance(){if(this.primaryIdle)return this.primaryIdle=!1,{php:await this.getPrimaryPhp(),reap:()=>this.primaryIdle=!0};const e=this.nextInstance||this.spawn({isPrimary:!1});return this.semaphore.remaining>0?this.nextInstance=this.spawn({isPrimary:!1}):this.nextInstance=null,await e}spawn(e){if(e.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(e);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(e){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(e);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(e=>e.then(({reap:r})=>r())))}}const SupportedPHPVersions=["8.3","8.2","8.1","8.0","7.4","7.3","7.2","7.1","7.0"],LatestSupportedPHPVersion=SupportedPHPVersions[0],SupportedPHPVersionsList=SupportedPHPVersions,SupportedPHPExtensionsList=["iconv","mbstring","xml-bundle","gd"],SupportedPHPExtensionBundles={"kitchen-sink":SupportedPHPExtensionsList,light:[]},DEFAULT_BASE_URL="http://example.com";function toRelativeUrl(t){return t.toString().substring(t.origin.length)}function removePathPrefix(t,e){return!e||!t.startsWith(e)?t:t.substring(e.length)}function ensurePathPrefix(t,e){return!e||t.startsWith(e)?t:e+t}async function encodeAsMultipart(t){const e=`----${Math.random().toString(36).slice(2)}`,r=`multipart/form-data; boundary=${e}`,s=new TextEncoder,i=[];for(const[l,c]of Object.entries(t))i.push(`--${e}\r
54
+ `),i.push(`Content-Disposition: form-data; name="${l}"`),c instanceof File&&i.push(`; filename="${c.name}"`),i.push(`\r
55
+ `),c instanceof File&&(i.push("Content-Type: application/octet-stream"),i.push(`\r
56
+ `)),i.push(`\r
57
+ `),c instanceof File?i.push(await fileToUint8Array(c)):i.push(c),i.push(`\r
58
+ `);i.push(`--${e}--\r
59
+ `);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(t){return new Promise(e=>{const r=new FileReader;r.onload=()=>{e(new Uint8Array(r.result))},r.readAsArrayBuffer(t)})}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};var m,R,T,v,S,_,b,F,$,le,z,ce,W,pe,G,ue;class PHPRequestHandler{constructor(e){u(this,$);u(this,z);u(this,W);u(this,G);u(this,m,void 0);u(this,R,void 0);u(this,T,void 0);u(this,v,void 0);u(this,S,void 0);u(this,_,void 0);u(this,b,void 0);u(this,F,void 0);const{documentRoot:r="/www/",absoluteUrl:s=typeof location=="object"?location==null?void 0:location.href:"",rewriteRules:i=[]}=e;"processManager"in e?this.processManager=e.processManager:this.processManager=new PHPProcessManager({phpFactory:async a=>{const l=await e.phpFactory({...a,requestHandler:this});return l.requestHandler=this,l},maxPhpInstances:e.maxPhpInstances}),h(this,F,new HttpCookieStore),h(this,m,r);const n=new URL(s);h(this,T,n.hostname),h(this,v,n.port?Number(n.port):n.protocol==="https:"?443:80),h(this,R,(n.protocol||"").replace(":",""));const o=p(this,v)!==443&&p(this,v)!==80;h(this,S,[p(this,T),o?`:${p(this,v)}`:""].join("")),h(this,_,n.pathname.replace(/\/+$/,"")),h(this,b,[`${p(this,R)}://`,p(this,S),p(this,_)].join("")),this.rewriteRules=i}async getPrimaryPhp(){return await this.processManager.getPrimaryPhp()}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const r=new URL(e);return r.pathname.startsWith(p(this,_))&&(r.pathname=r.pathname.slice(p(this,_).length)),toRelativeUrl(r)}get absoluteUrl(){return p(this,b)}get documentRoot(){return p(this,m)}async request(e){const r=e.url.startsWith("http://")||e.url.startsWith("https://"),s=new URL(e.url.split("#")[0],r?void 0:DEFAULT_BASE_URL),i=applyRewriteRules(removePathPrefix(decodeURIComponent(s.pathname),p(this,_)),this.rewriteRules),n=joinPaths(p(this,m),i);return seemsLikeAPHPRequestHandlerPath(n)?d(this,z,ce).call(this,e,s):d(this,$,le).call(this,await this.processManager.getPrimaryPhp(),n)}}m=new WeakMap,R=new WeakMap,T=new WeakMap,v=new WeakMap,S=new WeakMap,_=new WeakMap,b=new WeakMap,F=new WeakMap,$=new WeakSet,le=function(e,r){if(!e.fileExists(r))return new PHPResponse(404,{"x-file-type":["static"]},new TextEncoder().encode("404 File not found"));const s=e.readFileAsBuffer(r);return new PHPResponse(200,{"content-length":[`${s.byteLength}`],"content-type":[inferMimeType(r)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)},z=new WeakSet,ce=async function(e,r){let s;try{s=await this.processManager.acquirePHPInstance()}catch(i){return i instanceof MaxPhpInstancesError?PHPResponse.forHttpCode(502):PHPResponse.forHttpCode(500)}try{return await d(this,W,pe).call(this,s.php,e,r)}finally{s.reap()}},W=new WeakSet,pe=async function(e,r,s){let i="GET";const n={host:p(this,S),...normalizeHeaders(r.headers||{}),cookie:p(this,F).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=d(this,G,ue).call(this,e,decodeURIComponent(s.pathname))}catch{return PHPResponse.forHttpCode(404)}try{const l=await e.run({relativeUri:ensurePathPrefix(toRelativeUrl(s),p(this,_)),protocol:p(this,R),method:r.method||i,$_SERVER:{REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:p(this,m),HTTPS:p(this,b).startsWith("https://")?"on":""},body:o,scriptPath:a,headers:n});return p(this,F).rememberCookiesFromResponseHeaders(l.headers),l}catch(l){const c=l;if(c!=null&&c.response)return c.response;throw l}},G=new WeakSet,ue=function(e,r){let s=removePathPrefix(r,p(this,_));s=applyRewriteRules(s,this.rewriteRules),s.includes(".php")?s=s.split(".php")[0]+".php":e.isDir(`${p(this,m)}${s}`)?(s.endsWith("/")||(s=`${s}/`),s=`${s}index.php`):s="/index.php";let i=`${p(this,m)}${s}`;if(e.fileExists(i)||(i=`${p(this,m)}/index.php`),e.fileExists(i))return i;throw new Error(`File not found: ${i}`)};function inferMimeType(t){const e=t.split(".").pop();return mimeTypes[e]||mimeTypes._default}function seemsLikeAPHPRequestHandlerPath(t){return seemsLikeAPHPFile(t)||seemsLikeADirectoryRoot(t)}function seemsLikeAPHPFile(t){return t.endsWith(".php")||t.includes(".php/")}function seemsLikeADirectoryRoot(t){return!t.split("/").pop().includes(".")}function applyRewriteRules(t,e){for(const r of e)if(new RegExp(r.match).test(t))return t.replace(r.match,r.replacement);return t}function rotatePHPRuntime({php:t,cwd:e,recreateRuntime:r,maxRequests:s=400}){let i=0;async function n(){if(++i<s)return;i=0;const o=await t.semaphore.acquire();try{t.hotSwapPHPRuntime(await r(),e)}finally{o()}}return t.addEventListener("request.end",n),function(){t.removeEventListener("request.end",n)}}async function writeFiles(t,e,r,{rmRoot:s=!1}={}){s&&await t.isDir(e)&&await t.rmdir(e,{recursive:!0});for(const[i,n]of Object.entries(r)){const o=joinPaths(e,i);await t.fileExists(dirname(o))||await t.mkdir(dirname(o)),n instanceof Uint8Array||typeof n=="string"?await t.writeFile(o,n):await writeFiles(t,o,n)}}function proxyFileSystem(t,e,r){const s=Object.getOwnPropertySymbols(t)[0];for(const i of r)e.fileExists(i)||e.mkdir(i),t.fileExists(i)||t.mkdir(i),e[s].FS.mount(e[s].PROXYFS,{root:i,fs:t[s].FS},i)}exports.DEFAULT_BASE_URL=DEFAULT_BASE_URL;exports.FSHelpers=FSHelpers;exports.HttpCookieStore=HttpCookieStore;exports.LatestSupportedPHPVersion=LatestSupportedPHPVersion;exports.PHP=PHP;exports.PHPProcessManager=PHPProcessManager;exports.PHPRequestHandler=PHPRequestHandler;exports.PHPResponse=PHPResponse;exports.PHPWorker=PHPWorker;exports.SupportedPHPExtensionBundles=SupportedPHPExtensionBundles;exports.SupportedPHPExtensionsList=SupportedPHPExtensionsList;exports.SupportedPHPVersions=SupportedPHPVersions;exports.SupportedPHPVersionsList=SupportedPHPVersionsList;exports.UnhandledRejectionsTarget=UnhandledRejectionsTarget;exports.__private__dont__use=__private__dont__use;exports.applyRewriteRules=applyRewriteRules;exports.ensurePathPrefix=ensurePathPrefix;exports.getPhpIniEntries=getPhpIniEntries;exports.isExitCodeZero=isExitCodeZero;exports.iterateFiles=iteratePhpFiles;exports.loadPHPRuntime=loadPHPRuntime;exports.proxyFileSystem=proxyFileSystem;exports.removePathPrefix=removePathPrefix;exports.rotatePHPRuntime=rotatePHPRuntime;exports.setPhpIniEntries=setPhpIniEntries;exports.toRelativeUrl=toRelativeUrl;exports.withPHPIniValues=withPHPIniValues;exports.writeFiles=writeFiles;exports.writeFilesStreamToPhp=writeFilesStreamToPhp;