@php-wasm/universal 3.1.3 → 3.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var ce=Object.create;var G=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var de=Object.getPrototypeOf,pe=Object.prototype.hasOwnProperty;var J=r=>{throw TypeError(r)};var he=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ue(e))!pe.call(r,n)&&n!==t&&G(r,n,{get:()=>e[n],enumerable:!(s=le(e,n))||s.enumerable});return r};var fe=(r,e,t)=>(t=r!=null?ce(de(r)):{},he(e||!r||!r.__esModule?G(t,"default",{value:r,enumerable:!0}):t,r));var W=(r,e,t)=>e.has(r)||J("Cannot "+t);var u=(r,e,t)=>(W(r,e,"read from private field"),t?t.call(r):e.get(r)),y=(r,e,t)=>e.has(r)?J("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),g=(r,e,t,s)=>(W(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),m=(r,e,t)=>(W(r,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("@php-wasm/node-polyfills");const logger=require("@php-wasm/logger"),util=require("@php-wasm/util"),ini=require("ini"),streamCompression=require("@php-wasm/stream-compression");class ErrnoError extends Error{constructor(e,t,s){super(t,s),this.name="ErrnoError",this.errno=e}}const FileErrorCodes={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function getEmscriptenFsError(r){const e=typeof r=="object"?r==null?void 0:r.errno:null;if(e in FileErrorCodes)return FileErrorCodes[e]}function rethrowFileSystemError(r=""){return function(t){return function(...s){try{return t.apply(this,s)}catch(n){const i=typeof n=="object"?n==null?void 0:n.errno:null;if(i in FileErrorCodes){const o=FileErrorCodes[i],a=typeof s[1]=="string"?s[1]:null,c=a!==null?r.replaceAll("{path}",a):r;throw new ErrnoError(i,`${c}: ${o}`,{cause:n})}throw n}}}}class FSHelpers{static readFileAsText(e,t){return new TextDecoder().decode(FSHelpers.readFileAsBuffer(e,t))}static readFileAsBuffer(e,t){return e.readFile(t)}static writeFile(e,t,s){e.writeFile(t,s)}static unlink(e,t){e.unlink(t)}static mv(e,t,s){try{const n=e.lookupPath(t).node.mount,i=FSHelpers.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(util.dirname(s)).node.mount;n.mountpoint!==i.mountpoint?(FSHelpers.copyRecursive(e,t,s),FSHelpers.isDir(e,t)?FSHelpers.rmdir(e,t,{recursive:!0}):e.unlink(t)):e.rename(t,s)}catch(n){const i=getEmscriptenFsError(n);throw i?new Error(`Could not move ${t} to ${s}: ${i}`,{cause:n}):n}}static rmdir(e,t,s={recursive:!0}){const n=e.lookupPath(t,{follow:!1});if((n==null?void 0:n.node.mount.mountpoint)===t)throw new ErrnoError(10);s!=null&&s.recursive&&FSHelpers.listFiles(e,t).forEach(i=>{const o=`${t}/${i}`;FSHelpers.isDir(e,o)?FSHelpers.rmdir(e,o,s):FSHelpers.unlink(e,o)}),e.getPath(e.lookupPath(t).node)===e.cwd()&&e.chdir(util.joinPaths(e.cwd(),"..")),e.rmdir(t)}static listFiles(e,t,s={prependPath:!1}){if(!FSHelpers.fileExists(e,t))return[];try{const n=e.readdir(t).filter(i=>i!=="."&&i!=="..");if(s.prependPath){const i=t.replace(/\/$/,"");return n.map(o=>`${i}/${o}`)}return n}catch(n){return logger.logger.error(n,{path:t}),[]}}static isDir(e,t){return FSHelpers.fileExists(e,t)?e.isDir(e.lookupPath(t,{follow:!0}).node.mode):!1}static isFile(e,t){return FSHelpers.fileExists(e,t)?e.isFile(e.lookupPath(t,{follow:!0}).node.mode):!1}static symlink(e,t,s){return e.symlink(t,s)}static isSymlink(e,t){return FSHelpers.fileExists(e,t)?e.isLink(e.lookupPath(t).node.mode):!1}static readlink(e,t){return e.readlink(t)}static realpath(e,t){return e.lookupPath(t,{follow:!0}).path}static fileExists(e,t){try{return e.lookupPath(t),!0}catch{return!1}}static mkdir(e,t){e.mkdirTree(t)}static copyRecursive(e,t,s){try{const n=e.lookupPath(t).node;if(e.isDir(n.mode)){if(t===s||s.startsWith(`${t}/`))throw new ErrnoError(28);e.mkdirTree(s);const i=e.readdir(t).filter(o=>o!=="."&&o!=="..");for(const o of i)FSHelpers.copyRecursive(e,util.joinPaths(t,o),util.joinPaths(s,o))}else e.isLink(n.mode)?e.symlink(e.readlink(t),s):e.writeFile(s,e.readFile(t))}catch(n){const i=getEmscriptenFsError(n);throw i?new Error(`Could not copy ${t} to ${s}: ${i}`,{cause:n}):n}}}FSHelpers.readFileAsText=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsText);FSHelpers.readFileAsBuffer=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsBuffer);FSHelpers.writeFile=rethrowFileSystemError('Could not write to "{path}"')(FSHelpers.writeFile);FSHelpers.unlink=rethrowFileSystemError('Could not unlink "{path}"')(FSHelpers.unlink);FSHelpers.rmdir=rethrowFileSystemError('Could not remove directory "{path}"')(FSHelpers.rmdir);FSHelpers.listFiles=rethrowFileSystemError('Could not list files in "{path}"')(FSHelpers.listFiles);FSHelpers.isDir=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isDir);FSHelpers.isFile=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isFile);FSHelpers.realpath=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.realpath);FSHelpers.fileExists=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.fileExists);FSHelpers.mkdir=rethrowFileSystemError('Could not create directory "{path}"')(FSHelpers.mkdir);const _private=new WeakMap;var v;class PHPWorker{constructor(e,t){y(this,v);this.absoluteUrl="",this.documentRoot="",this.chroot=null,g(this,v,new Map),this.onMessageListeners=[],_private.set(this,{monitor:t}),e&&this.__internal_setRequestHandler(e)}__internal_setRequestHandler(e){this.absoluteUrl=e.absoluteUrl,this.documentRoot=e.documentRoot,this.chroot=this.documentRoot,_private.set(this,{..._private.get(this),requestHandler:e})}__internal_getPHP(){return _private.get(this).php}__internal_getRequestHandler(){return _private.get(this).requestHandler}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 t;return(t=_private.get(this).monitor)==null?void 0:t.addEventListener("progress",e)}async mv(e,t){return _private.get(this).php.mv(e,t)}async rmdir(e,t){return _private.get(this).php.rmdir(e,t)}async request(e){return await _private.get(this).requestHandler.request(e)}async requestStreamed(e){return await _private.get(this).requestHandler.requestStreamed(e)}async run(e){const{php:t,reap:s}=await this.acquirePHPInstance();try{return await t.run(e)}finally{s()}}async cli(e,t){const{php:s,reap:n}=await this.acquirePHPInstance();let i;try{i=await s.cli(e,t)}catch(o){throw n(),o}return i.finished.finally(n),i}chdir(e){return this.chroot=e,_private.get(this).php.chdir(e)}cwd(){return _private.get(this).php.cwd()}async acquirePHPInstance(){const{php:e,reap:t}=await _private.get(this).requestHandler.instanceManager.acquirePHPInstance();return this.chroot!==null&&e.chdir(this.chroot),this.registerWorkerListeners(e),{php:e,reap:t}}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,t){return _private.get(this).php.writeFile(e,t)}unlink(e){return _private.get(this).php.unlink(e)}listFiles(e,t){return _private.get(this).php.listFiles(e,t)}isDir(e){return _private.get(this).php.isDir(e)}isFile(e){return _private.get(this).php.isFile(e)}fileExists(e){return _private.get(this).php.fileExists(e)}onMessage(e){return this.onMessageListeners.push(e),async()=>{this.onMessageListeners=this.onMessageListeners.filter(t=>t!==e)}}defineConstant(e,t){_private.get(this).php.defineConstant(e,t)}addEventListener(e,t){u(this,v).has(e)||u(this,v).set(e,new Set),u(this,v).get(e).add(t)}removeEventListener(e,t){var s;(s=u(this,v).get(e))==null||s.delete(t)}dispatchEvent(e){const t=u(this,v).get(e.type);if(t)for(const s of t)s(e)}registerWorkerListeners(e){e.addEventListener("*",async t=>{this.dispatchEvent(t)}),e.onMessage(async t=>{for(const s of this.onMessageListeners){const n=await s(t);if(n)return n}return""})}async[Symbol.asyncDispose](){var e;await((e=_private.get(this).requestHandler)==null?void 0:e[Symbol.asyncDispose]())}}v=new WeakMap;function isExitCode(r){return r instanceof Error?(r==null?void 0:r.name)==="ExitStatus"&&"status"in r:!1}const RuntimeId=Symbol("RuntimeId"),loadedRuntimes=new Map;let lastRuntimeId=0;async function loadPHPRuntime(r,...e){const t=Object.assign({},...e),[s,n,i]=makePromise(),o=r.init(currentJsRuntime,{onAbort(c){i(c),logger.logger.error(c)},ENV:{},locateFile:c=>c,...t,noInitialRun:!0,onRuntimeInitialized(){t.onRuntimeInitialized&&t.onRuntimeInitialized(o),n()}});await s;const a=++lastRuntimeId;return o.FS,o.id=a,o.originalExit=o._exit,o._exit=function(c){return o.outboundNetworkProxyServer&&(o.outboundNetworkProxyServer.close(),o.outboundNetworkProxyServer.closeAllConnections()),loadedRuntimes.delete(a),o.originalExit(c)},o[RuntimeId]=a,loadedRuntimes.set(a,o),a}function popLoadedRuntime(r,{dangerouslyKeepTheRuntimeInTheMap:e=!1}={}){var s;const t=loadedRuntimes.get(r);if(!t)throw new Error(`Runtime with id ${r} not found`);if(e){if(!((s=process==null?void 0:process.env)!=null&&s.TEST))throw new Error("Cannot pop runtime in non-test environment");return t}return loadedRuntimes.delete(r),t}const currentJsRuntime=function(){var r;return typeof process<"u"&&((r=process.release)==null?void 0:r.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}(),makePromise=()=>{const r=[],e=new Promise((t,s)=>{r.push(t,s)});return r.unshift(e),r},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"};var M;const D=class D{constructor(e,t,s,n){y(this,M);this.parsedHeaders=null,this.cachedStdoutBytes=null,this.cachedStderrText=null,g(this,M,e),this.stdout=t,this.stderr=s,this.exitCode=n}static fromPHPResponse(e){const t=new ReadableStream({start(c){c.enqueue(e.bytes),c.close()}}),s=[];for(const[c,l]of Object.entries(e.headers))for(const d of l)s.push(`${c}: ${d}`);const n=JSON.stringify({status:e.httpStatusCode,headers:s}),i=new ReadableStream({start(c){c.enqueue(new TextEncoder().encode(n)),c.close()}}),o=new ReadableStream({start(c){e.errors.length>0&&c.enqueue(new TextEncoder().encode(e.errors)),c.close()}}),a=new D(i,t,o,Promise.resolve(e.exitCode));return a.parsedHeaders=Promise.resolve({headers:e.headers,httpStatusCode:e.httpStatusCode}),a}static forHttpCode(e,t=""){return D.fromPHPResponse(PHPResponse.forHttpCode(e,t))}getHeadersStream(){return u(this,M)}async ok(){try{const e=await this.httpStatusCode;return e>=200&&e<400}catch{return!1}}get finished(){return Promise.allSettled([this.exitCode.finally(()=>{})]).then(()=>{})}get headers(){return this.getParsedHeaders().then(e=>e.headers)}get httpStatusCode(){return this.getParsedHeaders().then(e=>e.httpStatusCode).then(e=>e!==void 0?e:this.getParsedHeaders().then(t=>t.httpStatusCode,()=>200)).catch(()=>500)}get stdoutText(){return this.stdoutBytes.then(e=>new TextDecoder().decode(e))}get stdoutBytes(){return this.cachedStdoutBytes||(this.cachedStdoutBytes=streamToBytes(this.stdout)),this.cachedStdoutBytes}get stderrText(){return this.cachedStderrText||(this.cachedStderrText=streamToText(this.stderr)),this.cachedStderrText}async getParsedHeaders(){return this.parsedHeaders||(this.parsedHeaders=parseHeadersStream(u(this,M))),await this.parsedHeaders}};M=new WeakMap;let StreamedPHPResponse=D;async function parseHeadersStream(r){const e=await streamToText(r);let t;try{t=JSON.parse(e)}catch{return{headers:{},httpStatusCode:200}}const s={};for(const n of t.headers){if(!n.includes(": "))continue;const i=n.indexOf(": "),o=n.substring(0,i).toLowerCase(),a=n.substring(i+2);o in s||(s[o]=[]),s[o].push(a)}return{headers:s,httpStatusCode:t.status}}async function streamToText(r){const e=r.pipeThrough(new TextDecoderStream).getReader(),t=[];for(;;){const{done:s,value:n}=await e.read();if(s)return t.join("");n&&t.push(n)}}async function streamToBytes(r){const e=r.getReader(),t=[];for(;;){const{done:s,value:n}=await e.read();if(s){const i=t.reduce((c,l)=>c+l.byteLength,0),o=new Uint8Array(i);let a=0;for(const c of t)o.set(c,a),a+=c.byteLength;return o}n&&t.push(n)}}class PHPResponse{constructor(e,t,s,n="",i=0){this.httpStatusCode=e,this.headers=t,this.bytes=s,this.exitCode=i,this.errors=n}static forHttpCode(e,t=""){return new PHPResponse(e,{},new TextEncoder().encode(t||responseTexts[e]||""))}static fromRawData(e){return new PHPResponse(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}static async fromStreamedResponse(e){return await e.finished,new PHPResponse(await e.httpStatusCode,await e.headers,await e.stdoutBytes,await e.stderrText,await e.exitCode)}ok(){return this.httpStatusCode>=200&&this.httpStatusCode<400}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)}}var _a;const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends(_a=Event,_a){constructor(e,t={}){super(e),this[kError]=t.error===void 0?null:t.error,this[kMessage]=t.message===void 0?"":t.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;class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,t,s){++this.listenersCount,super.addEventListener(e,t,s)}removeEventListener(e,t,s){--this.listenersCount,super.removeEventListener(e,t,s)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(r){const e=new UnhandledRejectionsTarget;for(const t in r.wasmExports)if(typeof r.wasmExports[t]=="function"){const s=r.wasmExports[t];r.wasmExports[t]=function(...n){var i;try{return s(...n)}catch(o){if(!(o instanceof Error))throw o;r.lastAsyncifyStackSource&&(o.cause=r.lastAsyncifyStackSource);const a=clarifyErrorMessage(o,(i=r.lastAsyncifyStackSource)==null?void 0:i.stack);if(e.hasListeners()){o.message=a;const c=new ErrorEvent("error",{error:o});throw e.dispatchEvent(c),o}throw(!isExitCode(o)||o.status!==0)&&showCriticalErrorBox(a),o}}}return e}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(r,e){if(r.message==="unreachable"){let t=UNREACHABLE_ERROR;e||(t+=`
1
+ "use strict";var ce=Object.create;var G=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var de=Object.getPrototypeOf,pe=Object.prototype.hasOwnProperty;var J=r=>{throw TypeError(r)};var he=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ue(e))!pe.call(r,n)&&n!==t&&G(r,n,{get:()=>e[n],enumerable:!(s=le(e,n))||s.enumerable});return r};var fe=(r,e,t)=>(t=r!=null?ce(de(r)):{},he(e||!r||!r.__esModule?G(t,"default",{value:r,enumerable:!0}):t,r));var j=(r,e,t)=>e.has(r)||J("Cannot "+t);var u=(r,e,t)=>(j(r,e,"read from private field"),t?t.call(r):e.get(r)),y=(r,e,t)=>e.has(r)?J("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),g=(r,e,t,s)=>(j(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),m=(r,e,t)=>(j(r,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("@php-wasm/node-polyfills");const logger=require("@php-wasm/logger"),util=require("@php-wasm/util"),ini=require("ini"),streamCompression=require("@php-wasm/stream-compression");class ErrnoError extends Error{constructor(e,t,s){super(t,s),this.name="ErrnoError",this.errno=e}}const FileErrorCodes={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function getEmscriptenFsError(r){const e=typeof r=="object"?r==null?void 0:r.errno:null;if(e in FileErrorCodes)return FileErrorCodes[e]}function rethrowFileSystemError(r=""){return function(t){return function(...s){try{return t.apply(this,s)}catch(n){const i=typeof n=="object"?n==null?void 0:n.errno:null;if(i in FileErrorCodes){const o=FileErrorCodes[i],a=typeof s[1]=="string"?s[1]:null,c=a!==null?r.replaceAll("{path}",a):r;throw new ErrnoError(i,`${c}: ${o}`,{cause:n})}throw n}}}}class FSHelpers{static readFileAsText(e,t){return new TextDecoder().decode(FSHelpers.readFileAsBuffer(e,t))}static readFileAsBuffer(e,t){return e.readFile(t)}static writeFile(e,t,s){e.writeFile(t,s)}static unlink(e,t){e.unlink(t)}static mv(e,t,s){try{const n=e.lookupPath(t).node.mount,i=FSHelpers.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(util.dirname(s)).node.mount;n.mountpoint!==i.mountpoint?(FSHelpers.copyRecursive(e,t,s),FSHelpers.isDir(e,t)?FSHelpers.rmdir(e,t,{recursive:!0}):e.unlink(t)):e.rename(t,s)}catch(n){const i=getEmscriptenFsError(n);throw i?new Error(`Could not move ${t} to ${s}: ${i}`,{cause:n}):n}}static rmdir(e,t,s={recursive:!0}){const n=e.lookupPath(t,{follow:!1});if((n==null?void 0:n.node.mount.mountpoint)===t)throw new ErrnoError(10);s!=null&&s.recursive&&FSHelpers.listFiles(e,t).forEach(i=>{const o=`${t}/${i}`;FSHelpers.isDir(e,o)?FSHelpers.rmdir(e,o,s):FSHelpers.unlink(e,o)}),e.getPath(e.lookupPath(t).node)===e.cwd()&&e.chdir(util.joinPaths(e.cwd(),"..")),e.rmdir(t)}static listFiles(e,t,s={prependPath:!1}){if(!FSHelpers.fileExists(e,t))return[];try{const n=e.readdir(t).filter(i=>i!=="."&&i!=="..");if(s.prependPath){const i=t.replace(/\/$/,"");return n.map(o=>`${i}/${o}`)}return n}catch(n){return logger.logger.error(n,{path:t}),[]}}static isDir(e,t){return FSHelpers.fileExists(e,t)?e.isDir(e.lookupPath(t,{follow:!0}).node.mode):!1}static isFile(e,t){return FSHelpers.fileExists(e,t)?e.isFile(e.lookupPath(t,{follow:!0}).node.mode):!1}static symlink(e,t,s){return e.symlink(t,s)}static isSymlink(e,t){return FSHelpers.fileExists(e,t)?e.isLink(e.lookupPath(t).node.mode):!1}static readlink(e,t){return e.readlink(t)}static realpath(e,t){return e.lookupPath(t,{follow:!0}).path}static fileExists(e,t){try{return e.lookupPath(t),!0}catch{return!1}}static mkdir(e,t){e.mkdirTree(t)}static copyRecursive(e,t,s){try{const n=e.lookupPath(t).node;if(e.isDir(n.mode)){if(t===s||s.startsWith(`${t}/`))throw new ErrnoError(28);e.mkdirTree(s);const i=e.readdir(t).filter(o=>o!=="."&&o!=="..");for(const o of i)FSHelpers.copyRecursive(e,util.joinPaths(t,o),util.joinPaths(s,o))}else e.isLink(n.mode)?e.symlink(e.readlink(t),s):e.writeFile(s,e.readFile(t))}catch(n){const i=getEmscriptenFsError(n);throw i?new Error(`Could not copy ${t} to ${s}: ${i}`,{cause:n}):n}}}FSHelpers.readFileAsText=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsText);FSHelpers.readFileAsBuffer=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsBuffer);FSHelpers.writeFile=rethrowFileSystemError('Could not write to "{path}"')(FSHelpers.writeFile);FSHelpers.unlink=rethrowFileSystemError('Could not unlink "{path}"')(FSHelpers.unlink);FSHelpers.rmdir=rethrowFileSystemError('Could not remove directory "{path}"')(FSHelpers.rmdir);FSHelpers.listFiles=rethrowFileSystemError('Could not list files in "{path}"')(FSHelpers.listFiles);FSHelpers.isDir=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isDir);FSHelpers.isFile=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isFile);FSHelpers.realpath=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.realpath);FSHelpers.fileExists=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.fileExists);FSHelpers.mkdir=rethrowFileSystemError('Could not create directory "{path}"')(FSHelpers.mkdir);const _private=new WeakMap;var v;class PHPWorker{constructor(e,t){y(this,v);this.absoluteUrl="",this.documentRoot="",this.chroot=null,g(this,v,new Map),this.onMessageListeners=[],_private.set(this,{monitor:t}),e&&this.__internal_setRequestHandler(e)}__internal_setRequestHandler(e){this.absoluteUrl=e.absoluteUrl,this.documentRoot=e.documentRoot,this.chroot=this.documentRoot,_private.set(this,{..._private.get(this),requestHandler:e})}__internal_getPHP(){return _private.get(this).php}__internal_getRequestHandler(){return _private.get(this).requestHandler}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 t;return(t=_private.get(this).monitor)==null?void 0:t.addEventListener("progress",e)}async mv(e,t){return _private.get(this).php.mv(e,t)}async rmdir(e,t){return _private.get(this).php.rmdir(e,t)}async request(e){return await _private.get(this).requestHandler.request(e)}async requestStreamed(e){return await _private.get(this).requestHandler.requestStreamed(e)}async run(e){const{php:t,reap:s}=await this.acquirePHPInstance();try{return await t.run(e)}finally{s()}}async cli(e,t){const{php:s,reap:n}=await this.acquirePHPInstance();let i;try{i=await s.cli(e,t)}catch(o){throw n(),o}return i.finished.finally(n),i}chdir(e){return this.chroot=e,_private.get(this).php.chdir(e)}cwd(){return _private.get(this).php.cwd()}async acquirePHPInstance(){const{php:e,reap:t}=await _private.get(this).requestHandler.instanceManager.acquirePHPInstance();return this.chroot!==null&&e.chdir(this.chroot),this.registerWorkerListeners(e),{php:e,reap:t}}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,t){return _private.get(this).php.writeFile(e,t)}unlink(e){return _private.get(this).php.unlink(e)}listFiles(e,t){return _private.get(this).php.listFiles(e,t)}isDir(e){return _private.get(this).php.isDir(e)}isFile(e){return _private.get(this).php.isFile(e)}fileExists(e){return _private.get(this).php.fileExists(e)}onMessage(e){return this.onMessageListeners.push(e),async()=>{this.onMessageListeners=this.onMessageListeners.filter(t=>t!==e)}}defineConstant(e,t){_private.get(this).php.defineConstant(e,t)}addEventListener(e,t){u(this,v).has(e)||u(this,v).set(e,new Set),u(this,v).get(e).add(t)}removeEventListener(e,t){var s;(s=u(this,v).get(e))==null||s.delete(t)}dispatchEvent(e){const t=u(this,v).get(e.type);if(t)for(const s of t)s(e)}registerWorkerListeners(e){e.addEventListener("*",async t=>{this.dispatchEvent(t)}),e.onMessage(async t=>{for(const s of this.onMessageListeners){const n=await s(t);if(n)return n}return""})}async[Symbol.asyncDispose](){var e;await((e=_private.get(this).requestHandler)==null?void 0:e[Symbol.asyncDispose]())}}v=new WeakMap;function isExitCode(r){return r instanceof Error?(r==null?void 0:r.name)==="ExitStatus"&&"status"in r:!1}const RuntimeId=Symbol("RuntimeId"),loadedRuntimes=new Map;let lastRuntimeId=0;async function loadPHPRuntime(r,...e){const t=Object.assign({},...e),[s,n,i]=makePromise(),o=r.init(currentJsRuntime,{onAbort(c){i(c),logger.logger.error(c)},ENV:{},locateFile:c=>c,...t,noInitialRun:!0,onRuntimeInitialized(){t.onRuntimeInitialized&&t.onRuntimeInitialized(o),n()}});await s;const a=++lastRuntimeId;return o.FS,o.id=a,o.originalExit=o._exit,o._exit=function(c){return o.outboundNetworkProxyServer&&(o.outboundNetworkProxyServer.close(),o.outboundNetworkProxyServer.closeAllConnections()),loadedRuntimes.delete(a),o.originalExit(c)},o[RuntimeId]=a,loadedRuntimes.set(a,o),a}function popLoadedRuntime(r,{dangerouslyKeepTheRuntimeInTheMap:e=!1}={}){var s;const t=loadedRuntimes.get(r);if(!t)throw new Error(`Runtime with id ${r} not found`);if(e){if(!((s=process==null?void 0:process.env)!=null&&s.TEST))throw new Error("Cannot pop runtime in non-test environment");return t}return loadedRuntimes.delete(r),t}const currentJsRuntime=function(){var r;return typeof process<"u"&&((r=process.release)==null?void 0:r.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}(),makePromise=()=>{const r=[],e=new Promise((t,s)=>{r.push(t,s)});return r.unshift(e),r},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"};var M;const D=class D{constructor(e,t,s,n){y(this,M);this.parsedHeaders=null,this.cachedStdoutBytes=null,this.cachedStderrText=null,g(this,M,e),this.stdout=t,this.stderr=s,this.exitCode=n}static fromPHPResponse(e){const t=new ReadableStream({start(c){c.enqueue(e.bytes),c.close()}}),s=[];for(const[c,l]of Object.entries(e.headers))for(const d of l)s.push(`${c}: ${d}`);const n=JSON.stringify({status:e.httpStatusCode,headers:s}),i=new ReadableStream({start(c){c.enqueue(new TextEncoder().encode(n)),c.close()}}),o=new ReadableStream({start(c){e.errors.length>0&&c.enqueue(new TextEncoder().encode(e.errors)),c.close()}}),a=new D(i,t,o,Promise.resolve(e.exitCode));return a.parsedHeaders=Promise.resolve({headers:e.headers,httpStatusCode:e.httpStatusCode}),a}static forHttpCode(e,t=""){return D.fromPHPResponse(PHPResponse.forHttpCode(e,t))}getHeadersStream(){return u(this,M)}async ok(){try{const e=await this.httpStatusCode;return e>=200&&e<400}catch{return!1}}get finished(){return Promise.allSettled([this.exitCode.finally(()=>{})]).then(()=>{})}get headers(){return this.getParsedHeaders().then(e=>e.headers)}get httpStatusCode(){return this.getParsedHeaders().then(e=>e.httpStatusCode).then(e=>e!==void 0?e:this.getParsedHeaders().then(t=>t.httpStatusCode,()=>200)).catch(()=>500)}get stdoutText(){return this.stdoutBytes.then(e=>new TextDecoder().decode(e))}get stdoutBytes(){return this.cachedStdoutBytes||(this.cachedStdoutBytes=streamToBytes(this.stdout)),this.cachedStdoutBytes}get stderrText(){return this.cachedStderrText||(this.cachedStderrText=streamToText(this.stderr)),this.cachedStderrText}async getParsedHeaders(){return this.parsedHeaders||(this.parsedHeaders=parseHeadersStream(u(this,M))),await this.parsedHeaders}};M=new WeakMap;let StreamedPHPResponse=D;async function parseHeadersStream(r){const e=await streamToText(r);let t;try{t=JSON.parse(e)}catch{return{headers:{},httpStatusCode:200}}const s={};for(const n of t.headers){if(!n.includes(": "))continue;const i=n.indexOf(": "),o=n.substring(0,i).toLowerCase(),a=n.substring(i+2);o in s||(s[o]=[]),s[o].push(a)}return{headers:s,httpStatusCode:t.status}}async function streamToText(r){const e=r.pipeThrough(new TextDecoderStream).getReader(),t=[];for(;;){const{done:s,value:n}=await e.read();if(s)return t.join("");n&&t.push(n)}}async function streamToBytes(r){const e=r.getReader(),t=[];for(;;){const{done:s,value:n}=await e.read();if(s){const i=t.reduce((c,l)=>c+l.byteLength,0),o=new Uint8Array(i);let a=0;for(const c of t)o.set(c,a),a+=c.byteLength;return o}n&&t.push(n)}}class PHPResponse{constructor(e,t,s,n="",i=0){this.httpStatusCode=e,this.headers=t,this.bytes=s,this.exitCode=i,this.errors=n}static forHttpCode(e,t=""){return new PHPResponse(e,{},new TextEncoder().encode(t||responseTexts[e]||""))}static fromRawData(e){return new PHPResponse(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}static async fromStreamedResponse(e){return await e.finished,new PHPResponse(await e.httpStatusCode,await e.headers,await e.stdoutBytes,await e.stderrText,await e.exitCode)}ok(){return this.httpStatusCode>=200&&this.httpStatusCode<400}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)}}var _a;const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends(_a=Event,_a){constructor(e,t={}){super(e),this[kError]=t.error===void 0?null:t.error,this[kMessage]=t.message===void 0?"":t.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;class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,t,s){++this.listenersCount,super.addEventListener(e,t,s)}removeEventListener(e,t,s){--this.listenersCount,super.removeEventListener(e,t,s)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(r){const e=new UnhandledRejectionsTarget;for(const t in r.wasmExports)if(typeof r.wasmExports[t]=="function"){const s=r.wasmExports[t];r.wasmExports[t]=function(...n){var i;try{return s(...n)}catch(o){if(!(o instanceof Error))throw o;r.lastAsyncifyStackSource&&(o.cause=r.lastAsyncifyStackSource);const a=clarifyErrorMessage(o,(i=r.lastAsyncifyStackSource)==null?void 0:i.stack);if(e.hasListeners()){o.message=a;const c=new ErrorEvent("error",{error:o});throw e.dispatchEvent(c),o}throw(!isExitCode(o)||o.status!==0)&&showCriticalErrorBox(a),o}}}return e}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(r,e){if(r.message==="unreachable"){let t=UNREACHABLE_ERROR;e||(t+=`
2
2
 
3
3
  This stack trace is lacking. For a better one initialize
4
4
  the PHP runtime with debug: true, e.g. loadNodeRuntime('8.1', { emscriptenOptions: { debug: true } }).
@@ -33,7 +33,7 @@ CLI option:
33
33
  ${eol}
34
34
  ${bold} WASM ERROR${reset}${redBg}`);for(const e of r.split(`
35
35
  `))logger.logger.log(`${eol} ${e} `);logger.logger.log(`${reset}`)}}function extractPHPFunctionsFromStack(r){try{const e=r.split(`
36
- `).slice(1).map(t=>{const s=t.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:t.includes("wasm:/")}}).filter(({fn:t,isWasm:s})=>s&&!t.startsWith("dynCall_")&&!t.startsWith("invoke_")).map(({fn:t})=>t);return Array.from(new Set(e))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(e,t,s){super(e),this.response=t,this.source=s}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php",OPCACHE_FILE_FOLDER="/internal/shared/opcache";var C,R,b,S,H,T,w,h,Y,X,Q,K,Z,ee,te,re,j,se,q,$;class PHP{constructor(r){y(this,h);y(this,C);y(this,R,!1);y(this,b,null);y(this,S,new Map([["*",new Set]]));y(this,H,[]);y(this,T,{});y(this,w,{enabled:!1,recreateRuntime:()=>0,needsRotating:!1,maxRequests:400,requestsMade:0});this.semaphore=new util.Semaphore({concurrency:1}),r!==void 0&&this.initializeRuntime(r),this.addEventListener("request.error",e=>{e.source==="php-wasm"&&(u(this,w).needsRotating=!0)})}addEventListener(r,e){u(this,S).has(r)||u(this,S).set(r,new Set),u(this,S).get(r).add(e)}removeEventListener(r,e){var t;(t=u(this,S).get(r))==null||t.delete(e)}dispatchEvent(r){const e=[...u(this,S).get(r.type)||[],...u(this,S).get("*")||[]];if(e)for(const t of e)t(r)}onMessage(r){return u(this,H).push(r),async()=>{g(this,H,u(this,H).filter(e=>e!==r))}}async setSpawnHandler(handler){typeof handler=="string"&&(handler=util.createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}pathToInternalUrl(r){return this.requestHandler.pathToInternalUrl(r)}internalUrlToPath(r){return this.requestHandler.internalUrlToPath(r)}initializeRuntime(r){if(this[__private__dont__use])throw new Error("PHP runtime already initialized.");const e=popLoadedRuntime(r);if(!e)throw new Error("Invalid PHP runtime id.");if(this[__private__dont__use]=e,this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[PHP_INI_PATH]),!this.fileExists(PHP_INI_PATH)){const t=["opcache.enable = 1","opcache.enable_cli = 1","opcache.jit = 0","opcache.interned_strings_buffer = 8","opcache.max_accelerated_files = 1000","opcache.memory_consumption = 64","opcache.max_wasted_percentage = 5","opcache.file_cache = "+OPCACHE_FILE_FOLDER,"opcache.file_cache_only = 1","opcache.file_cache_consistency_checks = 1"];this.fileExists(OPCACHE_FILE_FOLDER)||this.mkdir(OPCACHE_FILE_FOLDER),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","allow_url_fopen = On","allow_url_include = Off","session.save_path = /home/web_user","implicit_flush = 1","output_buffering = 0","max_execution_time = 0","max_input_time = -1",...t].join(`
36
+ `).slice(1).map(t=>{const s=t.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:t.includes("wasm:/")}}).filter(({fn:t,isWasm:s})=>s&&!t.startsWith("dynCall_")&&!t.startsWith("invoke_")).map(({fn:t})=>t);return Array.from(new Set(e))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(e,t,s){super(e),this.response=t,this.source=s}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php",OPCACHE_FILE_FOLDER="/internal/shared/opcache";var C,R,b,S,H,T,w,h,Y,X,Q,K,Z,ee,te,re,W,se,q,$;class PHP{constructor(r){y(this,h);y(this,C);y(this,R,!1);y(this,b,null);y(this,S,new Map([["*",new Set]]));y(this,H,[]);y(this,T,{});y(this,w,{enabled:!1,recreateRuntime:()=>0,needsRotating:!1,maxRequests:400,requestsMade:0});this.semaphore=new util.Semaphore({concurrency:1}),r!==void 0&&this.initializeRuntime(r),this.addEventListener("request.error",e=>{e.source==="php-wasm"&&(u(this,w).needsRotating=!0)})}addEventListener(r,e){u(this,S).has(r)||u(this,S).set(r,new Set),u(this,S).get(r).add(e)}removeEventListener(r,e){var t;(t=u(this,S).get(r))==null||t.delete(e)}dispatchEvent(r){const e=[...u(this,S).get(r.type)||[],...u(this,S).get("*")||[]];if(e)for(const t of e)t(r)}onMessage(r){return u(this,H).push(r),async()=>{g(this,H,u(this,H).filter(e=>e!==r))}}async setSpawnHandler(handler){typeof handler=="string"&&(handler=util.createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}pathToInternalUrl(r){return this.requestHandler.pathToInternalUrl(r)}internalUrlToPath(r){return this.requestHandler.internalUrlToPath(r)}initializeRuntime(r){if(this[__private__dont__use])throw new Error("PHP runtime already initialized.");const e=popLoadedRuntime(r);if(!e)throw new Error("Invalid PHP runtime id.");if(this[__private__dont__use]=e,this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[PHP_INI_PATH]),!this.fileExists(PHP_INI_PATH)){const t=["opcache.enable = 1","opcache.enable_cli = 1","opcache.jit = 0","opcache.interned_strings_buffer = 8","opcache.max_accelerated_files = 1000","opcache.memory_consumption = 64","opcache.max_wasted_percentage = 5","opcache.file_cache = "+OPCACHE_FILE_FOLDER,"opcache.file_cache_only = 1","opcache.file_cache_consistency_checks = 1"];this.fileExists(OPCACHE_FILE_FOLDER)||this.mkdir(OPCACHE_FILE_FOLDER),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","allow_url_fopen = On","allow_url_include = Off","session.save_path = /home/web_user","implicit_flush = 1","output_buffering = 0","max_execution_time = 0","max_input_time = -1",...t].join(`
37
37
  `))}this.fileExists(AUTO_PREPEND_SCRIPT)||this.writeFile(AUTO_PREPEND_SCRIPT,`<?php
38
38
  // Define constants set via defineConstant() calls
39
39
  if(file_exists('/internal/shared/consts.json')) {
@@ -54,7 +54,7 @@ ${bold} WASM ERROR${reset}${redBg}`);for(const e of r.split(`
54
54
  ${t.text}
55
55
 
56
56
  === Stderr ===
57
- ${t.errors}`,t,"request");return t}async runStream(r){const e=await this.semaphore.acquire();let t;const s=m(this,h,$).call(this,async()=>{if(u(this,R)||(await this[__private__dont__use].ccall("php_wasm_init",null,[],[],{isAsync:!0}),g(this,R,!0)),r.scriptPath&&!this.fileExists(r.scriptPath))throw new Error(`The script path "${r.scriptPath}" does not exist.`);m(this,h,X).call(this,r.relativeUri||""),m(this,h,ee).call(this,r.method||"GET");const i=normalizeHeaders(r.headers||{}),o=i.host||"example.com:443",a=m(this,h,Z).call(this,o,r.protocol||"http");if(m(this,h,Q).call(this,o),m(this,h,K).call(this,a),m(this,h,te).call(this,i),r.body&&(t=m(this,h,re).call(this,r.body)),typeof r.code=="string")this.writeFile("/internal/eval.php",r.code),m(this,h,j).call(this,"/internal/eval.php");else if(typeof r.scriptPath=="string")m(this,h,j).call(this,r.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const c=m(this,h,Y).call(this,r.$_SERVER,i,a);for(const d in c)m(this,h,se).call(this,d,c[d]);const l=r.env||{};for(const d in l)m(this,h,q).call(this,d,l[d]);return await this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0})}),n=()=>{if(t)try{this[__private__dont__use].free(t)}catch(i){logger.logger.error(i)}e(),this.dispatchEvent({type:"request.end"})};return s.then(i=>(i.finished.finally(n),i),i=>{try{n()}catch{}finally{throw i}})}defineConstant(r,e){let t={};try{t=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...t,[r]:e}))}mkdir(r){const e=FSHelpers.mkdir(this[__private__dont__use].FS,r);return this.dispatchEvent({type:"filesystem.write"}),e}mkdirTree(r){return FSHelpers.mkdir(this[__private__dont__use].FS,r)}readFileAsText(r){return FSHelpers.readFileAsText(this[__private__dont__use].FS,r)}readFileAsBuffer(r){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,r)}writeFile(r,e){const t=FSHelpers.writeFile(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}unlink(r){const e=FSHelpers.unlink(this[__private__dont__use].FS,r);return this.dispatchEvent({type:"filesystem.write"}),e}mv(r,e){const t=FSHelpers.mv(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}cp(r,e){const t=FSHelpers.copyRecursive(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}rmdir(r,e={recursive:!0}){const t=FSHelpers.rmdir(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}listFiles(r,e={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,r,e)}isDir(r){return FSHelpers.isDir(this[__private__dont__use].FS,r)}isFile(r){return FSHelpers.isFile(this[__private__dont__use].FS,r)}symlink(r,e){return FSHelpers.symlink(this[__private__dont__use].FS,r,e)}isSymlink(r){return FSHelpers.isSymlink(this[__private__dont__use].FS,r)}readlink(r){return FSHelpers.readlink(this[__private__dont__use].FS,r)}realpath(r){return FSHelpers.realpath(this[__private__dont__use].FS,r)}fileExists(r){return FSHelpers.fileExists(this[__private__dont__use].FS,r)}enableRuntimeRotation(r){g(this,w,{...u(this,w),enabled:!0,recreateRuntime:r.recreateRuntime,maxRequests:r.maxRequests??400})}async rotateRuntime(){if(!u(this,w).enabled)throw new Error("Runtime rotation is not enabled. Call enableRuntimeRotation() first.");await this.hotSwapPHPRuntime(await u(this,w).recreateRuntime()),u(this,w).requestsMade=0,u(this,w).needsRotating=!1}async hotSwapPHPRuntime(r){const e=this[__private__dont__use].FS,t=this.listFiles("/").map(c=>`/${c}`),s=this[__private__dont__use].spawnProcess,n=e.cwd();e.chdir("/");const i=Object.entries(u(this,T)).map(([c,l])=>({mountHandler:l.mountHandler,vfsPath:c})),o=Object.values(u(this,T)).reverse();for(const c of o)await c.unmount();try{this.exit()}catch{}this.initializeRuntime(r),s&&(this[__private__dont__use].spawnProcess=s),u(this,C)&&this.setSapiName(u(this,C));const a=this[__private__dont__use].FS;for(const c of t)c&&c!=="/request"&&copyMEMFSNodes(e,a,c);for(const{mountHandler:c,vfsPath:l}of i)this.mkdir(l),await this.mount(l,c);try{a.chdir(n)}catch(c){throw new Error(`Failed to restore CWD to ${n} after PHP runtime rotation.`,{cause:c})}}async mount(r,e){const t=await e(this,this[__private__dont__use].FS,r),s={mountHandler:e,unmount:async()=>{await t(),delete u(this,T)[r]}};return u(this,T)[r]=s,()=>{s.unmount()}}async cli(r,e={}){if(util.basename(r[0]??"")!=="php")return this.subProcess(r,e);u(this,R)&&(u(this,w).needsRotating=!0);const t=await this.semaphore.acquire();return await m(this,h,$).call(this,()=>{const s=e.env||{};for(const[n,i]of Object.entries(s))m(this,h,q).call(this,n,i);r=[r[0],"-c",PHP_INI_PATH,...r.slice(1)];for(const n of r)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[n]);return this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}).then(s=>(s.exitCode.finally(t),s)).finally(()=>{u(this,w).needsRotating=!0})}async subProcess(r,e={}){const t=this[__private__dont__use].spawnProcess(r[0],r.slice(1),{env:e.env,cwd:e.cwd??this.cwd()}),s=await createInvertedReadableStream();t.on("error",i=>{s.controller.error(i)}),t.stderr.on("data",i=>{s.controller.enqueue(i)});const n=await createInvertedReadableStream();return t.stdout.on("data",i=>{n.controller.enqueue(i)}),t.on("exit",()=>{setTimeout(()=>{try{s.controller.close()}catch{}try{n.controller.close()}catch{}},0)}),new StreamedPHPResponse(new ReadableStream({start(i){i.close()}}),n.stream,s.stream,new Promise(i=>{t.on("exit",o=>{i(o)})}))}setSkipShebang(r){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[r?1:0])}exit(r=0){this.dispatchEvent({type:"runtime.beforeExit"});try{this[__private__dont__use]._exit(r)}catch{}g(this,R,!1),g(this,b,null),this[__private__dont__use]&&(delete this[__private__dont__use].onMessage,delete this[__private__dont__use])}[Symbol.dispose](){this.exit(0)}}C=new WeakMap,R=new WeakMap,b=new WeakMap,S=new WeakMap,H=new WeakMap,T=new WeakMap,w=new WeakMap,h=new WeakSet,Y=function(r,e,t){const s={...r||{}};s.HTTPS=s.HTTPS||t===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},X=function(r){this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[r]);let e="";r.includes("?")&&(e=r.substring(r.indexOf("?")+1)),this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])},Q=function(r){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[r])},K=function(r){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[r])},Z=function(r,e){let t;try{t=parseInt(new URL(r).port,10)}catch{}return(!t||isNaN(t)||t===80)&&(t=e==="https"?443:80),t},ee=function(r){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[r])},te=function(r){r.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[r.cookie]),r["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[r["content-type"]]),r["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(r["content-length"],10)])},re=function(r){let e,t;typeof r=="string"?(logger.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"),t=this[__private__dont__use].lengthBytesUTF8(r),e=t+1):(t=r.byteLength,e=r.byteLength);const s=this[__private__dont__use].malloc(e);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof r=="string"?this[__private__dont__use].stringToUTF8(r,s,e+1):this[__private__dont__use].HEAPU8.set(r,s),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[s]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[t]),s},j=function(r){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[r])},se=function(r,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[r,e])},q=function(r,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[r,e])},$=async function(r){u(this,w).enabled&&u(this,w).needsRotating&&await this.rotateRuntime(),++u(this,w).requestsMade,u(this,w).requestsMade>=u(this,w).maxRequests&&(u(this,w).needsRotating=!0);const e=this[__private__dont__use],t=await createInvertedReadableStream();e.onHeaders=p=>{a||s||t.controller.enqueue(p.slice())};let s=!1;const n=()=>{s||(s=!0,t.controller.close())},i=await createInvertedReadableStream();e.onStdout=p=>{n(),!a&&i.controller.enqueue(p.slice())};const o=await createInvertedReadableStream();e.onStderr=p=>{a||o.controller.enqueue(p.slice())};let a=!1,c;const d=(async()=>{var p;try{return await Promise.race([r(),new Promise((_,k)=>{var z;c=V=>{isExitCode(V.error)||k(V.error)},(z=u(this,b))==null||z.addEventListener("error",c,{once:!0})})])}catch(f){if(isExitCode(f))return f.status;i.controller.error(f),o.controller.error(f),t.controller.error(f),a=!0;for(const _ in this)typeof this[_]=="function"&&(this[_]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});throw this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify(),f}finally{a||(i.controller.close(),o.controller.close(),n(),a=!0),(p=u(this,b))==null||p.removeEventListener("error",c)}})().then(p=>(p!==0&&this.dispatchEvent({type:"request.error",error:new Error(`PHP.run() failed with exit code ${p}.`),source:"php-wasm"}),p),p=>{const f=p.source??"php-wasm";throw this.dispatchEvent({type:"request.error",error:p,source:f}),p});return new StreamedPHPResponse(t.stream,i.stream,o.stream,d)};function normalizeHeaders(r){const e={};for(const t in r)e[t.toLowerCase()]=r[t];return e}function copyMEMFSNodes(r,e,t){if(getNodeType(r,t)!=="memfs"||!["memfs","missing"].includes(getNodeType(e,t)))return;const s=r.lookupPath(t);if(!r.isDir(s.node.mode)){e.writeFile(t,r.readFile(t));return}e.mkdirTree(t);const n=r.readdir(t).filter(i=>i!=="."&&i!=="..");for(const i of n)copyMEMFSNodes(r,e,util.joinPaths(t,i))}async function createInvertedReadableStream(r={}){let e;const t=new Promise(i=>{e=i}),s=new ReadableStream({...r,start(i){if(e(i),r.start)return r.start(i)}}),n=await t;return{stream:s,controller:n}}const getNodeType=(r,e)=>{try{return"contents"in r.lookupPath(e,{follow:!0}).node?"memfs":"not-memfs"}catch{return"missing"}};async function getPhpIniEntries(r,e){const t=ini.parse(await r.readFileAsText(PHP_INI_PATH));if(e===void 0)return t;const s={};for(const n of e)s[n]=t[n];return s}async function setPhpIniEntries(r,e){const t=ini.parse(await r.readFileAsText(PHP_INI_PATH));for(const[s,n]of Object.entries(e))n==null?delete t[s]:t[s]=n;await r.writeFile(PHP_INI_PATH,ini.stringify(t))}async function withPHPIniValues(r,e,t){const s=await r.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(r,e),await t()}finally{await r.writeFile(PHP_INI_PATH,s)}}async function printDebugDetails(r,e){e&&printResponseDebugDetails(await PHPResponse.fromStreamedResponse(e)),await prettyPrintFullStackTrace(r)}async function prettyPrintFullStackTrace(r){let e=r,t=!0;for(;e;)t||process.stderr.write(`
57
+ ${t.errors}`,t,"request");return t}async runStream(r){const e=await this.semaphore.acquire();let t;const s=m(this,h,$).call(this,async()=>{if(u(this,R)||(await this[__private__dont__use].ccall("php_wasm_init",null,[],[],{isAsync:!0}),g(this,R,!0)),r.scriptPath&&!this.fileExists(r.scriptPath))throw new Error(`The script path "${r.scriptPath}" does not exist.`);m(this,h,X).call(this,r.relativeUri||""),m(this,h,ee).call(this,r.method||"GET");const i=normalizeHeaders(r.headers||{}),o=i.host||"example.com:443",a=m(this,h,Z).call(this,o,r.protocol||"http");if(m(this,h,Q).call(this,o),m(this,h,K).call(this,a),m(this,h,te).call(this,i),r.body&&(t=m(this,h,re).call(this,r.body)),typeof r.code=="string")this.writeFile("/internal/eval.php",r.code),m(this,h,W).call(this,"/internal/eval.php");else if(typeof r.scriptPath=="string")m(this,h,W).call(this,r.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const c=m(this,h,Y).call(this,r.$_SERVER,i,a);for(const d in c)m(this,h,se).call(this,d,c[d]);const l=r.env||{};for(const d in l)m(this,h,q).call(this,d,l[d]);return await this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0})}),n=()=>{if(t)try{this[__private__dont__use].free(t)}catch(i){logger.logger.error(i)}e(),this.dispatchEvent({type:"request.end"})};return s.then(i=>(i.finished.finally(n),i),i=>{try{n()}catch{}finally{throw i}})}defineConstant(r,e){let t={};try{t=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...t,[r]:e}))}mkdir(r){const e=FSHelpers.mkdir(this[__private__dont__use].FS,r);return this.dispatchEvent({type:"filesystem.write"}),e}mkdirTree(r){return FSHelpers.mkdir(this[__private__dont__use].FS,r)}readFileAsText(r){return FSHelpers.readFileAsText(this[__private__dont__use].FS,r)}readFileAsBuffer(r){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,r)}writeFile(r,e){const t=FSHelpers.writeFile(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}unlink(r){const e=FSHelpers.unlink(this[__private__dont__use].FS,r);return this.dispatchEvent({type:"filesystem.write"}),e}mv(r,e){const t=FSHelpers.mv(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}cp(r,e){const t=FSHelpers.copyRecursive(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}rmdir(r,e={recursive:!0}){const t=FSHelpers.rmdir(this[__private__dont__use].FS,r,e);return this.dispatchEvent({type:"filesystem.write"}),t}listFiles(r,e={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,r,e)}isDir(r){return FSHelpers.isDir(this[__private__dont__use].FS,r)}isFile(r){return FSHelpers.isFile(this[__private__dont__use].FS,r)}symlink(r,e){return FSHelpers.symlink(this[__private__dont__use].FS,r,e)}isSymlink(r){return FSHelpers.isSymlink(this[__private__dont__use].FS,r)}readlink(r){return FSHelpers.readlink(this[__private__dont__use].FS,r)}realpath(r){return FSHelpers.realpath(this[__private__dont__use].FS,r)}fileExists(r){return FSHelpers.fileExists(this[__private__dont__use].FS,r)}enableRuntimeRotation(r){g(this,w,{...u(this,w),enabled:!0,recreateRuntime:r.recreateRuntime,maxRequests:r.maxRequests??400})}async rotateRuntime(){if(!u(this,w).enabled)throw new Error("Runtime rotation is not enabled. Call enableRuntimeRotation() first.");await this.hotSwapPHPRuntime(await u(this,w).recreateRuntime()),u(this,w).requestsMade=0,u(this,w).needsRotating=!1}async hotSwapPHPRuntime(r){const e=this[__private__dont__use].FS,t=this.listFiles("/").map(c=>`/${c}`),s=this[__private__dont__use].spawnProcess,n=e.cwd();e.chdir("/");const i=Object.entries(u(this,T)).map(([c,l])=>({mountHandler:l.mountHandler,vfsPath:c})),o=Object.values(u(this,T)).reverse();for(const c of o)await c.unmount();try{this.exit()}catch{}this.initializeRuntime(r),s&&(this[__private__dont__use].spawnProcess=s),u(this,C)&&this.setSapiName(u(this,C));const a=this[__private__dont__use].FS;for(const c of t)c&&c!=="/request"&&copyMEMFSNodes(e,a,c);for(const{mountHandler:c,vfsPath:l}of i)this.mkdir(l),await this.mount(l,c);try{a.chdir(n)}catch(c){throw new Error(`Failed to restore CWD to ${n} after PHP runtime rotation.`,{cause:c})}}async mount(r,e){const t=await e(this,this[__private__dont__use].FS,r),s={mountHandler:e,unmount:async()=>{await t(),delete u(this,T)[r]}};return u(this,T)[r]=s,()=>{s.unmount()}}async cli(r,e={}){if(util.basename(r[0]??"")!=="php")return this.subProcess(r,e);u(this,R)&&(u(this,w).needsRotating=!0);const t=await this.semaphore.acquire();return await m(this,h,$).call(this,()=>{const s=e.env||{};for(const[n,i]of Object.entries(s))m(this,h,q).call(this,n,i);r=[r[0],"-c",PHP_INI_PATH,...r.slice(1)];for(const n of r)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[n]);return this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}).then(s=>(s.exitCode.finally(t),s)).finally(()=>{u(this,w).needsRotating=!0})}async subProcess(r,e={}){const t=this[__private__dont__use].spawnProcess(r[0],r.slice(1),{env:e.env,cwd:e.cwd??this.cwd()}),s=await createInvertedReadableStream();t.on("error",i=>{s.controller.error(i)}),t.stderr.on("data",i=>{s.controller.enqueue(i)});const n=await createInvertedReadableStream();return t.stdout.on("data",i=>{n.controller.enqueue(i)}),t.on("exit",()=>{setTimeout(()=>{try{s.controller.close()}catch{}try{n.controller.close()}catch{}},0)}),new StreamedPHPResponse(new ReadableStream({start(i){i.close()}}),n.stream,s.stream,new Promise(i=>{t.on("exit",o=>{i(o)})}))}setSkipShebang(r){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[r?1:0])}exit(r=0){this.dispatchEvent({type:"runtime.beforeExit"});try{this[__private__dont__use]._exit(r)}catch{}g(this,R,!1),g(this,b,null),this[__private__dont__use]&&(delete this[__private__dont__use].onMessage,delete this[__private__dont__use])}[Symbol.dispose](){this.exit(0)}}C=new WeakMap,R=new WeakMap,b=new WeakMap,S=new WeakMap,H=new WeakMap,T=new WeakMap,w=new WeakMap,h=new WeakSet,Y=function(r,e,t){const s={...r||{}};s.HTTPS=s.HTTPS||t===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},X=function(r){this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[r]);let e="";r.includes("?")&&(e=r.substring(r.indexOf("?")+1)),this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])},Q=function(r){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[r])},K=function(r){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[r])},Z=function(r,e){let t;try{t=parseInt(new URL(r).port,10)}catch{}return(!t||isNaN(t)||t===80)&&(t=e==="https"?443:80),t},ee=function(r){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[r])},te=function(r){r.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[r.cookie]),r["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[r["content-type"]]),r["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(r["content-length"],10)])},re=function(r){let e,t;typeof r=="string"?(logger.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"),t=this[__private__dont__use].lengthBytesUTF8(r),e=t+1):(t=r.byteLength,e=r.byteLength);const s=this[__private__dont__use].malloc(e);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof r=="string"?this[__private__dont__use].stringToUTF8(r,s,e+1):this[__private__dont__use].HEAPU8.set(r,s),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[s]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[t]),s},W=function(r){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[r])},se=function(r,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[r,e])},q=function(r,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[r,e])},$=async function(r){u(this,w).enabled&&u(this,w).needsRotating&&await this.rotateRuntime(),++u(this,w).requestsMade,u(this,w).requestsMade>=u(this,w).maxRequests&&(u(this,w).needsRotating=!0);const e=this[__private__dont__use],t=await createInvertedReadableStream();e.onHeaders=p=>{a||s||t.controller.enqueue(p.slice())};let s=!1;const n=()=>{s||(s=!0,t.controller.close())},i=await createInvertedReadableStream();e.onStdout=p=>{n(),!a&&i.controller.enqueue(p.slice())};const o=await createInvertedReadableStream();e.onStderr=p=>{a||o.controller.enqueue(p.slice())};let a=!1,c;const d=(async()=>{var p;try{return await Promise.race([r(),new Promise((_,k)=>{var z;c=V=>{isExitCode(V.error)||k(V.error)},(z=u(this,b))==null||z.addEventListener("error",c,{once:!0})})])}catch(f){if(isExitCode(f))return f.status;i.controller.error(f),o.controller.error(f),t.controller.error(f),a=!0;for(const _ in this)typeof this[_]=="function"&&(this[_]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});throw this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify(),f}finally{a||(i.controller.close(),o.controller.close(),n(),a=!0),(p=u(this,b))==null||p.removeEventListener("error",c)}})().then(p=>(p!==0&&this.dispatchEvent({type:"request.error",error:new Error(`PHP.run() failed with exit code ${p}.`),source:"php-wasm"}),p),p=>{const f=p.source??"php-wasm";throw this.dispatchEvent({type:"request.error",error:p,source:f}),p});return new StreamedPHPResponse(t.stream,i.stream,o.stream,d)};function normalizeHeaders(r){const e={};for(const t in r)e[t.toLowerCase()]=r[t];return e}function copyMEMFSNodes(r,e,t){if(getNodeType(r,t)!=="memfs"||!["memfs","missing"].includes(getNodeType(e,t)))return;const s=r.lookupPath(t);if(!r.isDir(s.node.mode)){e.writeFile(t,r.readFile(t));return}e.mkdirTree(t);const n=r.readdir(t).filter(i=>i!=="."&&i!=="..");for(const i of n)copyMEMFSNodes(r,e,util.joinPaths(t,i))}async function createInvertedReadableStream(r={}){let e;const t=new Promise(i=>{e=i}),s=new ReadableStream({...r,start(i){if(e(i),r.start)return r.start(i)}}),n=await t;return{stream:s,controller:n}}const getNodeType=(r,e)=>{try{return"contents"in r.lookupPath(e,{follow:!0}).node?"memfs":"not-memfs"}catch{return"missing"}};async function getPhpIniEntries(r,e){const t=ini.parse(await r.readFileAsText(PHP_INI_PATH));if(e===void 0)return t;const s={};for(const n of e)s[n]=t[n];return s}async function setPhpIniEntries(r,e){const t=ini.parse(await r.readFileAsText(PHP_INI_PATH));for(const[s,n]of Object.entries(e))n==null?delete t[s]:t[s]=n;await r.writeFile(PHP_INI_PATH,ini.stringify(t))}async function withPHPIniValues(r,e,t){const s=await r.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(r,e),await t()}finally{await r.writeFile(PHP_INI_PATH,s)}}async function printDebugDetails(r,e){e&&printResponseDebugDetails(await PHPResponse.fromStreamedResponse(e)),await prettyPrintFullStackTrace(r)}async function prettyPrintFullStackTrace(r){let e=r,t=!0;for(;e;)t||process.stderr.write(`
58
58
  Caused by:
59
59
 
60
60
  `),process.stderr.write(e.originalErrorClassName??e.name),process.stderr.write(": "+e.message+`
@@ -86,7 +86,7 @@ ${JSON.stringify(r.headers,null,2)}
86
86
  `)),n.push(`\r
87
87
  `),l instanceof File?n.push(await fileToUint8Array(l)):n.push(l),n.push(`\r
88
88
  `);n.push(`--${e}--\r
89
- `);const i=n.reduce((c,l)=>c+l.length,0),o=new Uint8Array(i);let a=0;for(const c of n)o.set(typeof c=="string"?s.encode(c):c,a),a+=c.length;return{bytes:o,contentType:t}}function fileToUint8Array(r){return r.arrayBuffer().then(e=>new Uint8Array(e))}const _default="application/octet-stream",asx="video/x-ms-asf",atom="application/atom+xml",avi="video/x-msvideo",avif="image/avif",bin="application/octet-stream",bmp="image/x-ms-bmp",cco="application/x-cocoa",css="text/css",data="application/octet-stream",deb="application/octet-stream",der="application/x-x509-ca-cert",dmg="application/octet-stream",doc="application/msword",docx="application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot="application/vnd.ms-fontobject",flv="video/x-flv",gif="image/gif",gz="application/gzip",hqx="application/mac-binhex40",htc="text/x-component",html="text/html",ico="image/x-icon",iso="application/octet-stream",jad="text/vnd.sun.j2me.app-descriptor",jar="application/java-archive",jardiff="application/x-java-archive-diff",jng="image/x-jng",jnlp="application/x-java-jnlp-file",jpg="image/jpeg",jpeg="image/jpeg",js="application/javascript",json="application/json",kml="application/vnd.google-earth.kml+xml",kmz="application/vnd.google-earth.kmz",m3u8="application/vnd.apple.mpegurl",m4a="audio/x-m4a",m4v="video/x-m4v",md="text/plain",mid="audio/midi",mml="text/mathml",mng="video/x-mng",mov="video/quicktime",mp3="audio/mpeg",mp4="video/mp4",mpeg="video/mpeg",msi="application/octet-stream",odg="application/vnd.oasis.opendocument.graphics",odp="application/vnd.oasis.opendocument.presentation",ods="application/vnd.oasis.opendocument.spreadsheet",odt="application/vnd.oasis.opendocument.text",ogg="audio/ogg",otf="font/otf",pdf="application/pdf",pl="application/x-perl",png="image/png",ppt="application/vnd.ms-powerpoint",pptx="application/vnd.openxmlformats-officedocument.presentationml.presentation",prc="application/x-pilot",ps="application/postscript",ra="audio/x-realaudio",rar="application/x-rar-compressed",rpm="application/x-redhat-package-manager",rss="application/rss+xml",rtf="application/rtf",run="application/x-makeself",sea="application/x-sea",sit="application/x-stuffit",svg="image/svg+xml",swf="application/x-shockwave-flash",tcl="application/x-tcl",tar="application/x-tar",tif="image/tiff",ts="video/mp2t",ttf="font/ttf",txt="text/plain",wasm="application/wasm",wbmp="image/vnd.wap.wbmp",webm="video/webm",webp="image/webp",wml="text/vnd.wap.wml",wmlc="application/vnd.wap.wmlc",wmv="video/x-ms-wmv",woff="font/woff",woff2="font/woff2",xhtml="application/xhtml+xml",xls="application/vnd.ms-excel",xlsx="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml="text/xml",xpi="application/x-xpinstall",xspf="application/xspf+xml",zip="application/zip",mimeTypes={_default,"3gpp":"video/3gpp","7z":"application/x-7z-compressed",asx,atom,avi,avif,bin,bmp,cco,css,data,deb,der,dmg,doc,docx,eot,flv,gif,gz,hqx,htc,html,ico,iso,jad,jar,jardiff,jng,jnlp,jpg,jpeg,js,json,kml,kmz,m3u8,m4a,m4v,md,mid,mml,mng,mov,mp3,mp4,mpeg,msi,odg,odp,ods,odt,ogg,otf,pdf,pl,png,ppt,pptx,prc,ps,ra,rar,rpm,rss,rtf,run,sea,sit,svg,swf,tcl,tar,tif,ts,ttf,txt,wasm,wbmp,webm,webp,wml,wmlc,wmv,woff,woff2,xhtml,xls,xlsx,xml,xpi,xspf,zip};var E,I,O,L,A,x,N,F,U,P,ne,B,ie,oe,ae;class PHPRequestHandler{constructor(e){y(this,P);y(this,E);y(this,I);y(this,O);y(this,L);y(this,A);y(this,x);y(this,N);y(this,F);y(this,U);const{documentRoot:t="/www/",absoluteUrl:s=typeof location=="object"?location.href:DEFAULT_BASE_URL,rewriteRules:n=[],pathAliases:i=[],getFileNotFoundAction:o=()=>({type:"404"})}=e,a=d=>{d.isDir(t)||d.mkdir(t),d.chdir(t),d.requestHandler=this};if(e.php)a(e.php),this.instanceManager=new SinglePHPInstanceManager({php:e.php});else if(e.phpFactory)this.instanceManager=new PHPProcessManager({phpFactory:async d=>{const p=await e.phpFactory({...d,requestHandler:this});return a(p),p},maxPhpInstances:e.maxPhpInstances});else throw new Error("Either php or phpFactory must be provided in the configuration.");g(this,F,e.cookieStore===void 0?new HttpCookieStore:e.cookieStore),g(this,E,t);const c=new URL(s);g(this,O,c.hostname),g(this,L,c.port?Number(c.port):c.protocol==="https:"?443:80),g(this,I,(c.protocol||"").replace(":",""));const l=u(this,L)!==443&&u(this,L)!==80;g(this,A,[u(this,O),l?`:${u(this,L)}`:""].join("")),g(this,x,c.pathname.replace(/\/+$/,"")),g(this,N,[`${u(this,I)}://`,u(this,A),u(this,x)].join("")),this.rewriteRules=n,g(this,U,i),this.getFileNotFoundAction=o}async getPrimaryPhp(){return await this.instanceManager.getPrimaryPhp()}pathToInternalUrl(e){return e.startsWith("/")||(e=`/${e}`),`${this.absoluteUrl}${e}`}internalUrlToPath(e){const t=new URL(e,"https://playground.internal");return t.pathname.startsWith(u(this,x))&&(t.pathname=t.pathname.slice(u(this,x).length)),toRelativeUrl(t)}get absoluteUrl(){return u(this,N)}get documentRoot(){return u(this,E)}async request(e){const t=await this.requestStreamed(e),s=await PHPResponse.fromStreamedResponse(t);return s.ok()&&s.exitCode!==0?new PHPResponse(500,s.headers,s.bytes,s.errors,s.exitCode):s}async requestStreamed(e){const t=looksLikeAbsoluteUrl(e.url),s=new URL(e.url.split("#")[0],t?void 0:DEFAULT_BASE_URL),n=m(this,P,ne).call(this,s),i=await this.getPrimaryPhp(),o=removePathPrefix(decodeURIComponent(n.pathname),u(this,x));let a=m(this,P,B).call(this,o);if(i.isDir(a)){if(!o.endsWith("/"))return StreamedPHPResponse.fromPHPResponse(new PHPResponse(301,{Location:[`${n.pathname}/`]},new Uint8Array(0)));for(const c of["index.php","index.html"]){const l=util.joinPaths(a,c);if(i.isFile(l)){a=l,n.pathname=util.joinPaths(n.pathname,c);break}}}if(!i.isFile(a)){let c=o;for(;c.startsWith("/")&&c!==util.dirname(c);){c=util.dirname(c);const l=m(this,P,B).call(this,c);if(i.isFile(l)&&l.endsWith(".php")){a=m(this,P,B).call(this,c);break}}}if(!i.isFile(a)){const c=this.getFileNotFoundAction(n.pathname);switch(c.type){case"response":return StreamedPHPResponse.fromPHPResponse(c.response);case"internal-redirect":a=util.joinPaths(u(this,E),c.uri);break;case"404":return StreamedPHPResponse.forHttpCode(404);default:throw new Error(`Unsupported file-not-found action type: '${c.type}'`)}}return i.isFile(a)?a.endsWith(".php")?await m(this,P,oe).call(this,e,s,n,a):StreamedPHPResponse.fromPHPResponse(m(this,P,ie).call(this,i,a)):StreamedPHPResponse.forHttpCode(404)}prepare_$_SERVER_superglobal(e,t,s){const n={REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:u(this,E),HTTPS:u(this,N).startsWith("https://")?"on":""};return n.REQUEST_URI=e.pathname+e.search,s.startsWith(u(this,E))&&(n.SCRIPT_NAME=s.substring(u(this,E).length),n.PHP_SELF=t.pathname,n.REQUEST_URI.startsWith(n.SCRIPT_NAME)&&(n.PATH_INFO=n.REQUEST_URI.substring(n.SCRIPT_NAME.length),n.PATH_INFO.includes("?")&&(n.PATH_INFO=n.PATH_INFO.substring(0,n.PATH_INFO.indexOf("?"))))),n.QUERY_STRING=t.search.substring(1),n}async[Symbol.asyncDispose](){await this.instanceManager[Symbol.asyncDispose]()}}E=new WeakMap,I=new WeakMap,O=new WeakMap,L=new WeakMap,A=new WeakMap,x=new WeakMap,N=new WeakMap,F=new WeakMap,U=new WeakMap,P=new WeakSet,ne=function(e){const t=removePathPrefix(decodeURIComponent(e.pathname),u(this,x)),s=applyRewriteRules(t,this.rewriteRules),n=new URL(util.joinPaths(u(this,x),s),e.toString());for(const[i,o]of e.searchParams.entries())n.searchParams.append(i,o);return n},B=function(e){for(const t of u(this,U))if(e===t.urlPrefix||e.startsWith(t.urlPrefix+"/")){const s=e.slice(t.urlPrefix.length);return util.joinPaths(t.fsPath,s)}return util.joinPaths(u(this,E),e)},ie=function(e,t){const s=e.readFileAsBuffer(t);return new PHPResponse(200,{"content-length":[`${s.byteLength}`],"content-type":[inferMimeType(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)},oe=async function(e,t,s,n){let i;try{i=await this.instanceManager.acquirePHPInstance()}catch(a){return a instanceof MaxPhpInstancesError?StreamedPHPResponse.forHttpCode(502):StreamedPHPResponse.forHttpCode(500)}let o;try{o=await m(this,P,ae).call(this,i.php,e,t,s,n)}catch(a){throw i.reap(),a}return o.finished.finally(()=>{i==null||i.reap()}),o},ae=async function(e,t,s,n,i){let o="GET";const a={host:u(this,A),...normalizeHeaders(t.headers||{})};u(this,F)&&(a.cookie=u(this,F).getCookieRequestHeader());let c=t.body;if(typeof c=="object"&&!(c instanceof Uint8Array)){o="POST";const{bytes:d,contentType:p}=await encodeAsMultipart(c);c=d,a["content-type"]=p}const l=await e.runStream({relativeUri:ensurePathPrefix(toRelativeUrl(new URL(n.toString())),u(this,x)),protocol:u(this,I),method:t.method||o,$_SERVER:this.prepare_$_SERVER_superglobal(s,n,i),body:c,scriptPath:i,headers:a});if(u(this,F)){const d=u(this,F);l.headers.then(p=>{d.rememberCookiesFromResponseHeaders(p)})}return l};function inferMimeType(r){const e=r.split(".").pop();return mimeTypes[e]||mimeTypes._default}function applyRewriteRules(r,e){for(const t of e)if(new RegExp(t.match).test(r)){r=r.replace(t.match,t.replacement);break}return r}function looksLikeAbsoluteUrl(r){try{return new URL(r),!0}catch{return!1}}function rotatePHPRuntime({php:r,recreateRuntime:e,maxRequests:t=400}){return r.enableRuntimeRotation({recreateRuntime:e,maxRequests:t})}async function writeFiles(r,e,t,{rmRoot:s=!1}={}){s&&await r.isDir(e)&&await r.rmdir(e,{recursive:!0});for(const[n,i]of Object.entries(t)){const o=util.joinPaths(e,n);await r.fileExists(util.dirname(o))||await r.mkdir(util.dirname(o)),i instanceof Uint8Array||typeof i=="string"?await r.writeFile(o,i):await writeFiles(r,o,i)}}function ensureProxyFSHasMmapSupport(r){const e=Object.getOwnPropertySymbols(r)[0],t=r[e],s=t.PROXYFS,n=t.FS;s.stream_ops.mmap||(s.stream_ops.mmap=function(i,o,a,c,l){if(!n.isFile(i.node.mode))throw new n.ErrnoError(19);if(a!==0)throw new n.ErrnoError(22);const d=t.malloc(o);if(!d)throw new n.ErrnoError(48);const p=t.HEAPU8.subarray(d,d+o);let f=0;for(;f<o;){const _=i.stream_ops.read(i,p,f,o-f,f);if(_<=0)break;f+=_}if(f!==o)throw t.free(d),new n.ErrnoError(5);return{ptr:d,allocated:!0}},s.stream_ops.msync=function(i,o,a,c,l){return l&2||i.stream_ops.write(i,o,a,c,a,!1),0})}function proxyFileSystem(r,e,t){ensureProxyFSHasMmapSupport(e);const s=Object.getOwnPropertySymbols(e)[0],n=Object.getOwnPropertySymbols(r)[0];for(const i of t)e.fileExists(i)||e.mkdir(i),r.fileExists(i)||r.mkdir(i),e[s].FS.mount(e[s].PROXYFS,{root:i,fs:r[n].FS},i)}function isPathToSharedFS(r,e){var i;const t=Object.getOwnPropertySymbols(r)[0],n=r[t].FS.lookupPath(e,{noent_okay:!0});return((i=n==null?void 0:n.node)==null?void 0:i.isSharedFS)??!1}function sandboxedSpawnHandlerFactory(r){return util.createSpawnHandler(async function(e,t,s){t.notifySpawn(),(e==null?void 0:e[0])==="/bin/sh"&&(e==null?void 0:e[1])==="-c"&&typeof e[2]=="string"&&(e=util.splitShellCommand(e[2])),e[0]==="exec"&&e.shift(),(e[0].endsWith(".php")||e[0].endsWith(".phar"))&&e.unshift("php");const n=e[0].split("/").pop();if(e[0]==="/usr/bin/env"&&e[1]==="stty"&&e[2]==="size")t.stdout("18 140"),t.exit(0);else if(n==="tput"&&e[1]==="cols")t.stdout("140"),t.exit(0);else if(n==="less"){t.on("stdin",a=>{t.stdout(a)}),await new Promise(a=>{t.childProcess.stdin.on("finish",()=>{a(!0)})}),t.exit(0);return}if(!["php","ls","pwd"].includes(n??"")){t.exit(127);return}if(!r){logger.logger.warn("Tried to spawn a PHP subprocess, but the sandboxed spawn handler was created without a getPHPInstance function."),t.exit(127);return}const{php:i,reap:o}=await r();try{s.cwd&&await i.chdir(s.cwd);const a=await i.cwd();switch(n){case"php":{const c=await i.cli(e,{env:{...s.env,SCRIPT_PATH:e[1],SHELL_PIPE:"0"}});c.stdout.pipeTo(new WritableStream({write(l){t.stdout(l)}})),c.stderr.pipeTo(new WritableStream({write(l){t.stderr(l)}})),t.exit(await c.exitCode);break}case"ls":{const c=await i.listFiles(e[1]??a);for(const l of c)t.stdout(l+`
89
+ `);const i=n.reduce((c,l)=>c+l.length,0),o=new Uint8Array(i);let a=0;for(const c of n)o.set(typeof c=="string"?s.encode(c):c,a),a+=c.length;return{bytes:o,contentType:t}}function fileToUint8Array(r){return r.arrayBuffer().then(e=>new Uint8Array(e))}const _default="application/octet-stream",asx="video/x-ms-asf",atom="application/atom+xml",avi="video/x-msvideo",avif="image/avif",bin="application/octet-stream",bmp="image/x-ms-bmp",cco="application/x-cocoa",cjs="application/javascript",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",mjs="application/javascript",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,cjs,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,mjs,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 E,I,O,L,A,x,N,F,U,P,ne,B,ie,oe,ae;class PHPRequestHandler{constructor(e){y(this,P);y(this,E);y(this,I);y(this,O);y(this,L);y(this,A);y(this,x);y(this,N);y(this,F);y(this,U);const{documentRoot:t="/www/",absoluteUrl:s=typeof location=="object"?location.href:DEFAULT_BASE_URL,rewriteRules:n=[],pathAliases:i=[],getFileNotFoundAction:o=()=>({type:"404"})}=e,a=d=>{d.isDir(t)||d.mkdir(t),d.chdir(t),d.requestHandler=this};if(e.php)a(e.php),this.instanceManager=new SinglePHPInstanceManager({php:e.php});else if(e.phpFactory)this.instanceManager=new PHPProcessManager({phpFactory:async d=>{const p=await e.phpFactory({...d,requestHandler:this});return a(p),p},maxPhpInstances:e.maxPhpInstances});else throw new Error("Either php or phpFactory must be provided in the configuration.");g(this,F,e.cookieStore===void 0?new HttpCookieStore:e.cookieStore),g(this,E,t);const c=new URL(s);g(this,O,c.hostname),g(this,L,c.port?Number(c.port):c.protocol==="https:"?443:80),g(this,I,(c.protocol||"").replace(":",""));const l=u(this,L)!==443&&u(this,L)!==80;g(this,A,[u(this,O),l?`:${u(this,L)}`:""].join("")),g(this,x,c.pathname.replace(/\/+$/,"")),g(this,N,[`${u(this,I)}://`,u(this,A),u(this,x)].join("")),this.rewriteRules=n,g(this,U,i),this.getFileNotFoundAction=o}async getPrimaryPhp(){return await this.instanceManager.getPrimaryPhp()}pathToInternalUrl(e){return e.startsWith("/")||(e=`/${e}`),`${this.absoluteUrl}${e}`}internalUrlToPath(e){const t=new URL(e,"https://playground.internal");return t.pathname.startsWith(u(this,x))&&(t.pathname=t.pathname.slice(u(this,x).length)),toRelativeUrl(t)}get absoluteUrl(){return u(this,N)}get documentRoot(){return u(this,E)}async request(e){const t=await this.requestStreamed(e),s=await PHPResponse.fromStreamedResponse(t);return s.ok()&&s.exitCode!==0?new PHPResponse(500,s.headers,s.bytes,s.errors,s.exitCode):s}async requestStreamed(e){const t=looksLikeAbsoluteUrl(e.url),s=new URL(e.url.split("#")[0],t?void 0:DEFAULT_BASE_URL),n=m(this,P,ne).call(this,s),i=await this.getPrimaryPhp(),o=removePathPrefix(decodeURIComponent(n.pathname),u(this,x));let a=m(this,P,B).call(this,o);if(i.isDir(a)){if(!o.endsWith("/"))return StreamedPHPResponse.fromPHPResponse(new PHPResponse(301,{Location:[`${n.pathname}/`]},new Uint8Array(0)));for(const c of["index.php","index.html"]){const l=util.joinPaths(a,c);if(i.isFile(l)){a=l,n.pathname=util.joinPaths(n.pathname,c);break}}}if(!i.isFile(a)){let c=o;for(;c.startsWith("/")&&c!==util.dirname(c);){c=util.dirname(c);const l=m(this,P,B).call(this,c);if(i.isFile(l)&&l.endsWith(".php")){a=m(this,P,B).call(this,c);break}}}if(!i.isFile(a)){const c=this.getFileNotFoundAction(n.pathname);switch(c.type){case"response":return StreamedPHPResponse.fromPHPResponse(c.response);case"internal-redirect":a=util.joinPaths(u(this,E),c.uri);break;case"404":return StreamedPHPResponse.forHttpCode(404);default:throw new Error(`Unsupported file-not-found action type: '${c.type}'`)}}return i.isFile(a)?a.endsWith(".php")?await m(this,P,oe).call(this,e,s,n,a):StreamedPHPResponse.fromPHPResponse(m(this,P,ie).call(this,i,a)):StreamedPHPResponse.forHttpCode(404)}prepare_$_SERVER_superglobal(e,t,s){const n={REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:u(this,E),HTTPS:u(this,N).startsWith("https://")?"on":""};return n.REQUEST_URI=e.pathname+e.search,s.startsWith(u(this,E))&&(n.SCRIPT_NAME=s.substring(u(this,E).length),n.PHP_SELF=t.pathname,n.REQUEST_URI.startsWith(n.SCRIPT_NAME)&&(n.PATH_INFO=n.REQUEST_URI.substring(n.SCRIPT_NAME.length),n.PATH_INFO.includes("?")&&(n.PATH_INFO=n.PATH_INFO.substring(0,n.PATH_INFO.indexOf("?"))))),n.QUERY_STRING=t.search.substring(1),n}async[Symbol.asyncDispose](){await this.instanceManager[Symbol.asyncDispose]()}}E=new WeakMap,I=new WeakMap,O=new WeakMap,L=new WeakMap,A=new WeakMap,x=new WeakMap,N=new WeakMap,F=new WeakMap,U=new WeakMap,P=new WeakSet,ne=function(e){const t=removePathPrefix(decodeURIComponent(e.pathname),u(this,x)),s=applyRewriteRules(t,this.rewriteRules),n=new URL(util.joinPaths(u(this,x),s),e.toString());for(const[i,o]of e.searchParams.entries())n.searchParams.append(i,o);return n},B=function(e){for(const t of u(this,U))if(e===t.urlPrefix||e.startsWith(t.urlPrefix+"/")){const s=e.slice(t.urlPrefix.length);return util.joinPaths(t.fsPath,s)}return util.joinPaths(u(this,E),e)},ie=function(e,t){const s=e.readFileAsBuffer(t);return new PHPResponse(200,{"content-length":[`${s.byteLength}`],"content-type":[inferMimeType(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)},oe=async function(e,t,s,n){let i;try{i=await this.instanceManager.acquirePHPInstance()}catch(a){return a instanceof MaxPhpInstancesError?StreamedPHPResponse.forHttpCode(502):StreamedPHPResponse.forHttpCode(500)}let o;try{o=await m(this,P,ae).call(this,i.php,e,t,s,n)}catch(a){throw i.reap(),a}return o.finished.finally(()=>{i==null||i.reap()}),o},ae=async function(e,t,s,n,i){let o="GET";const a={host:u(this,A),...normalizeHeaders(t.headers||{})};u(this,F)&&(a.cookie=u(this,F).getCookieRequestHeader());let c=t.body;if(typeof c=="object"&&!(c instanceof Uint8Array)){o="POST";const{bytes:d,contentType:p}=await encodeAsMultipart(c);c=d,a["content-type"]=p}const l=await e.runStream({relativeUri:ensurePathPrefix(toRelativeUrl(new URL(n.toString())),u(this,x)),protocol:u(this,I),method:t.method||o,$_SERVER:this.prepare_$_SERVER_superglobal(s,n,i),body:c,scriptPath:i,headers:a});if(u(this,F)){const d=u(this,F);l.headers.then(p=>{d.rememberCookiesFromResponseHeaders(p)})}return l};function inferMimeType(r){const e=r.split(".").pop();return mimeTypes[e]||mimeTypes._default}function applyRewriteRules(r,e){for(const t of e)if(new RegExp(t.match).test(r)){r=r.replace(t.match,t.replacement);break}return r}function looksLikeAbsoluteUrl(r){try{return new URL(r),!0}catch{return!1}}function rotatePHPRuntime({php:r,recreateRuntime:e,maxRequests:t=400}){return r.enableRuntimeRotation({recreateRuntime:e,maxRequests:t})}async function writeFiles(r,e,t,{rmRoot:s=!1}={}){s&&await r.isDir(e)&&await r.rmdir(e,{recursive:!0});for(const[n,i]of Object.entries(t)){const o=util.joinPaths(e,n);await r.fileExists(util.dirname(o))||await r.mkdir(util.dirname(o)),i instanceof Uint8Array||typeof i=="string"?await r.writeFile(o,i):await writeFiles(r,o,i)}}function ensureProxyFSHasMmapSupport(r){const e=Object.getOwnPropertySymbols(r)[0],t=r[e],s=t.PROXYFS,n=t.FS;s.stream_ops.mmap||(s.stream_ops.mmap=function(i,o,a,c,l){if(!n.isFile(i.node.mode))throw new n.ErrnoError(19);if(a!==0)throw new n.ErrnoError(22);const d=t.malloc(o);if(!d)throw new n.ErrnoError(48);const p=t.HEAPU8.subarray(d,d+o);let f=0;for(;f<o;){const _=i.stream_ops.read(i,p,f,o-f,f);if(_<=0)break;f+=_}if(f!==o)throw t.free(d),new n.ErrnoError(5);return{ptr:d,allocated:!0}},s.stream_ops.msync=function(i,o,a,c,l){return l&2||i.stream_ops.write(i,o,a,c,a,!1),0})}function proxyFileSystem(r,e,t){ensureProxyFSHasMmapSupport(e);const s=Object.getOwnPropertySymbols(e)[0],n=Object.getOwnPropertySymbols(r)[0];for(const i of t)e.fileExists(i)||e.mkdir(i),r.fileExists(i)||r.mkdir(i),e[s].FS.mount(e[s].PROXYFS,{root:i,fs:r[n].FS},i)}function isPathToSharedFS(r,e){var i;const t=Object.getOwnPropertySymbols(r)[0],n=r[t].FS.lookupPath(e,{noent_okay:!0});return((i=n==null?void 0:n.node)==null?void 0:i.isSharedFS)??!1}function sandboxedSpawnHandlerFactory(r){return util.createSpawnHandler(async function(e,t,s){t.notifySpawn(),(e==null?void 0:e[0])==="/bin/sh"&&(e==null?void 0:e[1])==="-c"&&typeof e[2]=="string"&&(e=util.splitShellCommand(e[2])),e[0]==="exec"&&e.shift(),(e[0].endsWith(".php")||e[0].endsWith(".phar"))&&e.unshift("php");const n=e[0].split("/").pop();if(e[0]==="/usr/bin/env"&&e[1]==="stty"&&e[2]==="size")t.stdout("18 140"),t.exit(0);else if(n==="tput"&&e[1]==="cols")t.stdout("140"),t.exit(0);else if(n==="less"){t.on("stdin",a=>{t.stdout(a)}),await new Promise(a=>{t.childProcess.stdin.on("finish",()=>{a(!0)})}),t.exit(0);return}if(!["php","ls","pwd"].includes(n??"")){t.exit(127);return}if(!r){logger.logger.warn("Tried to spawn a PHP subprocess, but the sandboxed spawn handler was created without a getPHPInstance function."),t.exit(127);return}const{php:i,reap:o}=await r();try{s.cwd&&await i.chdir(s.cwd);const a=await i.cwd();switch(n){case"php":{const c=await i.cli(e,{env:{...s.env,SCRIPT_PATH:e[1],SHELL_PIPE:"0"}});c.stdout.pipeTo(new WritableStream({write(l){t.stdout(l)}})),c.stderr.pipeTo(new WritableStream({write(l){t.stderr(l)}})),t.exit(await c.exitCode);break}case"ls":{const c=await i.listFiles(e[1]??a);for(const l of c)t.stdout(l+`
90
90
  `);await new Promise(l=>setTimeout(l,10)),t.exit(0);break}case"pwd":{t.stdout(a+`
91
91
  `),await new Promise(c=>setTimeout(c,10)),t.exit(0);break}}}catch(a){throw t.exit(1),a}finally{o()}})}function exposeSync(r,e,t,s=["*"]){return expose(r,e,s,t.afterResponseSent)}function createSyncProxy(r,e=[],t){return new Proxy(()=>{},{get(s,n){return n==="then"&&!e.length?{then:(i,o)=>o(createSyncProxy(r,[],t))}:createSyncProxy(r,[...e,n],t)},set(s,n,i){const[o,a]=toWireValue(i);return t.send(r,{type:MessageType.SET,path:[...e,n].map(String),value:o},a),!0},apply(s,n,i){if(e.at(-1)==="bind")return createSyncProxy(r,e.slice(0,-1),t);const[a,c]=processArguments(i),l=t.send(r,{type:MessageType.APPLY,path:e.map(String),argumentList:a},c);return fromWireValue(l)},construct(s,n){const[i,o]=processArguments(n),a=t.send(r,{type:MessageType.CONSTRUCT,path:e.map(String),argumentList:i},o);return fromWireValue(a)}})}function wrapSync(r,e){return createSyncProxy(r,[],e)}class NodeSABSyncReceiveMessageTransport{static async create(){if(!NodeSABSyncReceiveMessageTransport.receiveMessageOnPort)try{NodeSABSyncReceiveMessageTransport.receiveMessageOnPort=require("worker_threads").receiveMessageOnPort}catch{NodeSABSyncReceiveMessageTransport.receiveMessageOnPort=await import("worker_threads").then(e=>e.receiveMessageOnPort)}return new NodeSABSyncReceiveMessageTransport}constructor(){}afterResponseSent(e){const{notifyBuffer:t}=e.data;if(t){const s=new Int32Array(t);s[0]=1,Atomics.notify(s,0)}}send(e,t,s){var l;const n=new SharedArrayBuffer(4),i=new Int32Array(n);i[0]=0;const o=generateUUID();if(e.postMessage({...t,id:o,notifyBuffer:n},s),Atomics.wait(i,0,0,5e3)==="timed-out")throw new Error("Timeout waiting for response");for(;;){const d=NodeSABSyncReceiveMessageTransport.receiveMessageOnPort(e);if(((l=d.message)==null?void 0:l.id)===o)return d.message;if(!d)throw new Error("No response received")}}}/**
92
92
  * Original, unmodified Comlink library from Google: