@php-wasm/universal 0.3.1 → 0.4.3

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,10 +1,10 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const R=Symbol("error"),S=Symbol("message");class E extends Event{constructor(e,t={}){super(e),this[R]=t.error===void 0?null:t.error,this[S]=t.message===void 0?"":t.message}get error(){return this[R]}get message(){return this[S]}}Object.defineProperty(E.prototype,"error",{enumerable:!0});Object.defineProperty(E.prototype,"message",{enumerable:!0});const D=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:E;function A(s){return s instanceof Error?"exitCode"in s&&s?.exitCode===0||s?.name==="ExitStatus"&&"status"in s&&s.status===0:!1}class U extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,t){++this.listenersCount,super.addEventListener(e,t)}removeEventListener(e,t){--this.listenersCount,super.removeEventListener(e,t)}hasListeners(){return this.listenersCount>0}}function W(s){s.asm={...s.asm};const e=new U;for(const t in s.asm)if(typeof s.asm[t]=="function"){const r=s.asm[t];s.asm[t]=function(...n){try{return r(...n)}catch(o){if(!(o instanceof Error))throw o;const i=z(o,s.lastAsyncifyStackSource?.stack);if(s.lastAsyncifyStackSource&&(o.cause=s.lastAsyncifyStackSource),e.hasListeners()){e.dispatchEvent(new D("error",{error:o,message:i}));return}throw A(o)||Y(i),o}}}return e}let P=[];function j(){return P}function z(s,e){if(s.message==="unreachable"){let t=G;e||(t+=`
1
+ "use strict";var se=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var i=(s,e,t)=>(se(s,e,"read from private field"),t?t.call(s):e.get(s)),c=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)},p=(s,e,t,r)=>(se(s,e,"write to private field"),r?r.call(s,t):e.set(s,t),t);var m=(s,e,t)=>(se(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const le=Symbol("error"),ce=Symbol("message");class oe extends Event{constructor(e,t={}){super(e),this[le]=t.error===void 0?null:t.error,this[ce]=t.message===void 0?"":t.message}get error(){return this[le]}get message(){return this[ce]}}Object.defineProperty(oe.prototype,"error",{enumerable:!0});Object.defineProperty(oe.prototype,"message",{enumerable:!0});const qe=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:oe;function ye(s){return s instanceof Error?"exitCode"in s&&(s==null?void 0:s.exitCode)===0||(s==null?void 0:s.name)==="ExitStatus"&&"status"in s&&s.status===0:!1}class ge extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,t){++this.listenersCount,super.addEventListener(e,t)}removeEventListener(e,t){--this.listenersCount,super.removeEventListener(e,t)}hasListeners(){return this.listenersCount>0}}function je(s){s.asm={...s.asm};const e=new ge;for(const t in s.asm)if(typeof s.asm[t]=="function"){const r=s.asm[t];s.asm[t]=function(...n){var o;try{return r(...n)}catch(a){if(!(a instanceof Error))throw a;const h=We(a,(o=s.lastAsyncifyStackSource)==null?void 0:o.stack);if(s.lastAsyncifyStackSource&&(a.cause=s.lastAsyncifyStackSource),e.hasListeners()){e.dispatchEvent(new qe("error",{error:a,message:h}));return}throw ye(a)||Ve(h),a}}}return e}let re=[];function De(){return re}function We(s,e){if(s.message==="unreachable"){let t=ze;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. PHPNode.load('8.1', { debug: true }).
5
5
 
6
- `),P=J(e||s.stack||"");for(const r of P)t+=` * ${r}
7
- `;return t}return s.message}const G=`
6
+ `),re=Je(e||s.stack||"");for(const r of re)t+=` * ${r}
7
+ `;return t}return s.message}const ze=`
8
8
  "unreachable" WASM instruction executed.
9
9
 
10
10
  The typical reason is a PHP function missing from the ASYNCIFY_ONLY
@@ -28,13 +28,21 @@ the Dockerfile, you'll need to trigger this error again with long stack
28
28
  traces enabled. In node.js, you can do it using the --stack-trace-limit=100
29
29
  CLI option:
30
30
 
31
- `,x="\x1B[41m",V="\x1B[1m",H="\x1B[0m",k="\x1B[K";let T=!1;function Y(s){if(!T){T=!0,console.log(`${x}
32
- ${k}
33
- ${V} WASM ERROR${H}${x}`);for(const e of s.split(`
34
- `))console.log(`${k} ${e} `);console.log(`${H}`)}}function J(s){try{const e=s.split(`
35
- `).slice(1).map(t=>{const r=t.trim().substring(3).split(" ");return{fn:r.length>=2?r[0]:"<unknown>",isWasm:t.includes("wasm://")}}).filter(({fn:t,isWasm:r})=>r&&!t.startsWith("dynCall_")&&!t.startsWith("invoke_")).map(({fn:t})=>t);return Array.from(new Set(e))}catch{return[]}}class y{constructor(e,t,r,n="",o=0){this.httpStatusCode=e,this.headers=t,this.bytes=r,this.exitCode=o,this.errors=n}static fromRawData(e){return new y(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}const v=["8.2","8.1","8.0","7.4","7.3","7.2","7.1","7.0","5.6"],K=v[0],Z=v,L=["iconv","mbstring","xml-bundle","gd"],Q={"kitchen-sink":L};class O{#e;#t;constructor(e,t={}){this.requestHandler=e,this.#e={},this.#t={handleRedirects:!1,maxRedirects:4,...t}}async request(e,t=0){const r=await this.requestHandler.request({...e,headers:{...e.headers,cookie:this.#r()}});if(r.headers["set-cookie"]&&this.#s(r.headers["set-cookie"]),this.#t.handleRedirects&&r.headers.location&&t<this.#t.maxRedirects){const n=new URL(r.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:n.toString(),method:"GET",headers:{}},t+1)}return r}pathToInternalUrl(e){return this.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.internalUrlToPath(e)}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}#s(e){for(const t of e)try{if(!t.includes("="))continue;const r=t.indexOf("="),n=t.substring(0,r),o=t.substring(r+1).split(";")[0];this.#e[n]=o}catch(r){console.error(r)}}#r(){const e=[];for(const t in this.#e)e.push(`${t}=${this.#e[t]}`);return e.join("; ")}}class X{constructor({concurrency:e}){this._running=0,this.concurrency=e,this.queue=[]}get running(){return this._running}async acquire(){for(;;)if(this._running>=this.concurrency)await new Promise(e=>this.queue.push(e));else{this._running++;let e=!1;return()=>{e||(e=!0,this._running--,this.queue.length>0&&this.queue.shift()())}}}async run(e){const t=await this.acquire();try{return await e()}finally{t()}}}const I="http://example.com";function w(s){return s.toString().substring(s.origin.length)}function b(s,e){return!e||!s.startsWith(e)?s:s.substring(e.length)}function N(s,e){return!e||s.startsWith(e)?s:e+s}class ${#e;#t;#s;#r;#o;#n;#i;#a;constructor(e,t={}){this.#a=new X({concurrency:1});const{documentRoot:r="/www/",absoluteUrl:n=typeof location=="object"?location?.href:""}=t;this.php=e,this.#e=r;const o=new URL(n);this.#s=o.hostname,this.#r=o.port?Number(o.port):o.protocol==="https:"?443:80,this.#t=(o.protocol||"").replace(":","");const i=this.#r!==443&&this.#r!==80;this.#o=[this.#s,i?`:${this.#r}`:""].join(""),this.#n=o.pathname.replace(/\/+$/,""),this.#i=[`${this.#t}://`,this.#o,this.#n].join("")}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const t=new URL(e);return t.pathname.startsWith(this.#n)&&(t.pathname=t.pathname.slice(this.#n.length)),w(t)}get isRequestRunning(){return this.#a.running>0}get absoluteUrl(){return this.#i}get documentRoot(){return this.#e}async request(e){const t=e.url.startsWith("http://")||e.url.startsWith("https://"),r=new URL(e.url,t?void 0:I),n=b(r.pathname,this.#n),o=`${this.#e}${n}`;return re(o)?await this.#c(e,r):this.#l(o)}#l(e){if(!this.php.fileExists(e))return new y(404,{"x-file-type":["static"]},new TextEncoder().encode("404 File not found"));const t=this.php.readFileAsBuffer(e);return new y(200,{"content-length":[`${t.byteLength}`],"content-type":[te(e)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},t)}async#c(e,t){const r=await this.#a.acquire();try{this.php.addServerGlobalEntry("DOCUMENT_ROOT",this.#e),this.php.addServerGlobalEntry("HTTPS",this.#i.startsWith("https://")?"on":"");let n="GET";const o={host:this.#o,...B(e.headers||{})},i=[];if(e.files&&Object.keys(e.files).length){n="POST";for(const c in e.files){const m=e.files[c];i.push({key:c,name:m.name,type:m.type,data:new Uint8Array(await m.arrayBuffer())})}o["content-type"]?.startsWith("multipart/form-data")&&(e.formData=ee(e.body||""),o["content-type"]="application/x-www-form-urlencoded",delete e.body)}let l;e.formData!==void 0?(n="POST",o["content-type"]=o["content-type"]||"application/x-www-form-urlencoded",l=new URLSearchParams(e.formData).toString()):l=e.body;let u;try{u=this.#u(t.pathname)}catch{return new y(404,{},new TextEncoder().encode("404 File not found"))}return await this.php.run({relativeUri:N(w(t),this.#n),protocol:this.#t,method:e.method||n,body:l,fileInfos:i,scriptPath:u,headers:o})}finally{r()}}#u(e){let t=b(e,this.#n);t.includes(".php")?t=t.split(".php")[0]+".php":(t.endsWith("/")||(t+="/"),t.endsWith("index.php")||(t+="index.php"));const r=`${this.#e}${t}`;if(this.php.fileExists(r))return r;if(!this.php.fileExists(`${this.#e}/index.php`))throw new Error(`File not found: ${r}`);return`${this.#e}/index.php`}}function ee(s){const e={},t=s.match(/--(.*)\r\n/);if(!t)return e;const r=t[1],n=s.split(`--${r}`);return n.shift(),n.pop(),n.forEach(o=>{const i=o.indexOf(`\r
31
+ `,he="\x1B[41m",Ge="\x1B[1m",ue="\x1B[0m",de="\x1B[K";let pe=!1;function Ve(s){if(!pe){pe=!0,console.log(`${he}
32
+ ${de}
33
+ ${Ge} WASM ERROR${ue}${he}`);for(const e of s.split(`
34
+ `))console.log(`${de} ${e} `);console.log(`${ue}`)}}function Je(s){try{const e=s.split(`
35
+ `).slice(1).map(t=>{const r=t.trim().substring(3).split(" ");return{fn:r.length>=2?r[0]:"<unknown>",isWasm:t.includes("wasm://")}}).filter(({fn:t,isWasm:r})=>r&&!t.startsWith("dynCall_")&&!t.startsWith("invoke_")).map(({fn:t})=>t);return Array.from(new Set(e))}catch{return[]}}class C{constructor(e,t,r,n="",o=0){this.httpStatusCode=e,this.headers=t,this.bytes=r,this.exitCode=o,this.errors=n}static fromRawData(e){return new C(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}const ae=["8.3","8.2","8.1","8.0","7.4","7.3","7.2","7.1","7.0"],Ye=ae[0],Ke=ae,Pe=["iconv","mbstring","xml-bundle","gd"],Ze={"kitchen-sink":Pe};var S,L;class we{constructor(e,t={}){c(this,S,void 0);c(this,L,void 0);this.requestHandler=e,p(this,S,{}),p(this,L,{handleRedirects:!1,maxRedirects:4,...t})}async request(e,t=0){const r=await this.requestHandler.request({...e,headers:{...e.headers,cookie:this.serializeCookies()}});if(r.headers["set-cookie"]&&this.setCookies(r.headers["set-cookie"]),i(this,L).handleRedirects&&r.headers.location&&t<i(this,L).maxRedirects){const n=new URL(r.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:n.toString(),method:"GET",headers:{}},t+1)}return r}pathToInternalUrl(e){return this.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.internalUrlToPath(e)}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}setCookies(e){for(const t of e)try{if(!t.includes("="))continue;const r=t.indexOf("="),n=t.substring(0,r),o=t.substring(r+1).split(";")[0];i(this,S)[n]=o}catch(r){console.error(r)}}serializeCookies(){const e=[];for(const t in i(this,S))e.push(`${t}=${i(this,S)[t]}`);return e.join("; ")}}S=new WeakMap,L=new WeakMap;class be{constructor({concurrency:e}){this._running=0,this.concurrency=e,this.queue=[]}get running(){return this._running}async acquire(){for(;;)if(this._running>=this.concurrency)await new Promise(e=>this.queue.push(e));else{this._running++;let e=!1;return()=>{e||(e=!0,this._running--,this.queue.length>0&&this.queue.shift()())}}}async run(e){const t=await this.acquire();try{return await e()}finally{t()}}}const _e="http://example.com";function ne(s){return s.toString().substring(s.origin.length)}function ie(s,e){return!e||!s.startsWith(e)?s:s.substring(e.length)}function Ee(s,e){return!e||s.startsWith(e)?s:e+s}var b,A,N,H,$,_,U,O,q,xe,j,Re,D,Se;class ve{constructor(e,t={}){c(this,q);c(this,j);c(this,D);c(this,b,void 0);c(this,A,void 0);c(this,N,void 0);c(this,H,void 0);c(this,$,void 0);c(this,_,void 0);c(this,U,void 0);c(this,O,void 0);p(this,O,new be({concurrency:1}));const{documentRoot:r="/www/",absoluteUrl:n=typeof location=="object"?location==null?void 0:location.href:""}=t;this.php=e,p(this,b,r);const o=new URL(n);p(this,N,o.hostname),p(this,H,o.port?Number(o.port):o.protocol==="https:"?443:80),p(this,A,(o.protocol||"").replace(":",""));const a=i(this,H)!==443&&i(this,H)!==80;p(this,$,[i(this,N),a?`:${i(this,H)}`:""].join("")),p(this,_,o.pathname.replace(/\/+$/,"")),p(this,U,[`${i(this,A)}://`,i(this,$),i(this,_)].join(""))}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const t=new URL(e);return t.pathname.startsWith(i(this,_))&&(t.pathname=t.pathname.slice(i(this,_).length)),ne(t)}get isRequestRunning(){return i(this,O).running>0}get absoluteUrl(){return i(this,U)}get documentRoot(){return i(this,b)}async request(e){const t=e.url.startsWith("http://")||e.url.startsWith("https://"),r=new URL(e.url,t?void 0:_e),n=ie(r.pathname,i(this,_)),o=`${i(this,b)}${n}`;return et(o)?await m(this,j,Re).call(this,e,r):m(this,q,xe).call(this,o)}}b=new WeakMap,A=new WeakMap,N=new WeakMap,H=new WeakMap,$=new WeakMap,_=new WeakMap,U=new WeakMap,O=new WeakMap,q=new WeakSet,xe=function(e){if(!this.php.fileExists(e))return new C(404,{"x-file-type":["static"]},new TextEncoder().encode("404 File not found"));const t=this.php.readFileAsBuffer(e);return new C(200,{"content-length":[`${t.byteLength}`],"content-type":[Xe(e)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},t)},j=new WeakSet,Re=async function(e,t){var n;const r=await i(this,O).acquire();try{this.php.addServerGlobalEntry("DOCUMENT_ROOT",i(this,b)),this.php.addServerGlobalEntry("HTTPS",i(this,U).startsWith("https://")?"on":"");let o="GET";const a={host:i(this,$),...Be(e.headers||{})},h=[];if(e.files&&Object.keys(e.files).length){o="POST";for(const u in e.files){const E=e.files[u];h.push({key:u,name:E.name,type:E.type,data:new Uint8Array(await E.arrayBuffer())})}(n=a["content-type"])!=null&&n.startsWith("multipart/form-data")&&(e.formData=Qe(e.body||""),a["content-type"]="application/x-www-form-urlencoded",delete e.body)}let d;e.formData!==void 0?(o="POST",a["content-type"]=a["content-type"]||"application/x-www-form-urlencoded",d=new URLSearchParams(e.formData).toString()):d=e.body;let f;try{f=m(this,D,Se).call(this,t.pathname)}catch{return new C(404,{},new TextEncoder().encode("404 File not found"))}return await this.php.run({relativeUri:Ee(ne(t),i(this,_)),protocol:i(this,A),method:e.method||o,body:d,fileInfos:h,scriptPath:f,headers:a})}finally{r()}},D=new WeakSet,Se=function(e){let t=ie(e,i(this,_));t.includes(".php")?t=t.split(".php")[0]+".php":(t.endsWith("/")||(t+="/"),t.endsWith("index.php")||(t+="index.php"));const r=`${i(this,b)}${t}`;if(this.php.fileExists(r))return r;if(!this.php.fileExists(`${i(this,b)}/index.php`))throw new Error(`File not found: ${r}`);return`${i(this,b)}/index.php`};function Qe(s){const e={},t=s.match(/--(.*)\r\n/);if(!t)return e;const r=t[1],n=s.split(`--${r}`);return n.shift(),n.pop(),n.forEach(o=>{const a=o.indexOf(`\r
36
36
  \r
37
- `),l=o.substring(0,i).trim(),u=o.substring(i+4).trim(),c=l.match(/name="([^"]+)"/);if(c){const m=c[1];e[m]=u}}),e}function te(s){switch(s.split(".").pop()){case"css":return"text/css";case"js":return"application/javascript";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"svg":return"image/svg+xml";case"woff":return"font/woff";case"woff2":return"font/woff2";case"ttf":return"font/ttf";case"otf":return"font/otf";case"eot":return"font/eot";case"ico":return"image/x-icon";case"html":return"text/html";case"json":return"application/json";case"xml":return"application/xml";case"txt":case"md":return"text/plain";default:return"application-octet-stream"}}function re(s){return se(s)||ne(s)}function se(s){return s.endsWith(".php")||s.includes(".php/")}function ne(s){return!s.split("/").pop().includes(".")}const C={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 p(s=""){return function(t,r,n){const o=n.value;n.value=function(...i){try{return o.apply(this,i)}catch(l){const u=typeof l=="object"?l?.errno:null;if(u in C){const c=C[u],m=typeof i[0]=="string"?i[0]:null,q=m!==null?s.replaceAll("{path}",m):s;throw new Error(`${q}: ${c}`,{cause:l})}throw l}}}}async function oe(s,e={},t=[]){const[r,n,o]=F(),[i,l]=F(),u=s.init(ae,{onAbort(c){o(c),l(),console.error(c)},ENV:{},locateFile:c=>c,...e,noInitialRun:!0,onRuntimeInitialized(){e.onRuntimeInitialized&&e.onRuntimeInitialized(),n()},monitorRunDependencies(c){c===0&&(delete u.monitorRunDependencies,l())}});return await Promise.all(t.map(({default:c})=>c(u))),t.length||l(),await i,await r,_.push(u),_.length-1}const _=[];function ie(s){return _[s]}const ae=function(){return typeof process<"u"&&process.release?.name==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}(),F=()=>{const s=[],e=new Promise((t,r)=>{s.push(t,r)});return s.unshift(e),s};var le=Object.defineProperty,ce=Object.getOwnPropertyDescriptor,f=(s,e,t,r)=>{for(var n=r>1?void 0:r?ce(e,t):e,o=s.length-1,i;o>=0;o--)(i=s[o])&&(n=(r?i(e,t,n):i(n))||n);return r&&n&&le(e,t,n),n};const h="string",g="number",a=Symbol("__private__dont__use");class d{constructor(e,t){this.#e=[],this.#t=!1,this.#s=null,this.#r={},this.#o=[],e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new O(new $(this,t)))}#e;#t;#s;#r;#o;async onMessage(e){this.#o.push(e)}get absoluteUrl(){return this.requestHandler.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.requestHandler.documentRoot}pathToInternalUrl(e){return this.requestHandler.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.requestHandler.internalUrlToPath(e)}initializeRuntime(e){if(this[a])throw new Error("PHP runtime already initialized.");const t=ie(e);if(!t)throw new Error("Invalid PHP runtime id.");this[a]=t,t.onMessage=r=>{for(const n of this.#o)n(r)},this.#s=W(t)}setPhpIniPath(e){if(this.#t)throw new Error("Cannot set PHP ini path after calling run().");this[a].ccall("wasm_set_phpini_path",null,["string"],[e])}setPhpIniEntry(e,t){if(this.#t)throw new Error("Cannot set PHP ini entries after calling run().");this.#e.push([e,t])}chdir(e){this[a].FS.chdir(e)}async request(e,t){if(!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(e,t)}async run(e){this.#t||(this.#n(),this.#t=!0),this.#d(e.scriptPath||""),this.#a(e.relativeUri||""),this.#c(e.method||"GET");const{host:t,...r}={host:"example.com:443",...B(e.headers||{})};if(this.#l(t,e.protocol||"http"),this.#u(r),e.body&&this.#h(e.body),e.fileInfos)for(const n of e.fileInfos)this.#f(n);return e.code&&this.#m(" ?>"+e.code),this.#p(),await this.#y()}#n(){if(this.#e.length>0){const e=this.#e.map(([t,r])=>`${t}=${r}`).join(`
37
+ `),h=o.substring(0,a).trim(),d=o.substring(a+4).trim(),f=h.match(/name="([^"]+)"/);if(f){const u=f[1];e[u]=d}}),e}function Xe(s){switch(s.split(".").pop()){case"css":return"text/css";case"js":return"application/javascript";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"svg":return"image/svg+xml";case"woff":return"font/woff";case"woff2":return"font/woff2";case"ttf":return"font/ttf";case"otf":return"font/otf";case"eot":return"font/eot";case"ico":return"image/x-icon";case"html":return"text/html";case"json":return"application/json";case"xml":return"application/xml";case"txt":case"md":return"text/plain";default:return"application-octet-stream"}}function et(s){return tt(s)||st(s)}function tt(s){return s.endsWith(".php")||s.includes(".php/")}function st(s){return!s.split("/").pop().includes(".")}const fe={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 P(s=""){return function(t,r,n){const o=n.value;n.value=function(...a){try{return o.apply(this,a)}catch(h){const d=typeof h=="object"?h==null?void 0:h.errno:null;if(d in fe){const f=fe[d],u=typeof a[0]=="string"?a[0]:null,E=u!==null?s.replaceAll("{path}",u):s;throw new Error(`${E}: ${f}`,{cause:h})}throw h}}}}const rt=Symbol("RuntimeId"),M=new Map;async function nt(s,e={},t=[]){const[r,n,o]=me(),[a,h]=me(),d=s.init(ot,{onAbort(u){o(u),h(),console.error(u)},ENV:{},locateFile:u=>u,...e,noInitialRun:!0,onRuntimeInitialized(){e.onRuntimeInitialized&&e.onRuntimeInitialized(),n()},monitorRunDependencies(u){u===0&&(delete d.monitorRunDependencies,h())}});await Promise.all(t.map(({default:u})=>u(d))),t.length||h(),await a,await r;const f=M.size;return d.originalExit=d._exit,d._exit=function(u){return M.delete(f),d.originalExit(u)},d[rt]=f,M.set(f,d),f}function it(s){return M.get(s)}const ot=function(){var s;return typeof process<"u"&&((s=process.release)==null?void 0:s.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}(),me=()=>{const s=[],e=new Promise((t,r)=>{s.push(t,r)});return s.unshift(e),s};var at=Object.defineProperty,lt=Object.getOwnPropertyDescriptor,w=(s,e,t,r)=>{for(var n=r>1?void 0:r?lt(e,t):e,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(r?a(e,t,n):a(n))||n);return r&&n&&at(e,t,n),n};const y="string",F="number",l=Symbol("__private__dont__use");var k,x,T,R,v,I,B,W,He,z,ke,G,Te,V,Ce,J,Fe,Y,Le,K,Ae,Z,$e,Q,Ue,X,Oe,ee,Ie,te,Ne;class g{constructor(e,t){c(this,W);c(this,z);c(this,G);c(this,V);c(this,J);c(this,Y);c(this,K);c(this,Z);c(this,Q);c(this,X);c(this,ee);c(this,te);c(this,k,void 0);c(this,x,void 0);c(this,T,void 0);c(this,R,void 0);c(this,v,void 0);c(this,I,void 0);c(this,B,void 0);p(this,k,[]),p(this,x,!1),p(this,T,null),p(this,R,{}),p(this,v,new Map),p(this,I,[]),p(this,B,new be({concurrency:1})),e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new we(new ve(this,t)))}addEventListener(e,t){i(this,v).has(e)||i(this,v).set(e,new Set),i(this,v).get(e).add(t)}removeEventListener(e,t){var r;(r=i(this,v).get(e))==null||r.delete(t)}dispatchEvent(e){const t=i(this,v).get(e.type);if(t)for(const r of t)r(e)}async onMessage(e){i(this,I).push(e)}async setSpawnHandler(e){this[l].spawnProcess=e}get absoluteUrl(){return this.requestHandler.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.requestHandler.documentRoot}pathToInternalUrl(e){return this.requestHandler.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.requestHandler.internalUrlToPath(e)}initializeRuntime(e){if(this[l])throw new Error("PHP runtime already initialized.");const t=it(e);if(!t)throw new Error("Invalid PHP runtime id.");this[l]=t,t.onMessage=async r=>{for(const n of i(this,I)){const o=await n(r);if(o)return o}return""},p(this,T,je(t))}setPhpIniPath(e){if(i(this,x))throw new Error("Cannot set PHP ini path after calling run().");this[l].ccall("wasm_set_phpini_path",null,["string"],[e])}setPhpIniEntry(e,t){if(i(this,x))throw new Error("Cannot set PHP ini entries after calling run().");i(this,k).push([e,t])}chdir(e){this[l].FS.chdir(e)}async request(e,t){if(!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(e,t)}async run(e){const t=await i(this,B).acquire();try{i(this,x)||(m(this,W,He).call(this),p(this,x,!0)),m(this,Z,$e).call(this,e.scriptPath||""),m(this,G,Te).call(this,e.relativeUri||""),m(this,J,Fe).call(this,e.method||"GET");const r=Be(e.headers||{}),n=r.host||"example.com:443";if(m(this,V,Ce).call(this,n,e.protocol||"http"),m(this,Y,Le).call(this,r),e.body&&m(this,K,Ae).call(this,e.body),e.fileInfos)for(const o of e.fileInfos)m(this,X,Oe).call(this,o);return e.code&&m(this,ee,Ie).call(this," ?>"+e.code),m(this,Q,Ue).call(this),await m(this,te,Ne).call(this)}finally{t(),this.dispatchEvent({type:"request.end"})}}addServerGlobalEntry(e,t){i(this,R)[e]=t}defineConstant(e,t){let r={};try{r=JSON.parse(this.fileExists("/tmp/consts.json")&&this.readFileAsText("/tmp/consts.json")||"{}")}catch{}this.writeFile("/tmp/consts.json",JSON.stringify({...r,[e]:t}))}mkdir(e){this[l].FS.mkdirTree(e)}mkdirTree(e){this.mkdir(e)}readFileAsText(e){return new TextDecoder().decode(this.readFileAsBuffer(e))}readFileAsBuffer(e){return this[l].FS.readFile(e)}writeFile(e,t){this[l].FS.writeFile(e,t)}unlink(e){this[l].FS.unlink(e)}mv(e,t){this[l].FS.rename(e,t)}rmdir(e,t={recursive:!0}){t!=null&&t.recursive&&this.listFiles(e).forEach(r=>{const n=`${e}/${r}`;this.isDir(n)?this.rmdir(n,t):this.unlink(n)}),this[l].FS.rmdir(e)}listFiles(e,t={prependPath:!1}){if(!this.fileExists(e))return[];try{const r=this[l].FS.readdir(e).filter(n=>n!=="."&&n!=="..");if(t.prependPath){const n=e.replace(/\/$/,"");return r.map(o=>`${n}/${o}`)}return r}catch(r){return console.error(r,{path:e}),[]}}isDir(e){return this.fileExists(e)?this[l].FS.isDir(this[l].FS.lookupPath(e).node.mode):!1}fileExists(e){try{return this[l].FS.lookupPath(e),!0}catch{return!1}}exit(e=0){return this[l]._exit(e)}}k=new WeakMap,x=new WeakMap,T=new WeakMap,R=new WeakMap,v=new WeakMap,I=new WeakMap,B=new WeakMap,W=new WeakSet,He=function(){if(this.setPhpIniEntry("auto_prepend_file","/tmp/consts.php"),this.fileExists("/tmp/consts.php")||this.writeFile("/tmp/consts.php",`<?php
38
+ if(file_exists('/tmp/consts.json')) {
39
+ $consts = json_decode(file_get_contents('/tmp/consts.json'), true);
40
+ foreach ($consts as $const => $value) {
41
+ if (!defined($const) && is_scalar($value)) {
42
+ define($const, $value);
43
+ }
44
+ }
45
+ }`),i(this,k).length>0){const e=i(this,k).map(([t,r])=>`${t}=${r}`).join(`
38
46
  `)+`
39
47
 
40
- `;this[a].ccall("wasm_set_phpini_entries",null,[h],[e])}this[a].ccall("php_wasm_init",null,[],[])}#i(){const e="/tmp/headers.json";if(!this.fileExists(e))throw new Error("SAPI Error: Could not find response headers file.");const t=JSON.parse(this.readFileAsText(e)),r={};for(const n of t.headers){if(!n.includes(": "))continue;const o=n.indexOf(": "),i=n.substring(0,o).toLowerCase(),l=n.substring(o+2);i in r||(r[i]=[]),r[i].push(l)}return{headers:r,httpStatusCode:t.status}}#a(e){if(this[a].ccall("wasm_set_request_uri",null,[h],[e]),e.includes("?")){const t=e.substring(e.indexOf("?")+1);this[a].ccall("wasm_set_query_string",null,[h],[t])}}#l(e,t){this[a].ccall("wasm_set_request_host",null,[h],[e]);let r;try{r=parseInt(new URL(e).port,10)}catch{}(!r||isNaN(r)||r===80)&&(r=t==="https"?443:80),this[a].ccall("wasm_set_request_port",null,[g],[r]),(t==="https"||!t&&r===443)&&this.addServerGlobalEntry("HTTPS","on")}#c(e){this[a].ccall("wasm_set_request_method",null,[h],[e])}#u(e){e.cookie&&this[a].ccall("wasm_set_cookies",null,[h],[e.cookie]),e["content-type"]&&this[a].ccall("wasm_set_content_type",null,[h],[e["content-type"]]),e["content-length"]&&this[a].ccall("wasm_set_content_length",null,[g],[parseInt(e["content-length"],10)]);for(const t in e){let r="HTTP_";["content-type","content-length"].includes(t.toLowerCase())&&(r=""),this.addServerGlobalEntry(`${r}${t.toUpperCase().replace(/-/g,"_")}`,e[t])}}#h(e){this[a].ccall("wasm_set_request_body",null,[h],[e]),this[a].ccall("wasm_set_content_length",null,[g],[new TextEncoder().encode(e).length])}#d(e){this[a].ccall("wasm_set_path_translated",null,[h],[e])}addServerGlobalEntry(e,t){this.#r[e]=t}#p(){for(const e in this.#r)this[a].ccall("wasm_add_SERVER_entry",null,[h,h],[e,this.#r[e]])}#f(e){const{key:t,name:r,type:n,data:o}=e,i=`/tmp/${Math.random().toFixed(20)}`;this.writeFile(i,o);const l=0;this[a].ccall("wasm_add_uploaded_file",null,[h,h,h,h,g,g],[t,r,n,i,l,o.byteLength])}#m(e){this[a].ccall("wasm_set_php_code",null,[h],[e])}async#y(){let e,t;try{e=await new Promise((o,i)=>{t=u=>{const c=new Error("Rethrown");c.cause=u.error,c.betterMessage=u.message,i(c)},this.#s?.addEventListener("error",t);const l=this[a].ccall("wasm_sapi_handle_request",g,[],[]);return l instanceof Promise?l.then(o,i):o(l)})}catch(o){for(const c in this)typeof this[c]=="function"&&(this[c]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=j();const i=o,l="betterMessage"in i?i.betterMessage:i.message,u=new Error(l);throw u.cause=i,u}finally{this.#s?.removeEventListener("error",t),this.#r={}}const{headers:r,httpStatusCode:n}=this.#i();return new y(n,r,this.readFileAsBuffer("/tmp/stdout"),this.readFileAsText("/tmp/stderr"),e)}mkdir(e){this[a].FS.mkdirTree(e)}mkdirTree(e){this.mkdir(e)}readFileAsText(e){return new TextDecoder().decode(this.readFileAsBuffer(e))}readFileAsBuffer(e){return this[a].FS.readFile(e)}writeFile(e,t){this[a].FS.writeFile(e,t)}unlink(e){this[a].FS.unlink(e)}mv(e,t){this[a].FS.rename(e,t)}rmdir(e,t={recursive:!0}){t?.recursive&&this.listFiles(e).forEach(r=>{const n=`${e}/${r}`;this.isDir(n)?this.rmdir(n,t):this.unlink(n)}),this[a].FS.rmdir(e)}listFiles(e,t={prependPath:!1}){if(!this.fileExists(e))return[];try{const r=this[a].FS.readdir(e).filter(n=>n!=="."&&n!=="..");if(t.prependPath){const n=e.replace(/\/$/,"");return r.map(o=>`${n}/${o}`)}return r}catch(r){return console.error(r,{path:e}),[]}}isDir(e){return this.fileExists(e)?this[a].FS.isDir(this[a].FS.lookupPath(e).node.mode):!1}fileExists(e){try{return this[a].FS.lookupPath(e),!0}catch{return!1}}}f([p('Could not create directory "{path}"')],d.prototype,"mkdir",1);f([p('Could not create directory "{path}"')],d.prototype,"mkdirTree",1);f([p('Could not read "{path}"')],d.prototype,"readFileAsText",1);f([p('Could not read "{path}"')],d.prototype,"readFileAsBuffer",1);f([p('Could not write to "{path}"')],d.prototype,"writeFile",1);f([p('Could not unlink "{path}"')],d.prototype,"unlink",1);f([p('Could not move "{path}"')],d.prototype,"mv",1);f([p('Could not remove directory "{path}"')],d.prototype,"rmdir",1);f([p('Could not list files in "{path}"')],d.prototype,"listFiles",1);f([p('Could not stat "{path}"')],d.prototype,"isDir",1);f([p('Could not stat "{path}"')],d.prototype,"fileExists",1);function B(s){const e={};for(const t in s)e[t.toLowerCase()]=s[t];return e}function M(s){return!(s instanceof d)}function ue(s){return!M(s)}exports.BasePHP=d;exports.DEFAULT_BASE_URL=I;exports.LatestSupportedPHPVersion=K;exports.PHPBrowser=O;exports.PHPRequestHandler=$;exports.PHPResponse=y;exports.SupportedPHPExtensionBundles=Q;exports.SupportedPHPExtensionsList=L;exports.SupportedPHPVersions=v;exports.SupportedPHPVersionsList=Z;exports.UnhandledRejectionsTarget=U;exports.__private__dont__use=a;exports.ensurePathPrefix=N;exports.isExitCodeZero=A;exports.isLocalPHP=M;exports.isRemotePHP=ue;exports.loadPHPRuntime=oe;exports.removePathPrefix=b;exports.rethrowFileSystemError=p;exports.toRelativeUrl=w;
48
+ `;this[l].ccall("wasm_set_phpini_entries",null,[y],[e])}this[l].ccall("php_wasm_init",null,[],[])},z=new WeakSet,ke=function(){const e="/tmp/headers.json";if(!this.fileExists(e))throw new Error("SAPI Error: Could not find response headers file.");const t=JSON.parse(this.readFileAsText(e)),r={};for(const n of t.headers){if(!n.includes(": "))continue;const o=n.indexOf(": "),a=n.substring(0,o).toLowerCase(),h=n.substring(o+2);a in r||(r[a]=[]),r[a].push(h)}return{headers:r,httpStatusCode:t.status}},G=new WeakSet,Te=function(e){if(this[l].ccall("wasm_set_request_uri",null,[y],[e]),e.includes("?")){const t=e.substring(e.indexOf("?")+1);this[l].ccall("wasm_set_query_string",null,[y],[t])}},V=new WeakSet,Ce=function(e,t){this[l].ccall("wasm_set_request_host",null,[y],[e]);let r;try{r=parseInt(new URL(e).port,10)}catch{}(!r||isNaN(r)||r===80)&&(r=t==="https"?443:80),this[l].ccall("wasm_set_request_port",null,[F],[r]),(t==="https"||!t&&r===443)&&this.addServerGlobalEntry("HTTPS","on")},J=new WeakSet,Fe=function(e){this[l].ccall("wasm_set_request_method",null,[y],[e])},Y=new WeakSet,Le=function(e){e.cookie&&this[l].ccall("wasm_set_cookies",null,[y],[e.cookie]),e["content-type"]&&this[l].ccall("wasm_set_content_type",null,[y],[e["content-type"]]),e["content-length"]&&this[l].ccall("wasm_set_content_length",null,[F],[parseInt(e["content-length"],10)]);for(const t in e){let r="HTTP_";["content-type","content-length"].includes(t.toLowerCase())&&(r=""),this.addServerGlobalEntry(`${r}${t.toUpperCase().replace(/-/g,"_")}`,e[t])}},K=new WeakSet,Ae=function(e){this[l].ccall("wasm_set_request_body",null,[y],[e]),this[l].ccall("wasm_set_content_length",null,[F],[new TextEncoder().encode(e).length])},Z=new WeakSet,$e=function(e){this[l].ccall("wasm_set_path_translated",null,[y],[e])},Q=new WeakSet,Ue=function(){for(const e in i(this,R))this[l].ccall("wasm_add_SERVER_entry",null,[y,y],[e,i(this,R)[e]])},X=new WeakSet,Oe=function(e){const{key:t,name:r,type:n,data:o}=e,a=`/tmp/${Math.random().toFixed(20)}`;this.writeFile(a,o);const h=0;this[l].ccall("wasm_add_uploaded_file",null,[y,y,y,y,F,F],[t,r,n,a,h,o.byteLength])},ee=new WeakSet,Ie=function(e){this[l].ccall("wasm_set_php_code",null,[y],[e])},te=new WeakSet,Ne=async function(){var o;let e,t;try{e=await new Promise((a,h)=>{var f;t=u=>{const E=new Error("Rethrown");E.cause=u.error,E.betterMessage=u.message,h(E)},(f=i(this,T))==null||f.addEventListener("error",t);const d=this[l].ccall("wasm_sapi_handle_request",F,[],[],{async:!0});return d instanceof Promise?d.then(a,h):a(d)})}catch(a){for(const u in this)typeof this[u]=="function"&&(this[u]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=De();const h=a,d="betterMessage"in h?h.betterMessage:h.message,f=new Error(d);throw f.cause=h,f}finally{(o=i(this,T))==null||o.removeEventListener("error",t),p(this,R,{})}const{headers:r,httpStatusCode:n}=m(this,z,ke).call(this);return new C(n,r,this.readFileAsBuffer("/tmp/stdout"),this.readFileAsText("/tmp/stderr"),e)};w([P('Could not create directory "{path}"')],g.prototype,"mkdir",1);w([P('Could not create directory "{path}"')],g.prototype,"mkdirTree",1);w([P('Could not read "{path}"')],g.prototype,"readFileAsText",1);w([P('Could not read "{path}"')],g.prototype,"readFileAsBuffer",1);w([P('Could not write to "{path}"')],g.prototype,"writeFile",1);w([P('Could not unlink "{path}"')],g.prototype,"unlink",1);w([P('Could not move "{path}"')],g.prototype,"mv",1);w([P('Could not remove directory "{path}"')],g.prototype,"rmdir",1);w([P('Could not list files in "{path}"')],g.prototype,"listFiles",1);w([P('Could not stat "{path}"')],g.prototype,"isDir",1);w([P('Could not stat "{path}"')],g.prototype,"fileExists",1);function Be(s){const e={};for(const t in s)e[t.toLowerCase()]=s[t];return e}function Me(s){return!(s instanceof g)}function ct(s){return!Me(s)}exports.BasePHP=g;exports.DEFAULT_BASE_URL=_e;exports.LatestSupportedPHPVersion=Ye;exports.PHPBrowser=we;exports.PHPRequestHandler=ve;exports.PHPResponse=C;exports.SupportedPHPExtensionBundles=Ze;exports.SupportedPHPExtensionsList=Pe;exports.SupportedPHPVersions=ae;exports.SupportedPHPVersionsList=Ke;exports.UnhandledRejectionsTarget=ge;exports.__private__dont__use=l;exports.ensurePathPrefix=Ee;exports.isExitCodeZero=ye;exports.isLocalPHP=Me;exports.isRemotePHP=ct;exports.loadPHPRuntime=nt;exports.removePathPrefix=ie;exports.rethrowFileSystemError=P;exports.toRelativeUrl=ne;