@php-wasm/universal 3.1.18 → 3.1.20
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 +1 -1
- package/index.cjs.map +1 -1
- package/index.js +0 -1
- package/index.js.map +1 -1
- package/package.json +8 -8
package/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var le=Object.create;var J=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var pe=Object.getPrototypeOf,he=Object.prototype.hasOwnProperty;var Y=r=>{throw TypeError(r)};var fe=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of de(e))!he.call(r,n)&&n!==t&&J(r,n,{get:()=>e[n],enumerable:!(s=ue(e,n))||s.enumerable});return r};var me=(r,e,t)=>(t=r!=null?le(pe(r)):{},fe(e||!r||!r.__esModule?J(t,"default",{value:r,enumerable:!0}):t,r));var W=(r,e,t)=>e.has(r)||Y("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)?Y("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),g=(r,e,t,s)=>(W(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),m=(r,e,t)=>(W(r,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("@php-wasm/node-polyfills");const logger=require("@php-wasm/logger"),util=require("@php-wasm/util"),ini=require("ini"),streamCompression=require("@php-wasm/stream-compression");class ErrnoError extends Error{constructor(e,t,s){super(t,s),this.name="ErrnoError",this.errno=e}}const FileErrorCodes={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function getEmscriptenFsError(r){const e=typeof r=="object"?r==null?void 0:r.errno:null;if(e in FileErrorCodes)return FileErrorCodes[e]}function rethrowFileSystemError(r=""){return function(t){return function(...s){try{return t.apply(this,s)}catch(n){const i=typeof n=="object"?n==null?void 0:n.errno:null;if(i in FileErrorCodes){const o=FileErrorCodes[i],a=typeof s[1]=="string"?s[1]:null,c=a!==null?r.replaceAll("{path}",a):r;throw new ErrnoError(i,`${c}: ${o}`,{cause:n})}throw n}}}}class FSHelpers{static readFileAsText(e,t){return new TextDecoder().decode(FSHelpers.readFileAsBuffer(e,t))}static readFileAsBuffer(e,t){return e.readFile(t)}static writeFile(e,t,s){e.writeFile(t,s)}static unlink(e,t){e.unlink(t)}static mv(e,t,s){try{const n=e.lookupPath(t).node.mount,i=FSHelpers.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(util.dirname(s)).node.mount;n.mountpoint!==i.mountpoint?(FSHelpers.copyRecursive(e,t,s),FSHelpers.isDir(e,t)?FSHelpers.rmdir(e,t,{recursive:!0}):e.unlink(t)):e.rename(t,s)}catch(n){const i=getEmscriptenFsError(n);throw i?new Error(`Could not move ${t} to ${s}: ${i}`,{cause:n}):n}}static rmdir(e,t,s={recursive:!0}){const n=e.lookupPath(t,{follow:!1});if((n==null?void 0:n.node.mount.mountpoint)===t)throw new ErrnoError(10);s!=null&&s.recursive&&FSHelpers.listFiles(e,t).forEach(i=>{const o=`${t}/${i}`;FSHelpers.isDir(e,o)?FSHelpers.rmdir(e,o,s):FSHelpers.unlink(e,o)}),e.getPath(e.lookupPath(t).node)===e.cwd()&&e.chdir(util.joinPaths(e.cwd(),"..")),e.rmdir(t)}static listFiles(e,t,s={prependPath:!1}){if(!FSHelpers.fileExists(e,t))return[];try{const n=e.readdir(t).filter(i=>i!=="."&&i!=="..");if(s.prependPath){const i=t.replace(/\/$/,"");return n.map(o=>`${i}/${o}`)}return n}catch(n){return logger.logger.error(n,{path:t}),[]}}static isDir(e,t){return FSHelpers.fileExists(e,t)?e.isDir(e.lookupPath(t,{follow:!0}).node.mode):!1}static isFile(e,t){return FSHelpers.fileExists(e,t)?e.isFile(e.lookupPath(t,{follow:!0}).node.mode):!1}static symlink(e,t,s){return e.symlink(t,s)}static isSymlink(e,t){return FSHelpers.fileExists(e,t)?e.isLink(e.lookupPath(t).node.mode):!1}static readlink(e,t){return e.readlink(t)}static realpath(e,t){return e.lookupPath(t,{follow:!0}).path}static fileExists(e,t){try{return e.lookupPath(t),!0}catch{return!1}}static mkdir(e,t){e.mkdirTree(t)}static copyRecursive(e,t,s){try{const n=e.lookupPath(t).node;if(e.isDir(n.mode)){if(t===s||s.startsWith(`${t}/`))throw new ErrnoError(28);e.mkdirTree(s);const i=e.readdir(t).filter(o=>o!=="."&&o!=="..");for(const o of i)FSHelpers.copyRecursive(e,util.joinPaths(t,o),util.joinPaths(s,o))}else e.isLink(n.mode)?e.symlink(e.readlink(t),s):e.writeFile(s,e.readFile(t))}catch(n){const i=getEmscriptenFsError(n);throw i?new Error(`Could not copy ${t} to ${s}: ${i}`,{cause:n}):n}}}FSHelpers.readFileAsText=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsText);FSHelpers.readFileAsBuffer=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsBuffer);FSHelpers.writeFile=rethrowFileSystemError('Could not write to "{path}"')(FSHelpers.writeFile);FSHelpers.unlink=rethrowFileSystemError('Could not unlink "{path}"')(FSHelpers.unlink);FSHelpers.rmdir=rethrowFileSystemError('Could not remove directory "{path}"')(FSHelpers.rmdir);FSHelpers.listFiles=rethrowFileSystemError('Could not list files in "{path}"')(FSHelpers.listFiles);FSHelpers.isDir=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isDir);FSHelpers.isFile=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isFile);FSHelpers.realpath=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.realpath);FSHelpers.fileExists=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.fileExists);FSHelpers.mkdir=rethrowFileSystemError('Could not create directory "{path}"')(FSHelpers.mkdir);const _private=new WeakMap;var S;class PHPWorker{constructor(e,t){y(this,S);this.absoluteUrl="",this.documentRoot="",this.chroot=null,g(this,S,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,S).has(e)||u(this,S).set(e,new Set),u(this,S).get(e).add(t)}removeEventListener(e,t){var s;(s=u(this,S).get(e))==null||s.delete(t)}dispatchEvent(e){const t=u(this,S).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]())}}S=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 N,O;const j=class j{constructor(e,t,s,n){y(this,N);y(this,O);this.cachedParsedHeaders=null,this.cachedStdoutBytes=null,this.cachedStderrText=null;const[i,o]=e.tee();g(this,N,i),g(this,O,o),this.stdout=t,this.stderr=s,this.exitCode=n}static fromPHPResponse(e){const t=new ReadableStream({start(a){a.enqueue(e.bytes),a.close()}}),s=[];for(const[a,c]of Object.entries(e.headers))for(const l of c)s.push(`${a}: ${l}`);const n=JSON.stringify({status:e.httpStatusCode,headers:s}),i=new ReadableStream({start(a){a.enqueue(new TextEncoder().encode(n)),a.close()}}),o=new ReadableStream({start(a){e.errors.length>0&&a.enqueue(new TextEncoder().encode(e.errors)),a.close()}});return new j(i,t,o,Promise.resolve(e.exitCode))}static forHttpCode(e,t=""){return j.fromPHPResponse(PHPResponse.forHttpCode(e,t))}getHeadersStream(){return u(this,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.cachedParsedHeaders||(this.cachedParsedHeaders=parseHeadersStream(u(this,O))),await this.cachedParsedHeaders}};N=new WeakMap,O=new WeakMap;let StreamedPHPResponse=j;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 le=Object.create;var J=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var pe=Object.getPrototypeOf,he=Object.prototype.hasOwnProperty;var Y=r=>{throw TypeError(r)};var fe=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of de(e))!he.call(r,n)&&n!==t&&J(r,n,{get:()=>e[n],enumerable:!(s=ue(e,n))||s.enumerable});return r};var me=(r,e,t)=>(t=r!=null?le(pe(r)):{},fe(e||!r||!r.__esModule?J(t,"default",{value:r,enumerable:!0}):t,r));var W=(r,e,t)=>e.has(r)||Y("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)?Y("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"});const logger=require("@php-wasm/logger"),util=require("@php-wasm/util"),ini=require("ini"),streamCompression=require("@php-wasm/stream-compression");class ErrnoError extends Error{constructor(e,t,s){super(t,s),this.name="ErrnoError",this.errno=e}}const FileErrorCodes={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function getEmscriptenFsError(r){const e=typeof r=="object"?r==null?void 0:r.errno:null;if(e in FileErrorCodes)return FileErrorCodes[e]}function rethrowFileSystemError(r=""){return function(t){return function(...s){try{return t.apply(this,s)}catch(n){const i=typeof n=="object"?n==null?void 0:n.errno:null;if(i in FileErrorCodes){const o=FileErrorCodes[i],a=typeof s[1]=="string"?s[1]:null,c=a!==null?r.replaceAll("{path}",a):r;throw new ErrnoError(i,`${c}: ${o}`,{cause:n})}throw n}}}}class FSHelpers{static readFileAsText(e,t){return new TextDecoder().decode(FSHelpers.readFileAsBuffer(e,t))}static readFileAsBuffer(e,t){return e.readFile(t)}static writeFile(e,t,s){e.writeFile(t,s)}static unlink(e,t){e.unlink(t)}static mv(e,t,s){try{const n=e.lookupPath(t).node.mount,i=FSHelpers.fileExists(e,s)?e.lookupPath(s).node.mount:e.lookupPath(util.dirname(s)).node.mount;n.mountpoint!==i.mountpoint?(FSHelpers.copyRecursive(e,t,s),FSHelpers.isDir(e,t)?FSHelpers.rmdir(e,t,{recursive:!0}):e.unlink(t)):e.rename(t,s)}catch(n){const i=getEmscriptenFsError(n);throw i?new Error(`Could not move ${t} to ${s}: ${i}`,{cause:n}):n}}static rmdir(e,t,s={recursive:!0}){const n=e.lookupPath(t,{follow:!1});if((n==null?void 0:n.node.mount.mountpoint)===t)throw new ErrnoError(10);s!=null&&s.recursive&&FSHelpers.listFiles(e,t).forEach(i=>{const o=`${t}/${i}`;FSHelpers.isDir(e,o)?FSHelpers.rmdir(e,o,s):FSHelpers.unlink(e,o)}),e.getPath(e.lookupPath(t).node)===e.cwd()&&e.chdir(util.joinPaths(e.cwd(),"..")),e.rmdir(t)}static listFiles(e,t,s={prependPath:!1}){if(!FSHelpers.fileExists(e,t))return[];try{const n=e.readdir(t).filter(i=>i!=="."&&i!=="..");if(s.prependPath){const i=t.replace(/\/$/,"");return n.map(o=>`${i}/${o}`)}return n}catch(n){return logger.logger.error(n,{path:t}),[]}}static isDir(e,t){return FSHelpers.fileExists(e,t)?e.isDir(e.lookupPath(t,{follow:!0}).node.mode):!1}static isFile(e,t){return FSHelpers.fileExists(e,t)?e.isFile(e.lookupPath(t,{follow:!0}).node.mode):!1}static symlink(e,t,s){return e.symlink(t,s)}static isSymlink(e,t){return FSHelpers.fileExists(e,t)?e.isLink(e.lookupPath(t).node.mode):!1}static readlink(e,t){return e.readlink(t)}static realpath(e,t){return e.lookupPath(t,{follow:!0}).path}static fileExists(e,t){try{return e.lookupPath(t),!0}catch{return!1}}static mkdir(e,t){e.mkdirTree(t)}static copyRecursive(e,t,s){try{const n=e.lookupPath(t).node;if(e.isDir(n.mode)){if(t===s||s.startsWith(`${t}/`))throw new ErrnoError(28);e.mkdirTree(s);const i=e.readdir(t).filter(o=>o!=="."&&o!=="..");for(const o of i)FSHelpers.copyRecursive(e,util.joinPaths(t,o),util.joinPaths(s,o))}else e.isLink(n.mode)?e.symlink(e.readlink(t),s):e.writeFile(s,e.readFile(t))}catch(n){const i=getEmscriptenFsError(n);throw i?new Error(`Could not copy ${t} to ${s}: ${i}`,{cause:n}):n}}}FSHelpers.readFileAsText=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsText);FSHelpers.readFileAsBuffer=rethrowFileSystemError('Could not read "{path}"')(FSHelpers.readFileAsBuffer);FSHelpers.writeFile=rethrowFileSystemError('Could not write to "{path}"')(FSHelpers.writeFile);FSHelpers.unlink=rethrowFileSystemError('Could not unlink "{path}"')(FSHelpers.unlink);FSHelpers.rmdir=rethrowFileSystemError('Could not remove directory "{path}"')(FSHelpers.rmdir);FSHelpers.listFiles=rethrowFileSystemError('Could not list files in "{path}"')(FSHelpers.listFiles);FSHelpers.isDir=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isDir);FSHelpers.isFile=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.isFile);FSHelpers.realpath=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.realpath);FSHelpers.fileExists=rethrowFileSystemError('Could not stat "{path}"')(FSHelpers.fileExists);FSHelpers.mkdir=rethrowFileSystemError('Could not create directory "{path}"')(FSHelpers.mkdir);const _private=new WeakMap;var S;class PHPWorker{constructor(e,t){y(this,S);this.absoluteUrl="",this.documentRoot="",this.chroot=null,g(this,S,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,S).has(e)||u(this,S).set(e,new Set),u(this,S).get(e).add(t)}removeEventListener(e,t){var s;(s=u(this,S).get(e))==null||s.delete(t)}dispatchEvent(e){const t=u(this,S).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]())}}S=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 N,O;const j=class j{constructor(e,t,s,n){y(this,N);y(this,O);this.cachedParsedHeaders=null,this.cachedStdoutBytes=null,this.cachedStderrText=null;const[i,o]=e.tee();g(this,N,i),g(this,O,o),this.stdout=t,this.stderr=s,this.exitCode=n}static fromPHPResponse(e){const t=new ReadableStream({start(a){a.enqueue(e.bytes),a.close()}}),s=[];for(const[a,c]of Object.entries(e.headers))for(const l of c)s.push(`${a}: ${l}`);const n=JSON.stringify({status:e.httpStatusCode,headers:s}),i=new ReadableStream({start(a){a.enqueue(new TextEncoder().encode(n)),a.close()}}),o=new ReadableStream({start(a){e.errors.length>0&&a.enqueue(new TextEncoder().encode(e.errors)),a.close()}});return new j(i,t,o,Promise.resolve(e.exitCode))}static forHttpCode(e,t=""){return j.fromPHPResponse(PHPResponse.forHttpCode(e,t))}getHeadersStream(){return u(this,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.cachedParsedHeaders||(this.cachedParsedHeaders=parseHeadersStream(u(this,O))),await this.cachedParsedHeaders}};N=new WeakMap,O=new WeakMap;let StreamedPHPResponse=j;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 } }).
|