@php-wasm/universal 3.1.1 → 3.1.2

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 oe=Object.create;var z=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var ce=Object.getOwnPropertyNames;var le=Object.getPrototypeOf,ue=Object.prototype.hasOwnProperty;var V=r=>{throw TypeError(r)};var pe=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ce(e))!ue.call(r,n)&&n!==t&&z(r,n,{get:()=>e[n],enumerable:!(s=ae(e,n))||s.enumerable});return r};var de=(r,e,t)=>(t=r!=null?oe(le(r)):{},pe(e||!r||!r.__esModule?z(t,"default",{value:r,enumerable:!0}):t,r));var B=(r,e,t)=>e.has(r)||V("Cannot "+t);var u=(r,e,t)=>(B(r,e,"read from private field"),t?t.call(r):e.get(r)),y=(r,e,t)=>e.has(r)?V("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),g=(r,e,t,s)=>(B(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),m=(r,e,t)=>(B(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){const n=e.lookupPath(t).node;if(e.isDir(n.mode)){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))}}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);FSHelpers.copyRecursive=rethrowFileSystemError('Could not copy files from "{path}"')(FSHelpers.copyRecursive);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 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"};class StreamedPHPResponse{constructor(e,t,s,n){this.parsedHeaders=null,this.cachedStdoutBytes=null,this.cachedStderrText=null,this.headersStream=e,this.stdout=t,this.stderr=s,this.exitCode=n}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(this.headersStream)),await this.parsedHeaders}}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 pe=Object.getPrototypeOf,de=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))!de.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(pe(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){const n=e.lookupPath(t).node;if(e.isDir(n.mode)){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))}}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);FSHelpers.copyRecursive=rethrowFileSystemError('Could not copy files from "{path}"')(FSHelpers.copyRecursive);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(i){i.enqueue(e.bytes),i.close()}}),s=()=>new ReadableStream({start(i){i.close()}}),n=new D(s(),t,s(),Promise.resolve(e.exitCode));return n.parsedHeaders=Promise.resolve({headers:e.headers,httpStatusCode:e.httpStatusCode}),n}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 M,R,b,S,T,H,w,h,G,J,Y,X,Q,K,Z,ee,D,te,W,j;class PHP{constructor(r){y(this,h);y(this,M);y(this,R,!1);y(this,b,null);y(this,S,new Map([["*",new Set]]));y(this,T,[]);y(this,H,{});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,T).push(r),async()=>{g(this,T,u(this,T).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,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(`
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')) {
@@ -48,13 +48,13 @@ ${bold} WASM ERROR${reset}${redBg}`);for(const e of r.split(`
48
48
  foreach (glob('/internal/shared/preload/*.php') as $file) {
49
49
  require_once $file;
50
50
  }
51
- `),e.onMessage=async t=>{for(const s of u(this,T)){const n=await s(t);if(n)return n}return""},g(this,b,improveWASMErrorReporting(e)),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(r){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[r])!==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?");g(this,M,r)}chdir(r){this[__private__dont__use].FS.chdir(r)}cwd(){return this[__private__dont__use].FS.cwd()}chmod(r,e){this[__private__dont__use].FS.chmod(r,e)}async request(r){if(logger.logger.debug("PHP.request() is deprecated. Please use new PHPRequestHandler() instead."),!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(r)}async run(r){const e=await this.runStream(r),t=await PHPResponse.fromStreamedResponse(e);if(t.exitCode!==0)throw new PHPExecutionFailureError(`PHP.run() failed with exit code ${t.exitCode}.
51
+ `),e.onMessage=async t=>{for(const s of u(this,H)){const n=await s(t);if(n)return n}return""},g(this,b,improveWASMErrorReporting(e)),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(r){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[r])!==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?");g(this,C,r)}chdir(r){this[__private__dont__use].FS.chdir(r)}cwd(){return this[__private__dont__use].FS.cwd()}chmod(r,e){this[__private__dont__use].FS.chmod(r,e)}async request(r){if(logger.logger.debug("PHP.request() is deprecated. Please use new PHPRequestHandler() instead."),!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(r)}async run(r){const e=await this.runStream(r),t=await PHPResponse.fromStreamedResponse(e);if(t.exitCode!==0)throw new PHPExecutionFailureError(`PHP.run() failed with exit code ${t.exitCode}.
52
52
 
53
53
  === Stdout ===
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,j).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,J).call(this,r.relativeUri||""),m(this,h,K).call(this,r.method||"GET");const i=normalizeHeaders(r.headers||{}),o=i.host||"example.com:443",a=m(this,h,Q).call(this,o,r.protocol||"http");if(m(this,h,Y).call(this,o),m(this,h,X).call(this,a),m(this,h,Z).call(this,i),r.body&&(t=m(this,h,ee).call(this,r.body)),typeof r.code=="string")this.writeFile("/internal/eval.php",r.code),m(this,h,D).call(this,"/internal/eval.php");else if(typeof r.scriptPath=="string")m(this,h,D).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,G).call(this,r.$_SERVER,i,a);for(const p in c)m(this,h,te).call(this,p,c[p]);const l=r.env||{};for(const p in l)m(this,h,W).call(this,p,l[p]);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}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,H)).map(([c,l])=>({mountHandler:l.mountHandler,vfsPath:c})),o=Object.values(u(this,H)).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,M)&&this.setSapiName(u(this,M));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,H)[r]}};return u(this,H)[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,j).call(this,()=>{const s=e.env||{};for(const[n,i]of Object.entries(s))m(this,h,W).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)}}M=new WeakMap,R=new WeakMap,b=new WeakMap,S=new WeakMap,T=new WeakMap,H=new WeakMap,w=new WeakMap,h=new WeakSet,G=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},J=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])},Y=function(r){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[r])},X=function(r){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[r])},Q=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},K=function(r){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[r])},Z=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)])},ee=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},D=function(r){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[r])},te=function(r,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[r,e])},W=function(r,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[r,e])},j=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=d=>{a||s||t.controller.enqueue(d.slice())};let s=!1;const n=()=>{s||(s=!0,t.controller.close())},i=await createInvertedReadableStream();e.onStdout=d=>{n(),!a&&i.controller.enqueue(d.slice())};const o=await createInvertedReadableStream();e.onStderr=d=>{a||o.controller.enqueue(d.slice())};let a=!1,c;const p=(async()=>{var d;try{return await Promise.race([r(),new Promise((_,k)=>{var q;c=$=>{isExitCode($.error)||k($.error)},(q=u(this,b))==null||q.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),(d=u(this,b))==null||d.removeEventListener("error",c)}})().then(d=>(d!==0&&this.dispatchEvent({type:"request.error",error:new Error(`PHP.run() failed with exit code ${d}.`),source:"php-wasm"}),d),d=>{const f=d.source??"php-wasm";throw this.dispatchEvent({type:"request.error",error:d,source:f}),d});return new StreamedPHPResponse(t.stream,i.stream,o.stream,p)};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,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 p in c)m(this,h,se).call(this,p,c[p]);const l=r.env||{};for(const p in l)m(this,h,q).call(this,p,l[p]);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}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=d=>{a||s||t.controller.enqueue(d.slice())};let s=!1;const n=()=>{s||(s=!0,t.controller.close())},i=await createInvertedReadableStream();e.onStdout=d=>{n(),!a&&i.controller.enqueue(d.slice())};const o=await createInvertedReadableStream();e.onStderr=d=>{a||o.controller.enqueue(d.slice())};let a=!1,c;const p=(async()=>{var d;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),(d=u(this,b))==null||d.removeEventListener("error",c)}})().then(d=>(d!==0&&this.dispatchEvent({type:"request.error",error:new Error(`PHP.run() failed with exit code ${d}.`),source:"php-wasm"}),d),d=>{const f=d.source??"php-wasm";throw this.dispatchEvent({type:"request.error",error:d,source:f}),d});return new StreamedPHPResponse(t.stream,i.stream,o.stream,p)};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,C,N,L,I,x,A,F,O,P,re,U,se,ne,ie;class PHPRequestHandler{constructor(e){y(this,P);y(this,E);y(this,C);y(this,N);y(this,L);y(this,I);y(this,x);y(this,A);y(this,F);y(this,O);const{documentRoot:t="/www/",absoluteUrl:s=typeof location=="object"?location.href:DEFAULT_BASE_URL,rewriteRules:n=[],pathAliases:i=[],getFileNotFoundAction:o=()=>({type:"404"})}=e,a=p=>{p.isDir(t)||p.mkdir(t),p.chdir(t),p.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 p=>{const d=await e.phpFactory({...p,requestHandler:this});return a(d),d},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,N,c.hostname),g(this,L,c.port?Number(c.port):c.protocol==="https:"?443:80),g(this,C,(c.protocol||"").replace(":",""));const l=u(this,L)!==443&&u(this,L)!==80;g(this,I,[u(this,N),l?`:${u(this,L)}`:""].join("")),g(this,x,c.pathname.replace(/\/+$/,"")),g(this,A,[`${u(this,C)}://`,u(this,I),u(this,x)].join("")),this.rewriteRules=n,g(this,O,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,A)}get documentRoot(){return u(this,E)}async request(e){const t=looksLikeAbsoluteUrl(e.url),s=new URL(e.url.split("#")[0],t?void 0:DEFAULT_BASE_URL),n=m(this,P,re).call(this,s),i=await this.getPrimaryPhp(),o=removePathPrefix(decodeURIComponent(n.pathname),u(this,x));let a=m(this,P,U).call(this,o);if(i.isDir(a)){if(!o.endsWith("/"))return 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,U).call(this,c);if(i.isFile(l)&&l.endsWith(".php")){a=m(this,P,U).call(this,c);break}}}if(!i.isFile(a)){const c=this.getFileNotFoundAction(n.pathname);switch(c.type){case"response":return c.response;case"internal-redirect":a=util.joinPaths(u(this,E),c.uri);break;case"404":return PHPResponse.forHttpCode(404);default:throw new Error(`Unsupported file-not-found action type: '${c.type}'`)}}if(i.isFile(a))if(a.endsWith(".php")){const c=await m(this,P,ne).call(this,e,s,n,a);return c.ok()&&c.exitCode!==0?new PHPResponse(500,c.headers,c.bytes,c.errors,c.exitCode):c}else return m(this,P,se).call(this,i,a);else return PHPResponse.forHttpCode(404)}prepare_$_SERVER_superglobal(e,t,s){const n={REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:u(this,E),HTTPS:u(this,A).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,C=new WeakMap,N=new WeakMap,L=new WeakMap,I=new WeakMap,x=new WeakMap,A=new WeakMap,F=new WeakMap,O=new WeakMap,P=new WeakSet,re=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},U=function(e){for(const t of u(this,O))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)},se=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)},ne=async function(e,t,s,n){let i;try{i=await this.instanceManager.acquirePHPInstance()}catch(o){return o instanceof MaxPhpInstancesError?PHPResponse.forHttpCode(502):PHPResponse.forHttpCode(500)}try{return await m(this,P,ie).call(this,i.php,e,t,s,n)}finally{i.reap()}},ie=async function(e,t,s,n,i){let o="GET";const a={host:u(this,I),...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:l,contentType:p}=await encodeAsMultipart(c);c=l,a["content-type"]=p}try{const l=await e.run({relativeUri:ensurePathPrefix(toRelativeUrl(new URL(n.toString())),u(this,x)),protocol:u(this,C),method:t.method||o,$_SERVER:this.prepare_$_SERVER_superglobal(s,n,i),body:c,scriptPath:i,headers:a});return u(this,F)&&u(this,F).rememberCookiesFromResponseHeaders(l.headers),l}catch(l){const p=l;if(p!=null&&p.response)return p.response;throw 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 p=t.malloc(o);if(!p)throw new n.ErrnoError(48);const d=t.HEAPU8.subarray(p,p+o);let f=0;for(;f<o;){const _=i.stream_ops.read(i,d,f,o-f,f);if(_<=0)break;f+=_}if(f!==o)throw t.free(p),new n.ErrnoError(5);return{ptr:p,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",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=p=>{p.isDir(t)||p.mkdir(t),p.chdir(t),p.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 p=>{const d=await e.phpFactory({...p,requestHandler:this});return a(d),d},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:p,contentType:d}=await encodeAsMultipart(c);c=p,a["content-type"]=d}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 p=u(this,F);l.headers.then(d=>{p.rememberCookiesFromResponseHeaders(d)})}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 p=t.malloc(o);if(!p)throw new n.ErrnoError(48);const d=t.HEAPU8.subarray(p,p+o);let f=0;for(;f<o;){const _=i.stream_ops.read(i,d,f,o-f,f);if(_<=0)break;f+=_}if(f!==o)throw t.free(p),new n.ErrnoError(5);return{ptr:p,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 p=NodeSABSyncReceiveMessageTransport.receiveMessageOnPort(e);if(((l=p.message)==null?void 0:l.id)===o)return p.message;if(!p)throw new Error("No response received")}}}/**
92
92
  * Original, unmodified Comlink library from Google:
@@ -98,5 +98,5 @@ ${JSON.stringify(r.headers,null,2)}
98
98
  * @license
99
99
  * Copyright 2019 Google LLC
100
100
  * SPDX-License-Identifier: Apache-2.0
101
- */const WireValueType={RAW:"RAW",HANDLER:"HANDLER"},MessageType={GET:"GET",SET:"SET",APPLY:"APPLY",CONSTRUCT:"CONSTRUCT",ENDPOINT:"ENDPOINT",RELEASE:"RELEASE"},isObject=r=>typeof r=="object"&&r!==null||typeof r=="function",proxyTransferHandler={canHandle:r=>isObject(r)&&r[proxyMarker],serialize(r){const{port1:e,port2:t}=new MessageChannel;return expose(r,e),[t,[t]]},deserialize(r){return r.start(),wrap(r)}},throwTransferHandler$1={canHandle:r=>isObject(r)&&throwMarker in r,serialize({value:r}){let e;return r instanceof Error?e={isError:!0,value:{message:r.message,name:r.name,stack:r.stack}}:e={isError:!1,value:r},[e,[]]},deserialize(r){throw r.isError?Object.assign(new Error(r.value.message),r.value):r.value}},transferHandlers=new Map([["proxy",proxyTransferHandler],["throw",throwTransferHandler$1]]);function isAllowedOrigin(r,e){for(const t of r)if(e===t||t==="*"||t instanceof RegExp&&t.test(e))return!0;return!1}function expose(r,e=globalThis,t=["*"],s){e.addEventListener("message",function n(i){if(!i||!i.data)return;if(!isAllowedOrigin(t,i.origin)){console.warn(`Invalid origin '${i.origin}' for comlink proxy`);return}const{id:o,type:a,path:c}={path:[],...i.data},l=(i.data.argumentList||[]).map(fromWireValue);let p;try{const d=c.slice(0,-1).reduce((_,k)=>_[k],r),f=c.reduce((_,k)=>_[k],r);switch(a){case MessageType.GET:p=f;break;case MessageType.SET:d[c.slice(-1)[0]]=fromWireValue(i.data.value),p=!0;break;case MessageType.APPLY:p=f.apply(d,l);break;case MessageType.CONSTRUCT:{const _=new f(...l);p=proxy(_)}break;case MessageType.ENDPOINT:{const{port1:_,port2:k}=new MessageChannel;expose(r,k),p=transfer(_,[_])}break;case MessageType.RELEASE:p=void 0;break;default:return}}catch(d){p={value:d,[throwMarker]:0}}Promise.resolve(p).catch(d=>({value:d,[throwMarker]:0})).then(d=>{const[f,_]=toWireValue(d);e.postMessage({...f,id:o},_),a===MessageType.RELEASE&&(e.removeEventListener("message",n),closeEndPoint(e),finalizer in r&&typeof r[finalizer]=="function"&&r[finalizer]())}).catch(()=>{const[d,f]=toWireValue({value:new TypeError("Unserializable return value"),[throwMarker]:0});e.postMessage({...d,id:o},f)}).finally(()=>{s==null||s(i)})}),e.start&&e.start()}function isMessagePort(r){return r.constructor.name==="MessagePort"}function closeEndPoint(r){isMessagePort(r)&&r.close()}function wrap(r,e){const t=new Map;return r.addEventListener("message",function(n){const{data:i}=n;if(!i||!i.id)return;const o=t.get(i.id);if(o)try{o(i)}finally{t.delete(i.id)}}),createProxy(r,t,[],e)}function throwIfProxyReleased(r){if(r)throw new Error("Proxy has been released and is not useable")}function releaseEndpoint(r){return requestResponseMessage(r,new Map,{type:MessageType.RELEASE}).then(()=>{closeEndPoint(r)})}const proxyCounter=new WeakMap,proxyFinalizers="FinalizationRegistry"in globalThis&&new FinalizationRegistry(r=>{const e=(proxyCounter.get(r)||0)-1;proxyCounter.set(r,e),e===0&&releaseEndpoint(r)});function registerProxy(r,e){const t=(proxyCounter.get(e)||0)+1;proxyCounter.set(e,t),proxyFinalizers&&proxyFinalizers.register(r,e,r)}function unregisterProxy(r){proxyFinalizers&&proxyFinalizers.unregister(r)}function createProxy(r,e,t=[],s=function(){}){let n=!1;const i=new Proxy(s,{get(o,a){if(throwIfProxyReleased(n),a===releaseProxy)return()=>{unregisterProxy(i),releaseEndpoint(r),e.clear(),n=!0};if(a==="then"){if(t.length===0)return{then:()=>i};const c=requestResponseMessage(r,e,{type:MessageType.GET,path:t.map(l=>l.toString())}).then(fromWireValue);return c.then.bind(c)}return createProxy(r,e,[...t,a])},set(o,a,c){throwIfProxyReleased(n);const[l,p]=toWireValue(c);return requestResponseMessage(r,e,{type:MessageType.SET,path:[...t,a].map(d=>d.toString()),value:l},p).then(fromWireValue)},apply(o,a,c){throwIfProxyReleased(n);const l=t[t.length-1];if(l===createEndpoint)return requestResponseMessage(r,e,{type:MessageType.ENDPOINT}).then(fromWireValue);if(l==="bind")return createProxy(r,e,t.slice(0,-1));const[p,d]=processArguments(c);return requestResponseMessage(r,e,{type:MessageType.APPLY,path:t.map(f=>f.toString()),argumentList:p},d).then(fromWireValue)},construct(o,a){throwIfProxyReleased(n);const[c,l]=processArguments(a);return requestResponseMessage(r,e,{type:MessageType.CONSTRUCT,path:t.map(p=>p.toString()),argumentList:c},l).then(fromWireValue)}});return registerProxy(i,r),i}function myFlat(r){return Array.prototype.concat.apply([],r)}function processArguments(r){const e=r.map(toWireValue);return[e.map(t=>t[0]),myFlat(e.map(t=>t[1]))]}const transferCache=new WeakMap;function transfer(r,e){return transferCache.set(r,e),r}function proxy(r){return Object.assign(r,{[proxyMarker]:!0})}function windowEndpoint(r,e=globalThis,t="*"){return{postMessage:(s,n)=>r.postMessage(s,t,n),addEventListener:e.addEventListener.bind(e),removeEventListener:e.removeEventListener.bind(e)}}function toWireValue(r){for(const[e,t]of transferHandlers)if(t.canHandle(r)){const[s,n]=t.serialize(r);return[{type:WireValueType.HANDLER,name:e,value:s},n]}return[{type:WireValueType.RAW,value:r},transferCache.get(r)||[]]}function fromWireValue(r){switch(r.type){case WireValueType.HANDLER:return transferHandlers.get(r.name).deserialize(r.value);case WireValueType.RAW:return r.value}}function requestResponseMessage(r,e,t,s){return new Promise(n=>{const i=generateUUID();e.set(i,n),r.start&&r.start(),r.postMessage({id:i,...t},s)})}function generateUUID(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function nodeEndpoint(r){const e=new WeakMap;return{postMessage:r.postMessage.bind(r),addEventListener:(t,s)=>{const n=i=>{"handleEvent"in s?s.handleEvent({data:i}):s({data:i})};r.on("message",n),e.set(s,n)},removeEventListener:(t,s)=>{const n=e.get(s);n&&(r.off("message",n),e.delete(s))},start:r.start&&r.start.bind(r)}}const proxyByListener=new WeakMap;function nodeProcessEndpoint(r){const e=r||process;if(typeof e.send!="function")throw new Error("IPC channel is not available. Did you forget to fork the process?");const t=e;return{postMessage(s,n){var i;if(n&&n.length>0)throw new Error("Transferable objects are not supported for nodeProcessEndpoint");(i=t.send)==null||i.call(t,s)},addEventListener(s,n){const i=typeof n=="function"?o=>n({data:o}):o=>n.handleEvent({data:o});proxyByListener.set(n,i),t.addListener(s,i)},removeEventListener(s,n){const i=proxyByListener.get(n);i&&(proxyByListener.delete(n),t.removeListener(s,i))},start(){}}}const list=[Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError,globalThis.DOMException,globalThis.AssertionError,globalThis.SystemError].filter(Boolean).map(r=>[r.name,r]),errorConstructors=new Map(list);class NonError extends Error{constructor(e){super(NonError._prepareSuperMessage(e)),this.name="NonError"}static _prepareSuperMessage(e){try{return JSON.stringify(e)}catch{return String(e)}}}const errorProperties=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1},{property:"errors",enumerable:!1}],toJsonWasCalled=new WeakSet,toJSON=r=>{toJsonWasCalled.add(r);const e=r.toJSON();return toJsonWasCalled.delete(r),e},newError=r=>{const e=errorConstructors.get(r)??Error;return e===AggregateError?new e([]):new e},destroyCircular=({from:r,seen:e,to:t,forceEnumerable:s,maxDepth:n,depth:i,useToJSON:o,serialize:a})=>{if(t||(Array.isArray(r)?t=[]:!a&&isErrorLike(r)?t=newError(r.name):t={}),e.push(r),i>=n)return t;if(o&&typeof r.toJSON=="function"&&!toJsonWasCalled.has(r))return toJSON(r);const c=l=>destroyCircular({from:l,seen:[...e],forceEnumerable:s,maxDepth:n,depth:i,useToJSON:o,serialize:a});for(const[l,p]of Object.entries(r)){if(p&&p instanceof Uint8Array&&p.constructor.name==="Buffer"){t[l]="[object Buffer]";continue}if(p!==null&&typeof p=="object"&&typeof p.pipe=="function"){t[l]="[object Stream]";continue}if(typeof p!="function"){if(!p||typeof p!="object"){try{t[l]=p}catch{}continue}if(!e.includes(r[l])){i++,t[l]=c(r[l]);continue}t[l]="[Circular]"}}if(a||t instanceof Error)for(const{property:l,enumerable:p}of errorProperties)r[l]!==void 0&&r[l]!==null&&Object.defineProperty(t,l,{value:isErrorLike(r[l])||Array.isArray(r[l])?c(r[l]):r[l],enumerable:s?!0:p,configurable:!0,writable:!0});return t};function serializeError(r,e={}){const{maxDepth:t=Number.POSITIVE_INFINITY,useToJSON:s=!0}=e;return typeof r=="object"&&r!==null?destroyCircular({from:r,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:s,serialize:!0}):typeof r=="function"?`[Function: ${r.name||"anonymous"}]`:r}function deserializeError(r,e={}){const{maxDepth:t=Number.POSITIVE_INFINITY}=e;return r instanceof Error?r:isMinimumViableSerializedError(r)?destroyCircular({from:r,seen:[],to:newError(r.name),maxDepth:t,depth:0,serialize:!1}):new NonError(r)}function isErrorLike(r){return!!r&&typeof r=="object"&&typeof r.name=="string"&&typeof r.message=="string"&&typeof r.stack=="string"}function isMinimumViableSerializedError(r){return!!r&&typeof r=="object"&&typeof r.message=="string"&&!Array.isArray(r)}const releaseApiProxy=releaseProxy;async function consumeAPISync(r){setupTransferHandlers();const e=await NodeSABSyncReceiveMessageTransport.create();return wrapSync(r,e)}function consumeAPI(r,e=void 0){setupTransferHandlers();let t;if(typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u")if("postMessage"in r)t=nodeEndpoint(r);else if("send"in r&&"addListener"in r)t=nodeProcessEndpoint(r);else throw new Error("consumeAPI: remote does not look like a Worker, MessagePort, or Process");else t=r instanceof Worker?r:windowEndpoint(r,e);const n=wrap(t),i=proxyClone(n);return new Proxy(i,{get:(o,a)=>a==="isConnected"?async()=>{for(;;)try{await runWithTimeout(n.isConnected(),200);break}catch{}}:n[a]})}async function runWithTimeout(r,e){return new Promise((t,s)=>{setTimeout(s,e),r.then(t)})}function exposeAPI(r,e,t){const{setReady:s,setFailed:n,exposedApi:i}=prepareForExpose(r,e);let o;if(t)if("addEventListener"in t)o=t;else if("postMessage"in t)o=nodeEndpoint(t);else if("send"in t&&"addListener"in t)o=nodeProcessEndpoint(t);else throw new Error("exposeAPI: targetWorker does not look like a Worker, MessagePort, or Process");else o=typeof window<"u"?windowEndpoint(self.parent):void 0;return expose(i,o),[s,n,i]}async function exposeSyncAPI(r,e){const{setReady:t,setFailed:s,exposedApi:n}=prepareForExpose(r),i=await NodeSABSyncReceiveMessageTransport.create(),o=nodeEndpoint(e);return exposeSync(n,o,i),[t,s,n]}function prepareForExpose(r,e){setupTransferHandlers();const t=Promise.resolve();let s,n;const i=new Promise((c,l)=>{s=c,n=l}),o=proxyClone(r),a=new Proxy(o,{get:(c,l)=>l==="isConnected"?()=>t:l==="isReady"?()=>i:l in c?c[l]:e==null?void 0:e[l]});return{setReady:s,setFailed:n,exposedApi:a}}let isTransferHandlersSetup=!1;function setupTransferHandlers(){if(isTransferHandlersSetup)return;isTransferHandlersSetup=!0,transferHandlers.set("EVENT",{canHandle:t=>t instanceof CustomEvent,serialize:t=>[{detail:t.detail},[]],deserialize:t=>t}),transferHandlers.set("FUNCTION",{canHandle:t=>typeof t=="function",serialize(t){const{port1:s,port2:n}=new MessageChannel;return expose(t,s),[n,[n]]},deserialize(t){return t.start(),wrap(t)}}),transferHandlers.set("MESSAGE_PORT",{canHandle:t=>t instanceof MessagePort,serialize(t){return[t,[t]]},deserialize(t){return t}}),transferHandlers.set("PHPResponse",{canHandle:t=>typeof t=="object"&&t!==null&&"headers"in t&&"bytes"in t&&"errors"in t&&"exitCode"in t&&"httpStatusCode"in t,serialize(t){const s=t.toRawData(),n=[];return s.bytes.buffer.byteLength>0&&n.push(s.bytes.buffer),[s,n]},deserialize(t){return PHPResponse.fromRawData(t)}});const r=transferHandlers.get("throw"),e=r==null?void 0:r.serialize;r.serialize=({value:t})=>{const s=e({value:t});return t.response&&(s[0].value.response=t.response),t.source&&(s[0].value.source=t.source),s},transferHandlers.set("StreamedPHPResponse",{canHandle:t=>t instanceof StreamedPHPResponse,serialize(t){const s=supportsTransferableStreams(),n=promiseToPort(t.exitCode);if(s)return[{__type:"StreamedPHPResponse",headers:t.headersStream,stdout:t.stdout,stderr:t.stderr,exitCodePort:n},[n]];const i=streamToPort(t.headersStream),o=streamToPort(t.stdout),a=streamToPort(t.stderr);return[{__type:"StreamedPHPResponse",headersPort:i,stdoutPort:o,stderrPort:a,exitCodePort:n},[i,o,a,n]]},deserialize(t){if(t.headers&&t.stdout&&t.stderr){const a=portToPromise(t.exitCodePort);return new StreamedPHPResponse(t.headers,t.stdout,t.stderr,a)}const s=portToStream(t.headersPort),n=portToStream(t.stdoutPort),i=portToStream(t.stderrPort),o=portToPromise(t.exitCodePort);return new StreamedPHPResponse(s,n,i,o)}})}function supportsTransferableStreams(){try{if(typeof ReadableStream>"u")return!1;const{port1:r}=new MessageChannel,e=new ReadableStream;r.postMessage(e);try{r.close()}catch{}return!0}catch{return!1}}function streamToPort(r){const{port1:e,port2:t}=new MessageChannel;return(async()=>{const s=r.getReader();try{for(;;){const{done:n,value:i}=await s.read();if(n){try{e.postMessage({t:"close"})}catch{}try{e.close()}catch{}break}if(i){const o=i.byteOffset===0&&i.byteLength===i.buffer.byteLength?i:i.slice(),a=o.buffer;try{e.postMessage({t:"chunk",b:a},[a])}catch{e.postMessage({t:"chunk",b:o.buffer.slice(0)})}}}}catch(n){try{e.postMessage({t:"error",m:(n==null?void 0:n.message)||String(n)})}catch{}}finally{try{e.close()}catch{}}})(),t}function portToStream(r){return new ReadableStream({start(e){const t=n=>{const i=n.data;if(i)switch(i.t){case"chunk":e.enqueue(new Uint8Array(i.b));break;case"close":e.close(),s();break;case"error":e.error(new Error(i.m||"Stream error")),s();break}},s=()=>{var n;try{(n=r.removeEventListener)==null||n.call(r,"message",t)}catch{}try{r.onmessage=null}catch{}try{r.close()}catch{}};r.addEventListener?r.addEventListener("message",t):r.on?r.on("message",n=>t({data:n})):r.onmessage=t,typeof r.start=="function"&&r.start()},cancel(){try{r.close()}catch{}}})}function promiseToPort(r){const{port1:e,port2:t}=new MessageChannel;return r.then(s=>{try{e.postMessage({t:"resolve",v:s})}catch{}}).catch(s=>{try{e.postMessage({t:"reject",m:(s==null?void 0:s.message)||String(s)})}catch{}}).finally(()=>{try{e.close()}catch{}}),t}function portToPromise(r){return new Promise((e,t)=>{const s=i=>{const o=i.data;o&&(o.t==="resolve"?(n(),e(o.v)):o.t==="reject"&&(n(),t(new Error(o.m||""))))},n=()=>{var i;try{(i=r.removeEventListener)==null||i.call(r,"message",s)}catch{}try{r.onmessage=null}catch{}try{r.close()}catch{}};r.addEventListener?r.addEventListener("message",s):r.on?r.on("message",i=>s({data:i})):r.onmessage=s,typeof r.start=="function"&&r.start()})}const throwTransferHandler=transferHandlers.get("throw"),throwTransferHandlerCustom={canHandle:throwTransferHandler.canHandle,serialize:({value:r})=>{let e;return r instanceof Error?(e={isError:!0,value:serializeError(r)},e.value.originalErrorClassName=r.constructor.name):e={isError:!1,value:r},[e,[]]},deserialize:r=>{if(r.isError){const e=deserializeError(r.value),t=new Error("Comlink method call failed");let s=e;for(;s.cause;)s=s.cause;throw s.cause=t,e}throw r.value}};transferHandlers.set("throw",throwTransferHandlerCustom);function proxyClone(r){return new Proxy(r,{get(e,t){switch(typeof e[t]){case"function":return(...s)=>e[t](...s);case"object":return e[t]===null?e[t]:proxyClone(e[t]);case"undefined":case"number":case"string":return e[t];default:return proxy(e[t])}}})}const MAX_ADDRESSABLE_FILE_OFFSET=BigInt(Number.MAX_SAFE_INTEGER);class IntervalNode{constructor(e){this.left=null,this.right=null,this.range=e,this.max=e.end}}class FileLockIntervalTree{constructor(){this.root=null}isEmpty(){return this.root===null}insert(e){this.root=this.insertNode(this.root,e)}findOverlapping(e){const t=[];return this.findOverlappingRanges(this.root,e,t),t}remove(e){this.root=this.removeNode(this.root,e)}findLocksForProcess(e){const t=[];return this.findLocksForProcessInNode(this.root,e,t),t}findStrictestExistingLockType(){let e="unlocked";const t=s=>{if(s){if(s.range.type==="exclusive"){e="exclusive";return}s.range.type==="shared"&&(e="shared"),t(s.left),t(s.right)}};return t(this.root),e}insertNode(e,t){return e?(t.start<e.range.start?e.left=this.insertNode(e.left,t):e.right=this.insertNode(e.right,t),e.max=this.bigintMax(e.max,t.end),e):new IntervalNode(t)}bigintMax(...e){return e.reduce((t,s)=>s>t?s:t,e[0])}findOverlappingRanges(e,t,s){e&&(this.doRangesOverlap(e.range,t)&&s.push(e.range),e.left&&e.left.max>=t.start&&this.findOverlappingRanges(e.left,t,s),e.right&&e.range.start<=t.end&&this.findOverlappingRanges(e.right,t,s))}doRangesOverlap(e,t){return e.start<t.end&&t.start<e.end}removeNode(e,t){if(!e)return null;if(this.areRangesEqual(e.range,t)){if(!e.left)return e.right;if(!e.right)return e.left;const s=this.findMin(e.right);e.range=s.range,e.right=this.removeNode(e.right,s.range)}else t.start<e.range.start?e.left=this.removeNode(e.left,t):e.right=this.removeNode(e.right,t);return e.max=e.range.end,e.left&&(e.max=this.bigintMax(e.max,e.left.max)),e.right&&(e.max=this.bigintMax(e.max,e.right.max)),e}findMin(e){let t=e;for(;t.left;)t=t.left;return t}areRangesEqual(e,t){return e.start===t.start&&e.end===t.end&&e.pid===t.pid&&e.fd===t.fd}findLocksForProcessInNode(e,t,s){e&&(e.range.pid===t&&s.push(e.range),this.findLocksForProcessInNode(e.left,t,s),this.findLocksForProcessInNode(e.right,t,s))}}class FileLockManagerInMemory{constructor(){this.locks=new Map}lockWholeFile(e,t){if(this.locks.get(e)===void 0){if(t.type==="unlock")return!0;this.locks.set(e,new FileLock)}const n=this.locks.get(e).lockWholeFile(t);return this.forgetPathIfUnlocked(e),n}lockFileByteRange(e,t){if(!this.locks.has(e)){if(t.type==="unlocked")return!0;this.locks.set(e,new FileLock)}return this.locks.get(e).lockFileByteRange(t)}findFirstConflictingByteRangeLock(e,t){const s=this.locks.get(e);if(s!==void 0)return s.findFirstConflictingByteRangeLock(t)}releaseLocksForProcess(e){for(const[t,s]of this.locks.entries())s.releaseLocksForProcess(e),this.forgetPathIfUnlocked(t)}releaseLocksOnFdClose(e,t,s){const n=this.locks.get(s);n&&(n.releaseLocksOnFdClose(e,t),this.forgetPathIfUnlocked(s))}forgetPathIfUnlocked(e){const t=this.locks.get(e);t&&t.isUnlocked()&&this.locks.delete(e)}}class FileLock{constructor(){this.rangeLocks=new FileLockIntervalTree,this.wholeFileLock={type:"unlocked"}}lockWholeFile(e){if(e.type==="unlock")return this.wholeFileLock.type==="unlocked"||(this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid===e.pid&&this.wholeFileLock.fd===e.fd?this.wholeFileLock={type:"unlocked"}:this.wholeFileLock.type==="shared"&&this.wholeFileLock.pidFds.has(e.pid)&&this.wholeFileLock.pidFds.get(e.pid).has(e.fd)&&(this.wholeFileLock.pidFds.get(e.pid).delete(e.fd),this.wholeFileLock.pidFds.get(e.pid).size===0&&this.wholeFileLock.pidFds.delete(e.pid),this.wholeFileLock.pidFds.size===0&&(this.wholeFileLock={type:"unlocked"}))),!0;if(this.isThereAConflictWithRequestedWholeFileLock(e))return!1;if(e.type==="exclusive")return this.wholeFileLock={type:"exclusive",pid:e.pid,fd:e.fd},!0;if(e.type==="shared"){this.wholeFileLock.type!=="shared"&&(this.wholeFileLock={type:"shared",pidFds:new Map});const t=this.wholeFileLock;return t.pidFds.has(e.pid)||t.pidFds.set(e.pid,new Set),t.pidFds.get(e.pid).add(e.fd),!0}throw new Error(`Unexpected wholeFileLock() op: '${e.type}'`)}lockFileByteRange(e){if(e.start===e.end&&(e={...e,end:MAX_ADDRESSABLE_FILE_OFFSET}),e.type==="unlocked"){const o=this.rangeLocks.findOverlapping(e).filter(a=>a.pid===e.pid);for(const a of o)this.rangeLocks.remove(a),a.start<e.start&&this.rangeLocks.insert({...a,end:e.start}),a.end>e.end&&this.rangeLocks.insert({...a,start:e.end});return!0}if(this.isThereAConflictWithRequestedRangeLock(e))return!1;const t=this.rangeLocks.findOverlapping(e).filter(o=>o.pid===e.pid);let s=e.start,n=e.end;for(const o of t)this.rangeLocks.remove(o),o.start<s&&(s=o.start),o.end>n&&(n=o.end);const i={...e,start:s,end:n};return this.rangeLocks.insert(i),!0}findFirstConflictingByteRangeLock(e){e.start===e.end&&(e={...e,end:MAX_ADDRESSABLE_FILE_OFFSET});const s=this.rangeLocks.findOverlapping(e).find(i=>i.pid!==e.pid&&(e.type==="exclusive"||i.type==="exclusive"));if(s)return s;if(this.wholeFileLock.type==="unlocked")return;if(this.wholeFileLock.type==="exclusive"||e.type==="exclusive")return{type:this.wholeFileLock.type,start:0n,end:0n,pid:-1}}releaseLocksForProcess(e){for(const t of this.rangeLocks.findLocksForProcess(e))this.lockFileByteRange({...t,type:"unlocked"});if(this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid===e)this.lockWholeFile({pid:e,fd:this.wholeFileLock.fd,type:"unlock"});else if(this.wholeFileLock.type==="shared"&&this.wholeFileLock.pidFds.has(e))for(const t of this.wholeFileLock.pidFds.get(e))this.lockWholeFile({pid:e,fd:t,type:"unlock"})}releaseLocksOnFdClose(e,t){for(const s of this.rangeLocks.findLocksForProcess(e))this.lockFileByteRange({...s,type:"unlocked"});this.lockWholeFile({pid:e,fd:t,type:"unlock"})}isUnlocked(){return this.wholeFileLock.type==="unlocked"&&this.rangeLocks.isEmpty()}isThereAConflictWithRequestedRangeLock(e){return this.findFirstConflictingByteRangeLock(e)!==void 0}isThereAConflictWithRequestedWholeFileLock(e){return e.type==="exclusive"?!!(this.wholeFileLock.type==="exclusive"&&(this.wholeFileLock.fd!==e.fd||this.wholeFileLock.pid!==e.pid)||this.wholeFileLock.type==="shared"&&Array.from(this.wholeFileLock.pidFds).some(([s])=>s!==e.pid)||this.rangeLocks.findOverlapping({start:0n,end:MAX_ADDRESSABLE_FILE_OFFSET}).length>0):e.type==="shared"?this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid!==e.pid||this.rangeLocks.findOverlapping({start:0n,end:MAX_ADDRESSABLE_FILE_OFFSET}).filter(n=>n.type==="exclusive").length>0:!1}}class FileLockManagerComposite{constructor({nativeLockManager:e,wasmLockManager:t}){this.nativeLockManager=e,this.wasmLockManager=t}lockWholeFile(e,t){if(t.type!=="unlock"){let s,n;try{if(s=this.nativeLockManager.lockWholeFile(e,t),!s)return!1;n=this.wasmLockManager.lockWholeFile(e,t)}catch(i){logger.logger.error("Unexpected error in lockWholeFile()",i)}finally{s&&!n&&this.nativeLockManager.lockWholeFile(e,{...t,type:"unlock"})}return!!s&&!!n}try{this.wasmLockManager.lockWholeFile(e,t)}catch(s){logger.logger.error("Unexpected error unlocking whole file with in-memory lock manager",s)}try{this.nativeLockManager.lockWholeFile(e,t)}catch(s){logger.logger.error("Unexpected error unlocking whole file with native lock manager",s)}return!0}lockFileByteRange(e,t,s){if(t.type!=="unlocked"){let n,i;try{if(n=this.nativeLockManager.lockFileByteRange(e,t,s),!n)return!1;i=this.wasmLockManager.lockFileByteRange(e,t,s)}catch(o){logger.logger.error("Unexpected error in lockFileByteRange()",o)}finally{n&&!i&&this.nativeLockManager.lockFileByteRange(e,{...t,type:"unlocked"},!1)}return!!n&&!!i}try{this.wasmLockManager.lockFileByteRange(e,t,s)}catch(n){logger.logger.error("Unexpected error unlocking byte range with in-memory lock manager",n)}try{this.nativeLockManager.lockFileByteRange(e,t,s)}catch(n){logger.logger.error("Unexpected error unlocking byte range with native lock manager",n)}return!0}findFirstConflictingByteRangeLock(e,t){try{const s=this.nativeLockManager.findFirstConflictingByteRangeLock(e,t);return s||this.wasmLockManager.findFirstConflictingByteRangeLock(e,t)}catch(s){logger.logger.error("Unexpected error in findFirstConflictingByteRangeLock()",s);return}}releaseLocksForProcess(e){try{this.wasmLockManager.releaseLocksForProcess(e)}catch(t){logger.logger.error("Unexpected error in wasmLockManager.releaseLocksForProcess()",t)}try{this.nativeLockManager.releaseLocksForProcess(e)}catch(t){logger.logger.error("Unexpected error in nativeLockManager.releaseLocksForProcess()",t)}}releaseLocksOnFdClose(e,t,s){try{this.wasmLockManager.releaseLocksOnFdClose(e,t,s)}catch(n){logger.logger.error("Unexpected error in wasmLockManager.releaseLocksOnFdClose()",n)}try{this.nativeLockManager.releaseLocksOnFdClose(e,t,s)}catch(n){logger.logger.error("Unexpected error in nativeLockManager.releaseLocksOnFdClose()",n)}}}function createObjectPoolProxy(r){if(r.length===0)throw new Error("At least one instance is required");const e=[...r],t=[];function s(){const o=e.shift();return o!==void 0?Promise.resolve(o):new Promise(a=>{t.push(a)})}function n(o){const a=t.shift();a?a(o):e.push(o)}function i(o){return s().then(a=>{let c;try{c=o(a)}catch(l){throw n(a),l}return c!=null&&typeof c.then=="function"?c.then(l=>(n(a),l),l=>{throw n(a),l}):(n(a),c)})}return new Proxy({},{get(o,a){if(a in o)return o[a];if(a!=="then")return new Proxy(function(){},{apply(c,l,p){return i(d=>d[a](...p))},get(c,l){if(l==="then")return(p,d)=>i(f=>f[a]).then(p,d)}})}})}exports.DEFAULT_BASE_URL=DEFAULT_BASE_URL;exports.FSHelpers=FSHelpers;exports.FileLock=FileLock;exports.FileLockIntervalTree=FileLockIntervalTree;exports.FileLockManagerComposite=FileLockManagerComposite;exports.FileLockManagerInMemory=FileLockManagerInMemory;exports.HttpCookieStore=HttpCookieStore;exports.LatestSupportedPHPVersion=LatestSupportedPHPVersion;exports.MAX_ADDRESSABLE_FILE_OFFSET=MAX_ADDRESSABLE_FILE_OFFSET;exports.PHP=PHP;exports.PHPExecutionFailureError=PHPExecutionFailureError;exports.PHPProcessManager=PHPProcessManager;exports.PHPRequestHandler=PHPRequestHandler;exports.PHPResponse=PHPResponse;exports.PHPWorker=PHPWorker;exports.SinglePHPInstanceManager=SinglePHPInstanceManager;exports.StreamedPHPResponse=StreamedPHPResponse;exports.SupportedPHPVersions=SupportedPHPVersions;exports.SupportedPHPVersionsList=SupportedPHPVersionsList;exports.UnhandledRejectionsTarget=UnhandledRejectionsTarget;exports.__private__dont__use=__private__dont__use;exports.applyRewriteRules=applyRewriteRules;exports.consumeAPI=consumeAPI;exports.consumeAPISync=consumeAPISync;exports.createObjectPoolProxy=createObjectPoolProxy;exports.ensurePathPrefix=ensurePathPrefix;exports.exposeAPI=exposeAPI;exports.exposeSyncAPI=exposeSyncAPI;exports.getPhpIniEntries=getPhpIniEntries;exports.inferMimeType=inferMimeType;exports.isExitCode=isExitCode;exports.isPathToSharedFS=isPathToSharedFS;exports.iterateFiles=iteratePhpFiles;exports.loadPHPRuntime=loadPHPRuntime;exports.popLoadedRuntime=popLoadedRuntime;exports.prettyPrintFullStackTrace=prettyPrintFullStackTrace;exports.printDebugDetails=printDebugDetails;exports.printResponseDebugDetails=printResponseDebugDetails;exports.proxyFileSystem=proxyFileSystem;exports.releaseApiProxy=releaseApiProxy;exports.removePathPrefix=removePathPrefix;exports.rotatePHPRuntime=rotatePHPRuntime;exports.sandboxedSpawnHandlerFactory=sandboxedSpawnHandlerFactory;exports.setPhpIniEntries=setPhpIniEntries;exports.toRelativeUrl=toRelativeUrl;exports.withPHPIniValues=withPHPIniValues;exports.writeFiles=writeFiles;exports.writeFilesStreamToPhp=writeFilesStreamToPhp;
101
+ */const WireValueType={RAW:"RAW",HANDLER:"HANDLER"},MessageType={GET:"GET",SET:"SET",APPLY:"APPLY",CONSTRUCT:"CONSTRUCT",ENDPOINT:"ENDPOINT",RELEASE:"RELEASE"},isObject=r=>typeof r=="object"&&r!==null||typeof r=="function",proxyTransferHandler={canHandle:r=>isObject(r)&&r[proxyMarker],serialize(r){const{port1:e,port2:t}=new MessageChannel;return expose(r,e),[t,[t]]},deserialize(r){return r.start(),wrap(r)}},throwTransferHandler$1={canHandle:r=>isObject(r)&&throwMarker in r,serialize({value:r}){let e;return r instanceof Error?e={isError:!0,value:{message:r.message,name:r.name,stack:r.stack}}:e={isError:!1,value:r},[e,[]]},deserialize(r){throw r.isError?Object.assign(new Error(r.value.message),r.value):r.value}},transferHandlers=new Map([["proxy",proxyTransferHandler],["throw",throwTransferHandler$1]]);function isAllowedOrigin(r,e){for(const t of r)if(e===t||t==="*"||t instanceof RegExp&&t.test(e))return!0;return!1}function expose(r,e=globalThis,t=["*"],s){e.addEventListener("message",function n(i){if(!i||!i.data)return;if(!isAllowedOrigin(t,i.origin)){console.warn(`Invalid origin '${i.origin}' for comlink proxy`);return}const{id:o,type:a,path:c}={path:[],...i.data},l=(i.data.argumentList||[]).map(fromWireValue);let p;try{const d=c.slice(0,-1).reduce((_,k)=>_[k],r),f=c.reduce((_,k)=>_[k],r);switch(a){case MessageType.GET:p=f;break;case MessageType.SET:d[c.slice(-1)[0]]=fromWireValue(i.data.value),p=!0;break;case MessageType.APPLY:p=f.apply(d,l);break;case MessageType.CONSTRUCT:{const _=new f(...l);p=proxy(_)}break;case MessageType.ENDPOINT:{const{port1:_,port2:k}=new MessageChannel;expose(r,k),p=transfer(_,[_])}break;case MessageType.RELEASE:p=void 0;break;default:return}}catch(d){p={value:d,[throwMarker]:0}}Promise.resolve(p).catch(d=>({value:d,[throwMarker]:0})).then(d=>{const[f,_]=toWireValue(d);e.postMessage({...f,id:o},_),a===MessageType.RELEASE&&(e.removeEventListener("message",n),closeEndPoint(e),finalizer in r&&typeof r[finalizer]=="function"&&r[finalizer]())}).catch(()=>{const[d,f]=toWireValue({value:new TypeError("Unserializable return value"),[throwMarker]:0});e.postMessage({...d,id:o},f)}).finally(()=>{s==null||s(i)})}),e.start&&e.start()}function isMessagePort(r){return r.constructor.name==="MessagePort"}function closeEndPoint(r){isMessagePort(r)&&r.close()}function wrap(r,e){const t=new Map;return r.addEventListener("message",function(n){const{data:i}=n;if(!i||!i.id)return;const o=t.get(i.id);if(o)try{o(i)}finally{t.delete(i.id)}}),createProxy(r,t,[],e)}function throwIfProxyReleased(r){if(r)throw new Error("Proxy has been released and is not useable")}function releaseEndpoint(r){return requestResponseMessage(r,new Map,{type:MessageType.RELEASE}).then(()=>{closeEndPoint(r)})}const proxyCounter=new WeakMap,proxyFinalizers="FinalizationRegistry"in globalThis&&new FinalizationRegistry(r=>{const e=(proxyCounter.get(r)||0)-1;proxyCounter.set(r,e),e===0&&releaseEndpoint(r)});function registerProxy(r,e){const t=(proxyCounter.get(e)||0)+1;proxyCounter.set(e,t),proxyFinalizers&&proxyFinalizers.register(r,e,r)}function unregisterProxy(r){proxyFinalizers&&proxyFinalizers.unregister(r)}function createProxy(r,e,t=[],s=function(){}){let n=!1;const i=new Proxy(s,{get(o,a){if(throwIfProxyReleased(n),a===releaseProxy)return()=>{unregisterProxy(i),releaseEndpoint(r),e.clear(),n=!0};if(a==="then"){if(t.length===0)return{then:()=>i};const c=requestResponseMessage(r,e,{type:MessageType.GET,path:t.map(l=>l.toString())}).then(fromWireValue);return c.then.bind(c)}return createProxy(r,e,[...t,a])},set(o,a,c){throwIfProxyReleased(n);const[l,p]=toWireValue(c);return requestResponseMessage(r,e,{type:MessageType.SET,path:[...t,a].map(d=>d.toString()),value:l},p).then(fromWireValue)},apply(o,a,c){throwIfProxyReleased(n);const l=t[t.length-1];if(l===createEndpoint)return requestResponseMessage(r,e,{type:MessageType.ENDPOINT}).then(fromWireValue);if(l==="bind")return createProxy(r,e,t.slice(0,-1));const[p,d]=processArguments(c);return requestResponseMessage(r,e,{type:MessageType.APPLY,path:t.map(f=>f.toString()),argumentList:p},d).then(fromWireValue)},construct(o,a){throwIfProxyReleased(n);const[c,l]=processArguments(a);return requestResponseMessage(r,e,{type:MessageType.CONSTRUCT,path:t.map(p=>p.toString()),argumentList:c},l).then(fromWireValue)}});return registerProxy(i,r),i}function myFlat(r){return Array.prototype.concat.apply([],r)}function processArguments(r){const e=r.map(toWireValue);return[e.map(t=>t[0]),myFlat(e.map(t=>t[1]))]}const transferCache=new WeakMap;function transfer(r,e){return transferCache.set(r,e),r}function proxy(r){return Object.assign(r,{[proxyMarker]:!0})}function windowEndpoint(r,e=globalThis,t="*"){return{postMessage:(s,n)=>r.postMessage(s,t,n),addEventListener:e.addEventListener.bind(e),removeEventListener:e.removeEventListener.bind(e)}}function toWireValue(r){for(const[e,t]of transferHandlers)if(t.canHandle(r)){const[s,n]=t.serialize(r);return[{type:WireValueType.HANDLER,name:e,value:s},n]}return[{type:WireValueType.RAW,value:r},transferCache.get(r)||[]]}function fromWireValue(r){switch(r.type){case WireValueType.HANDLER:return transferHandlers.get(r.name).deserialize(r.value);case WireValueType.RAW:return r.value}}function requestResponseMessage(r,e,t,s){return new Promise(n=>{const i=generateUUID();e.set(i,n),r.start&&r.start(),r.postMessage({id:i,...t},s)})}function generateUUID(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function nodeEndpoint(r){const e=new WeakMap;return{postMessage:r.postMessage.bind(r),addEventListener:(t,s)=>{const n=i=>{"handleEvent"in s?s.handleEvent({data:i}):s({data:i})};r.on("message",n),e.set(s,n)},removeEventListener:(t,s)=>{const n=e.get(s);n&&(r.off("message",n),e.delete(s))},start:r.start&&r.start.bind(r)}}const proxyByListener=new WeakMap;function nodeProcessEndpoint(r){const e=r||process;if(typeof e.send!="function")throw new Error("IPC channel is not available. Did you forget to fork the process?");const t=e;return{postMessage(s,n){var i;if(n&&n.length>0)throw new Error("Transferable objects are not supported for nodeProcessEndpoint");(i=t.send)==null||i.call(t,s)},addEventListener(s,n){const i=typeof n=="function"?o=>n({data:o}):o=>n.handleEvent({data:o});proxyByListener.set(n,i),t.addListener(s,i)},removeEventListener(s,n){const i=proxyByListener.get(n);i&&(proxyByListener.delete(n),t.removeListener(s,i))},start(){}}}const list=[Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError,globalThis.DOMException,globalThis.AssertionError,globalThis.SystemError].filter(Boolean).map(r=>[r.name,r]),errorConstructors=new Map(list);class NonError extends Error{constructor(e){super(NonError._prepareSuperMessage(e)),this.name="NonError"}static _prepareSuperMessage(e){try{return JSON.stringify(e)}catch{return String(e)}}}const errorProperties=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1},{property:"errors",enumerable:!1}],toJsonWasCalled=new WeakSet,toJSON=r=>{toJsonWasCalled.add(r);const e=r.toJSON();return toJsonWasCalled.delete(r),e},newError=r=>{const e=errorConstructors.get(r)??Error;return e===AggregateError?new e([]):new e},destroyCircular=({from:r,seen:e,to:t,forceEnumerable:s,maxDepth:n,depth:i,useToJSON:o,serialize:a})=>{if(t||(Array.isArray(r)?t=[]:!a&&isErrorLike(r)?t=newError(r.name):t={}),e.push(r),i>=n)return t;if(o&&typeof r.toJSON=="function"&&!toJsonWasCalled.has(r))return toJSON(r);const c=l=>destroyCircular({from:l,seen:[...e],forceEnumerable:s,maxDepth:n,depth:i,useToJSON:o,serialize:a});for(const[l,p]of Object.entries(r)){if(p&&p instanceof Uint8Array&&p.constructor.name==="Buffer"){t[l]="[object Buffer]";continue}if(p!==null&&typeof p=="object"&&typeof p.pipe=="function"){t[l]="[object Stream]";continue}if(typeof p!="function"){if(!p||typeof p!="object"){try{t[l]=p}catch{}continue}if(!e.includes(r[l])){i++,t[l]=c(r[l]);continue}t[l]="[Circular]"}}if(a||t instanceof Error)for(const{property:l,enumerable:p}of errorProperties)r[l]!==void 0&&r[l]!==null&&Object.defineProperty(t,l,{value:isErrorLike(r[l])||Array.isArray(r[l])?c(r[l]):r[l],enumerable:s?!0:p,configurable:!0,writable:!0});return t};function serializeError(r,e={}){const{maxDepth:t=Number.POSITIVE_INFINITY,useToJSON:s=!0}=e;return typeof r=="object"&&r!==null?destroyCircular({from:r,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:s,serialize:!0}):typeof r=="function"?`[Function: ${r.name||"anonymous"}]`:r}function deserializeError(r,e={}){const{maxDepth:t=Number.POSITIVE_INFINITY}=e;return r instanceof Error?r:isMinimumViableSerializedError(r)?destroyCircular({from:r,seen:[],to:newError(r.name),maxDepth:t,depth:0,serialize:!1}):new NonError(r)}function isErrorLike(r){return!!r&&typeof r=="object"&&typeof r.name=="string"&&typeof r.message=="string"&&typeof r.stack=="string"}function isMinimumViableSerializedError(r){return!!r&&typeof r=="object"&&typeof r.message=="string"&&!Array.isArray(r)}const releaseApiProxy=releaseProxy;async function consumeAPISync(r){setupTransferHandlers();const e=await NodeSABSyncReceiveMessageTransport.create();return wrapSync(r,e)}function consumeAPI(r,e=void 0){setupTransferHandlers();let t;if(typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u")if("postMessage"in r)t=nodeEndpoint(r);else if("send"in r&&"addListener"in r)t=nodeProcessEndpoint(r);else throw new Error("consumeAPI: remote does not look like a Worker, MessagePort, or Process");else t=r instanceof Worker?r:windowEndpoint(r,e);const n=wrap(t),i=proxyClone(n);return new Proxy(i,{get:(o,a)=>a==="isConnected"?async()=>{for(;;)try{await runWithTimeout(n.isConnected(),200);break}catch{}}:n[a]})}async function runWithTimeout(r,e){return new Promise((t,s)=>{setTimeout(s,e),r.then(t)})}function exposeAPI(r,e,t){const{setReady:s,setFailed:n,exposedApi:i}=prepareForExpose(r,e);let o;if(t)if("addEventListener"in t)o=t;else if("postMessage"in t)o=nodeEndpoint(t);else if("send"in t&&"addListener"in t)o=nodeProcessEndpoint(t);else throw new Error("exposeAPI: targetWorker does not look like a Worker, MessagePort, or Process");else o=typeof window<"u"?windowEndpoint(self.parent):void 0;return expose(i,o),[s,n,i]}async function exposeSyncAPI(r,e){const{setReady:t,setFailed:s,exposedApi:n}=prepareForExpose(r),i=await NodeSABSyncReceiveMessageTransport.create(),o=nodeEndpoint(e);return exposeSync(n,o,i),[t,s,n]}function prepareForExpose(r,e){setupTransferHandlers();const t=Promise.resolve();let s,n;const i=new Promise((c,l)=>{s=c,n=l}),o=proxyClone(r),a=new Proxy(o,{get:(c,l)=>l==="isConnected"?()=>t:l==="isReady"?()=>i:l in c?c[l]:e==null?void 0:e[l]});return{setReady:s,setFailed:n,exposedApi:a}}let isTransferHandlersSetup=!1;function setupTransferHandlers(){if(isTransferHandlersSetup)return;isTransferHandlersSetup=!0,transferHandlers.set("EVENT",{canHandle:t=>t instanceof CustomEvent,serialize:t=>[{detail:t.detail},[]],deserialize:t=>t}),transferHandlers.set("FUNCTION",{canHandle:t=>typeof t=="function",serialize(t){const{port1:s,port2:n}=new MessageChannel;return expose(t,s),[n,[n]]},deserialize(t){return t.start(),wrap(t)}}),transferHandlers.set("MESSAGE_PORT",{canHandle:t=>t instanceof MessagePort,serialize(t){return[t,[t]]},deserialize(t){return t}}),transferHandlers.set("PHPResponse",{canHandle:t=>typeof t=="object"&&t!==null&&"headers"in t&&"bytes"in t&&"errors"in t&&"exitCode"in t&&"httpStatusCode"in t,serialize(t){const s=t.toRawData(),n=[];return s.bytes.buffer.byteLength>0&&n.push(s.bytes.buffer),[s,n]},deserialize(t){return PHPResponse.fromRawData(t)}});const r=transferHandlers.get("throw"),e=r==null?void 0:r.serialize;r.serialize=({value:t})=>{const s=e({value:t});return t.response&&(s[0].value.response=t.response),t.source&&(s[0].value.source=t.source),s},transferHandlers.set("StreamedPHPResponse",{canHandle:t=>t instanceof StreamedPHPResponse,serialize(t){const s=supportsTransferableStreams(),n=promiseToPort(t.exitCode),i=t.getHeadersStream();if(s)return[{__type:"StreamedPHPResponse",headers:i,stdout:t.stdout,stderr:t.stderr,exitCodePort:n},[i,t.stdout,t.stderr,n]];const o=streamToPort(i),a=streamToPort(t.stdout),c=streamToPort(t.stderr);return[{__type:"StreamedPHPResponse",headersPort:o,stdoutPort:a,stderrPort:c,exitCodePort:n},[o,a,c,n]]},deserialize(t){if(t.headers&&t.stdout&&t.stderr){const a=portToPromise(t.exitCodePort);return new StreamedPHPResponse(t.headers,t.stdout,t.stderr,a)}const s=portToStream(t.headersPort),n=portToStream(t.stdoutPort),i=portToStream(t.stderrPort),o=portToPromise(t.exitCodePort);return new StreamedPHPResponse(s,n,i,o)}})}function supportsTransferableStreams(){try{if(typeof ReadableStream>"u")return!1;const{port1:r}=new MessageChannel,e=new ReadableStream;r.postMessage(e);try{r.close()}catch{}return!0}catch{return!1}}function streamToPort(r){const{port1:e,port2:t}=new MessageChannel;return(async()=>{const s=r.getReader();try{for(;;){const{done:n,value:i}=await s.read();if(n){try{e.postMessage({t:"close"})}catch{}try{e.close()}catch{}break}if(i){const o=i.byteOffset===0&&i.byteLength===i.buffer.byteLength?i:i.slice(),a=o.buffer;try{e.postMessage({t:"chunk",b:a},[a])}catch{e.postMessage({t:"chunk",b:o.buffer.slice(0)})}}}}catch(n){try{e.postMessage({t:"error",m:(n==null?void 0:n.message)||String(n)})}catch{}}finally{try{e.close()}catch{}}})(),t}function portToStream(r){return new ReadableStream({start(e){const t=n=>{const i=n.data;if(i)switch(i.t){case"chunk":e.enqueue(new Uint8Array(i.b));break;case"close":e.close(),s();break;case"error":e.error(new Error(i.m||"Stream error")),s();break}},s=()=>{var n;try{(n=r.removeEventListener)==null||n.call(r,"message",t)}catch{}try{r.onmessage=null}catch{}try{r.close()}catch{}};r.addEventListener?r.addEventListener("message",t):r.on?r.on("message",n=>t({data:n})):r.onmessage=t,typeof r.start=="function"&&r.start()},cancel(){try{r.close()}catch{}}})}function promiseToPort(r){const{port1:e,port2:t}=new MessageChannel;return r.then(s=>{try{e.postMessage({t:"resolve",v:s})}catch{}}).catch(s=>{try{e.postMessage({t:"reject",m:(s==null?void 0:s.message)||String(s)})}catch{}}).finally(()=>{try{e.close()}catch{}}),t}function portToPromise(r){return new Promise((e,t)=>{const s=i=>{const o=i.data;o&&(o.t==="resolve"?(n(),e(o.v)):o.t==="reject"&&(n(),t(new Error(o.m||""))))},n=()=>{var i;try{(i=r.removeEventListener)==null||i.call(r,"message",s)}catch{}try{r.onmessage=null}catch{}try{r.close()}catch{}};r.addEventListener?r.addEventListener("message",s):r.on?r.on("message",i=>s({data:i})):r.onmessage=s,typeof r.start=="function"&&r.start()})}const throwTransferHandler=transferHandlers.get("throw"),throwTransferHandlerCustom={canHandle:throwTransferHandler.canHandle,serialize:({value:r})=>{let e;return r instanceof Error?(e={isError:!0,value:serializeError(r)},e.value.originalErrorClassName=r.constructor.name):e={isError:!1,value:r},[e,[]]},deserialize:r=>{if(r.isError){const e=deserializeError(r.value),t=new Error("Comlink method call failed");let s=e;for(;s.cause;)s=s.cause;throw s.cause=t,e}throw r.value}};transferHandlers.set("throw",throwTransferHandlerCustom);function proxyClone(r){return new Proxy(r,{get(e,t){switch(typeof e[t]){case"function":return(...s)=>e[t](...s);case"object":return e[t]===null?e[t]:proxyClone(e[t]);case"undefined":case"number":case"string":return e[t];default:return proxy(e[t])}}})}const MAX_ADDRESSABLE_FILE_OFFSET=BigInt(Number.MAX_SAFE_INTEGER);class IntervalNode{constructor(e){this.left=null,this.right=null,this.range=e,this.max=e.end}}class FileLockIntervalTree{constructor(){this.root=null}isEmpty(){return this.root===null}insert(e){this.root=this.insertNode(this.root,e)}findOverlapping(e){const t=[];return this.findOverlappingRanges(this.root,e,t),t}remove(e){this.root=this.removeNode(this.root,e)}findLocksForProcess(e){const t=[];return this.findLocksForProcessInNode(this.root,e,t),t}findStrictestExistingLockType(){let e="unlocked";const t=s=>{if(s){if(s.range.type==="exclusive"){e="exclusive";return}s.range.type==="shared"&&(e="shared"),t(s.left),t(s.right)}};return t(this.root),e}insertNode(e,t){return e?(t.start<e.range.start?e.left=this.insertNode(e.left,t):e.right=this.insertNode(e.right,t),e.max=this.bigintMax(e.max,t.end),e):new IntervalNode(t)}bigintMax(...e){return e.reduce((t,s)=>s>t?s:t,e[0])}findOverlappingRanges(e,t,s){e&&(this.doRangesOverlap(e.range,t)&&s.push(e.range),e.left&&e.left.max>=t.start&&this.findOverlappingRanges(e.left,t,s),e.right&&e.range.start<=t.end&&this.findOverlappingRanges(e.right,t,s))}doRangesOverlap(e,t){return e.start<t.end&&t.start<e.end}removeNode(e,t){if(!e)return null;if(this.areRangesEqual(e.range,t)){if(!e.left)return e.right;if(!e.right)return e.left;const s=this.findMin(e.right);e.range=s.range,e.right=this.removeNode(e.right,s.range)}else t.start<e.range.start?e.left=this.removeNode(e.left,t):e.right=this.removeNode(e.right,t);return e.max=e.range.end,e.left&&(e.max=this.bigintMax(e.max,e.left.max)),e.right&&(e.max=this.bigintMax(e.max,e.right.max)),e}findMin(e){let t=e;for(;t.left;)t=t.left;return t}areRangesEqual(e,t){return e.start===t.start&&e.end===t.end&&e.pid===t.pid&&e.fd===t.fd}findLocksForProcessInNode(e,t,s){e&&(e.range.pid===t&&s.push(e.range),this.findLocksForProcessInNode(e.left,t,s),this.findLocksForProcessInNode(e.right,t,s))}}class FileLockManagerInMemory{constructor(){this.locks=new Map}lockWholeFile(e,t){if(this.locks.get(e)===void 0){if(t.type==="unlock")return!0;this.locks.set(e,new FileLock)}const n=this.locks.get(e).lockWholeFile(t);return this.forgetPathIfUnlocked(e),n}lockFileByteRange(e,t){if(!this.locks.has(e)){if(t.type==="unlocked")return!0;this.locks.set(e,new FileLock)}return this.locks.get(e).lockFileByteRange(t)}findFirstConflictingByteRangeLock(e,t){const s=this.locks.get(e);if(s!==void 0)return s.findFirstConflictingByteRangeLock(t)}releaseLocksForProcess(e){for(const[t,s]of this.locks.entries())s.releaseLocksForProcess(e),this.forgetPathIfUnlocked(t)}releaseLocksOnFdClose(e,t,s){const n=this.locks.get(s);n&&(n.releaseLocksOnFdClose(e,t),this.forgetPathIfUnlocked(s))}forgetPathIfUnlocked(e){const t=this.locks.get(e);t&&t.isUnlocked()&&this.locks.delete(e)}}class FileLock{constructor(){this.rangeLocks=new FileLockIntervalTree,this.wholeFileLock={type:"unlocked"}}lockWholeFile(e){if(e.type==="unlock")return this.wholeFileLock.type==="unlocked"||(this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid===e.pid&&this.wholeFileLock.fd===e.fd?this.wholeFileLock={type:"unlocked"}:this.wholeFileLock.type==="shared"&&this.wholeFileLock.pidFds.has(e.pid)&&this.wholeFileLock.pidFds.get(e.pid).has(e.fd)&&(this.wholeFileLock.pidFds.get(e.pid).delete(e.fd),this.wholeFileLock.pidFds.get(e.pid).size===0&&this.wholeFileLock.pidFds.delete(e.pid),this.wholeFileLock.pidFds.size===0&&(this.wholeFileLock={type:"unlocked"}))),!0;if(this.isThereAConflictWithRequestedWholeFileLock(e))return!1;if(e.type==="exclusive")return this.wholeFileLock={type:"exclusive",pid:e.pid,fd:e.fd},!0;if(e.type==="shared"){this.wholeFileLock.type!=="shared"&&(this.wholeFileLock={type:"shared",pidFds:new Map});const t=this.wholeFileLock;return t.pidFds.has(e.pid)||t.pidFds.set(e.pid,new Set),t.pidFds.get(e.pid).add(e.fd),!0}throw new Error(`Unexpected wholeFileLock() op: '${e.type}'`)}lockFileByteRange(e){if(e.start===e.end&&(e={...e,end:MAX_ADDRESSABLE_FILE_OFFSET}),e.type==="unlocked"){const o=this.rangeLocks.findOverlapping(e).filter(a=>a.pid===e.pid);for(const a of o)this.rangeLocks.remove(a),a.start<e.start&&this.rangeLocks.insert({...a,end:e.start}),a.end>e.end&&this.rangeLocks.insert({...a,start:e.end});return!0}if(this.isThereAConflictWithRequestedRangeLock(e))return!1;const t=this.rangeLocks.findOverlapping(e).filter(o=>o.pid===e.pid);let s=e.start,n=e.end;for(const o of t)this.rangeLocks.remove(o),o.start<s&&(s=o.start),o.end>n&&(n=o.end);const i={...e,start:s,end:n};return this.rangeLocks.insert(i),!0}findFirstConflictingByteRangeLock(e){e.start===e.end&&(e={...e,end:MAX_ADDRESSABLE_FILE_OFFSET});const s=this.rangeLocks.findOverlapping(e).find(i=>i.pid!==e.pid&&(e.type==="exclusive"||i.type==="exclusive"));if(s)return s;if(this.wholeFileLock.type==="unlocked")return;if(this.wholeFileLock.type==="exclusive"||e.type==="exclusive")return{type:this.wholeFileLock.type,start:0n,end:0n,pid:-1}}releaseLocksForProcess(e){for(const t of this.rangeLocks.findLocksForProcess(e))this.lockFileByteRange({...t,type:"unlocked"});if(this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid===e)this.lockWholeFile({pid:e,fd:this.wholeFileLock.fd,type:"unlock"});else if(this.wholeFileLock.type==="shared"&&this.wholeFileLock.pidFds.has(e))for(const t of this.wholeFileLock.pidFds.get(e))this.lockWholeFile({pid:e,fd:t,type:"unlock"})}releaseLocksOnFdClose(e,t){for(const s of this.rangeLocks.findLocksForProcess(e))this.lockFileByteRange({...s,type:"unlocked"});this.lockWholeFile({pid:e,fd:t,type:"unlock"})}isUnlocked(){return this.wholeFileLock.type==="unlocked"&&this.rangeLocks.isEmpty()}isThereAConflictWithRequestedRangeLock(e){return this.findFirstConflictingByteRangeLock(e)!==void 0}isThereAConflictWithRequestedWholeFileLock(e){return e.type==="exclusive"?!!(this.wholeFileLock.type==="exclusive"&&(this.wholeFileLock.fd!==e.fd||this.wholeFileLock.pid!==e.pid)||this.wholeFileLock.type==="shared"&&Array.from(this.wholeFileLock.pidFds).some(([s])=>s!==e.pid)||this.rangeLocks.findOverlapping({start:0n,end:MAX_ADDRESSABLE_FILE_OFFSET}).length>0):e.type==="shared"?this.wholeFileLock.type==="exclusive"&&this.wholeFileLock.pid!==e.pid||this.rangeLocks.findOverlapping({start:0n,end:MAX_ADDRESSABLE_FILE_OFFSET}).filter(n=>n.type==="exclusive").length>0:!1}}class FileLockManagerComposite{constructor({nativeLockManager:e,wasmLockManager:t}){this.nativeLockManager=e,this.wasmLockManager=t}lockWholeFile(e,t){if(t.type!=="unlock"){let s,n;try{if(s=this.nativeLockManager.lockWholeFile(e,t),!s)return!1;n=this.wasmLockManager.lockWholeFile(e,t)}catch(i){logger.logger.error("Unexpected error in lockWholeFile()",i)}finally{s&&!n&&this.nativeLockManager.lockWholeFile(e,{...t,type:"unlock"})}return!!s&&!!n}try{this.wasmLockManager.lockWholeFile(e,t)}catch(s){logger.logger.error("Unexpected error unlocking whole file with in-memory lock manager",s)}try{this.nativeLockManager.lockWholeFile(e,t)}catch(s){logger.logger.error("Unexpected error unlocking whole file with native lock manager",s)}return!0}lockFileByteRange(e,t,s){if(t.type!=="unlocked"){let n,i;try{if(n=this.nativeLockManager.lockFileByteRange(e,t,s),!n)return!1;i=this.wasmLockManager.lockFileByteRange(e,t,s)}catch(o){logger.logger.error("Unexpected error in lockFileByteRange()",o)}finally{n&&!i&&this.nativeLockManager.lockFileByteRange(e,{...t,type:"unlocked"},!1)}return!!n&&!!i}try{this.wasmLockManager.lockFileByteRange(e,t,s)}catch(n){logger.logger.error("Unexpected error unlocking byte range with in-memory lock manager",n)}try{this.nativeLockManager.lockFileByteRange(e,t,s)}catch(n){logger.logger.error("Unexpected error unlocking byte range with native lock manager",n)}return!0}findFirstConflictingByteRangeLock(e,t){try{const s=this.nativeLockManager.findFirstConflictingByteRangeLock(e,t);return s||this.wasmLockManager.findFirstConflictingByteRangeLock(e,t)}catch(s){logger.logger.error("Unexpected error in findFirstConflictingByteRangeLock()",s);return}}releaseLocksForProcess(e){try{this.wasmLockManager.releaseLocksForProcess(e)}catch(t){logger.logger.error("Unexpected error in wasmLockManager.releaseLocksForProcess()",t)}try{this.nativeLockManager.releaseLocksForProcess(e)}catch(t){logger.logger.error("Unexpected error in nativeLockManager.releaseLocksForProcess()",t)}}releaseLocksOnFdClose(e,t,s){try{this.wasmLockManager.releaseLocksOnFdClose(e,t,s)}catch(n){logger.logger.error("Unexpected error in wasmLockManager.releaseLocksOnFdClose()",n)}try{this.nativeLockManager.releaseLocksOnFdClose(e,t,s)}catch(n){logger.logger.error("Unexpected error in nativeLockManager.releaseLocksOnFdClose()",n)}}}function createObjectPoolProxy(r){if(r.length===0)throw new Error("At least one instance is required");const e=[...r],t=[];function s(){const o=e.shift();return o!==void 0?Promise.resolve(o):new Promise(a=>{t.push(a)})}function n(o){const a=t.shift();a?a(o):e.push(o)}function i(o){return s().then(a=>{let c;try{c=o(a)}catch(l){throw n(a),l}return c!=null&&typeof c.then=="function"?c.then(l=>(n(a),l),l=>{throw n(a),l}):(n(a),c)})}return new Proxy({},{get(o,a){if(a in o)return o[a];if(a!=="then")return new Proxy(function(){},{apply(c,l,p){return i(d=>d[a](...p))},get(c,l){if(l==="then")return(p,d)=>i(f=>f[a]).then(p,d)}})}})}exports.DEFAULT_BASE_URL=DEFAULT_BASE_URL;exports.FSHelpers=FSHelpers;exports.FileLock=FileLock;exports.FileLockIntervalTree=FileLockIntervalTree;exports.FileLockManagerComposite=FileLockManagerComposite;exports.FileLockManagerInMemory=FileLockManagerInMemory;exports.HttpCookieStore=HttpCookieStore;exports.LatestSupportedPHPVersion=LatestSupportedPHPVersion;exports.MAX_ADDRESSABLE_FILE_OFFSET=MAX_ADDRESSABLE_FILE_OFFSET;exports.PHP=PHP;exports.PHPExecutionFailureError=PHPExecutionFailureError;exports.PHPProcessManager=PHPProcessManager;exports.PHPRequestHandler=PHPRequestHandler;exports.PHPResponse=PHPResponse;exports.PHPWorker=PHPWorker;exports.SinglePHPInstanceManager=SinglePHPInstanceManager;exports.StreamedPHPResponse=StreamedPHPResponse;exports.SupportedPHPVersions=SupportedPHPVersions;exports.SupportedPHPVersionsList=SupportedPHPVersionsList;exports.UnhandledRejectionsTarget=UnhandledRejectionsTarget;exports.__private__dont__use=__private__dont__use;exports.applyRewriteRules=applyRewriteRules;exports.consumeAPI=consumeAPI;exports.consumeAPISync=consumeAPISync;exports.createObjectPoolProxy=createObjectPoolProxy;exports.ensurePathPrefix=ensurePathPrefix;exports.exposeAPI=exposeAPI;exports.exposeSyncAPI=exposeSyncAPI;exports.getPhpIniEntries=getPhpIniEntries;exports.inferMimeType=inferMimeType;exports.isExitCode=isExitCode;exports.isPathToSharedFS=isPathToSharedFS;exports.iterateFiles=iteratePhpFiles;exports.loadPHPRuntime=loadPHPRuntime;exports.popLoadedRuntime=popLoadedRuntime;exports.prettyPrintFullStackTrace=prettyPrintFullStackTrace;exports.printDebugDetails=printDebugDetails;exports.printResponseDebugDetails=printResponseDebugDetails;exports.proxyFileSystem=proxyFileSystem;exports.releaseApiProxy=releaseApiProxy;exports.removePathPrefix=removePathPrefix;exports.rotatePHPRuntime=rotatePHPRuntime;exports.sandboxedSpawnHandlerFactory=sandboxedSpawnHandlerFactory;exports.setPhpIniEntries=setPhpIniEntries;exports.toRelativeUrl=toRelativeUrl;exports.withPHPIniValues=withPHPIniValues;exports.writeFiles=writeFiles;exports.writeFilesStreamToPhp=writeFilesStreamToPhp;
102
102
  //# sourceMappingURL=index.cjs.map