@php-wasm/universal 0.5.4 → 0.5.6
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 +7 -7
- package/index.js +3 -3
- package/package.json +2 -2
package/index.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var ne=(r,e,t)=>{if(!e.has(r))throw TypeError("Cannot "+t)};var a=(r,e,t)=>(ne(r,e,"read from private field"),t?t.call(r):e.get(r)),u=(r,e,t)=>{if(e.has(r))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(r):e.set(r,t)},p=(r,e,t,n)=>(ne(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t);var m=(r,e,t)=>(ne(r,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});if(typeof File>"u"){class r extends Blob{constructor(t,n,s){super(t);let i;s!=null&&s.lastModified&&(i=new Date),(!i||isNaN(i.getFullYear()))&&(i=new Date),this.lastModifiedDate=i,this.lastModified=i.getMilliseconds(),this.name=n||""}}global.File=r}function we(r){return new Promise(function(e,t){r.onload=r.onerror=function(n){r.onload=r.onerror=null,n.type==="load"?e(r.result):t(new Error("Failed to read the blob/file"))}})}typeof Blob.prototype.arrayBuffer>"u"&&(Blob.prototype.arrayBuffer=function(){const e=new FileReader;return e.readAsArrayBuffer(this),we(e)});typeof Blob.prototype.text>"u"&&(Blob.prototype.text=function(){const e=new FileReader;return e.readAsText(this),we(e)});function We(){const r=new Uint8Array([1,2,3,4]),t=new File([r],"test").stream();try{return t.getReader({mode:"byob"}),!0}catch{return!1}}(typeof Blob.prototype.stream>"u"||!We())&&(Blob.prototype.stream=function(){let r=0;const e=this;return new ReadableStream({type:"bytes",autoAllocateChunkSize:512*1024,async pull(t){const n=t.byobRequest.view,i=await e.slice(r,r+n.byteLength).arrayBuffer(),o=new Uint8Array(i);new Uint8Array(n.buffer).set(o);const l=o.byteLength;t.byobRequest.respond(l),r+=l,r>=e.size&&t.close()}})});if(typeof CustomEvent>"u"){class r extends Event{constructor(t,n={}){super(t,n),this.detail=n.detail}initCustomEvent(){}}globalThis.CustomEvent=r}const ue=Symbol("error"),he=Symbol("message");class ae extends Event{constructor(e,t={}){super(e),this[ue]=t.error===void 0?null:t.error,this[he]=t.message===void 0?"":t.message}get error(){return this[ue]}get message(){return this[he]}}Object.defineProperty(ae.prototype,"error",{enumerable:!0});Object.defineProperty(ae.prototype,"message",{enumerable:!0});const ze=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:ae;function ge(r){return r instanceof Error?"exitCode"in r&&(r==null?void 0:r.exitCode)===0||(r==null?void 0:r.name)==="ExitStatus"&&"status"in r&&r.status===0:!1}class Pe 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 Ge(r){r.asm={...r.asm};const e=new Pe;for(const t in r.asm)if(typeof r.asm[t]=="function"){const n=r.asm[t];r.asm[t]=function(...s){var i;try{return n(...s)}catch(o){if(!(o instanceof Error))throw o;const l=Je(o,(i=r.lastAsyncifyStackSource)==null?void 0:i.stack);if(r.lastAsyncifyStackSource&&(o.cause=r.lastAsyncifyStackSource),e.hasListeners()){e.dispatchEvent(new ze("error",{error:o,message:l}));return}throw ge(o)||Ze(l),o}}}return e}let se=[];function Ve(){return se}function Je(r,e){if(r.message==="unreachable"){let t=Ye;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
|
-
`),
|
|
6
|
+
`),se=Qe(e||r.stack||"");for(const n of se)t+=` * ${n}
|
|
7
7
|
`;return t}return r.message}const Ye=`
|
|
8
8
|
"unreachable" WASM instruction executed.
|
|
9
9
|
|
|
@@ -28,13 +28,13 @@ 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
|
-
`,de="\x1B[41m",Ke="\x1B[1m",fe="\x1B[0m",pe="\x1B[K";let me=!1;function Ze(r){if(!me
|
|
31
|
+
`,de="\x1B[41m",Ke="\x1B[1m",fe="\x1B[0m",pe="\x1B[K";let me=!1;function Ze(r){if(!me&&(me=!0,!(r!=null&&r.trim().startsWith("Program terminated with exit")))){console.log(`${de}
|
|
32
32
|
${pe}
|
|
33
33
|
${Ke} WASM ERROR${fe}${de}`);for(const e of r.split(`
|
|
34
34
|
`))console.log(`${pe} ${e} `);console.log(`${fe}`)}}function Qe(r){try{const e=r.split(`
|
|
35
|
-
`).slice(1).map(t=>{const
|
|
35
|
+
`).slice(1).map(t=>{const n=t.trim().substring(3).split(" ");return{fn:n.length>=2?n[0]:"<unknown>",isWasm:t.includes("wasm://")}}).filter(({fn:t,isWasm:n})=>n&&!t.startsWith("dynCall_")&&!t.startsWith("invoke_")).map(({fn:t})=>t);return Array.from(new Set(e))}catch{return[]}}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()}}}function Se(...r){let e=r.join("/");const t=e[0]==="/",n=e.substring(e.length-1)==="/";return e=le(e),!e&&!t&&(e="."),e&&n&&(e+="/"),e}function Xe(r){if(r==="/")return"/";r=le(r);const e=r.lastIndexOf("/");return e===-1?"":e===0?"/":r.substr(0,e)}function le(r){const e=r[0]==="/";return r=et(r.split("/").filter(t=>!!t),!e).join("/"),(e?"/":"")+r.replace(/\/$/,"")}function et(r,e){let t=0;for(let n=r.length-1;n>=0;n--){const s=r[n];s==="."?r.splice(n,1):s===".."?(r.splice(n,1),t++):t&&(r.splice(n,1),t--)}if(e)for(;t;t--)r.unshift("..");return r}function tt(...r){const e=new Uint8Array(r.reduce((n,s)=>n+s.length,0));let t=0;for(const n of r)e.set(n,t),t+=n.length;return e}function rt(r){if(r===void 0){let e=new Uint8Array;return new TransformStream({transform(t){e=tt(e,t)},flush(t){t.enqueue(e)}})}else{const e=new ArrayBuffer(r||0);let t=0;return new TransformStream({transform(n){new Uint8Array(e).set(n,t),t+=n.byteLength},flush(n){n.enqueue(new Uint8Array(e))}})}}function nt(r,e){if(e===0)return new ReadableStream({start(s){s.close()}});const t=r.getReader({mode:"byob"});let n=0;return new ReadableStream({async pull(s){const{value:i,done:o}=await t.read(new Uint8Array(e-n));if(o){t.releaseLock(),s.close();return}n+=i.length,s.enqueue(i),n>=e&&(t.releaseLock(),s.close())},cancel(){t.cancel()}})}async function st(r,e){return e!==void 0&&(r=nt(r,e)),await r.pipeThrough(rt(e)).getReader().read().then(({value:t})=>t)}class it extends File{constructor(e,t,n){super([],t,{type:n}),this.readableStream=e}slice(){throw new Error("slice() is not possible on a StreamedFile")}stream(){return this.readableStream}async text(){return new TextDecoder().decode(await this.arrayBuffer())}async arrayBuffer(){return await st(this.stream())}}ReadableStream.prototype[Symbol.asyncIterator]||(ReadableStream.prototype[Symbol.asyncIterator]=async function*(){const r=this.getReader();try{for(;;){const{done:e,value:t}=await r.read();if(e)return;yield t}}finally{r.releaseLock()}},ReadableStream.prototype.iterate=ReadableStream.prototype[Symbol.asyncIterator]);function ot(r,e){return new ReadableStream({async pull(t){const n=await r.readFileAsBuffer(e);t.enqueue(n),t.close()}})}async function*at(r,e,{relativePaths:t=!0,pathPrefix:n,exceptPaths:s=[]}={}){e=le(e);const i=[e];for(;i.length;){const o=i.pop();if(!o)return;const l=await r.listFiles(o);for(const d of l){const f=`${o}/${d}`;if(s.includes(f.substring(e.length+1)))continue;await r.isDir(f)?i.push(f):yield new it(ot(r,f),t?Se(n||"",f.substring(e.length+1)):f)}}}function lt(r,e){return new WritableStream({async write(t){const n=Se(e,t.name);t.type==="directory"?await r.mkdir(n):(await r.mkdir(Xe(n)),await r.writeFile(n,new Uint8Array(await t.arrayBuffer())))}})}class T{constructor(e,t,n,s="",i=0){this.httpStatusCode=e,this.headers=t,this.bytes=n,this.exitCode=i,this.errors=s}static fromRawData(e){return new T(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 ce=["8.3","8.2","8.1","8.0","7.4","7.3","7.2","7.1","7.0"],ct=ce[0],ut=ce,Ee=["iconv","mbstring","xml-bundle","gd"],ht={"kitchen-sink":Ee};var x,A;class Re{constructor(e,t={}){u(this,x,void 0);u(this,A,void 0);this.requestHandler=e,p(this,x,{}),p(this,A,{handleRedirects:!1,maxRedirects:4,...t})}async request(e,t=0){const n=await this.requestHandler.request({...e,headers:{...e.headers,cookie:this.serializeCookies()}});if(n.headers["set-cookie"]&&this.setCookies(n.headers["set-cookie"]),a(this,A).handleRedirects&&n.headers.location&&t<a(this,A).maxRedirects){const s=new URL(n.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:s.toString(),method:"GET",headers:{}},t+1)}return n}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 n=t.indexOf("="),s=t.substring(0,n),i=t.substring(n+1).split(";")[0];a(this,x)[s]=i}catch(n){console.error(n)}}serializeCookies(){const e=[];for(const t in a(this,x))e.push(`${t}=${a(this,x)[t]}`);return e.join("; ")}}x=new WeakMap,A=new WeakMap;const ve="http://example.com";function ie(r){return r.toString().substring(r.origin.length)}function oe(r,e){return!e||!r.startsWith(e)?r:r.substring(e.length)}function _e(r,e){return!e||r.startsWith(e)?r:e+r}var P,U,O,F,B,b,L,$,M,Fe,j,He,W,ke;class xe{constructor(e,t={}){u(this,M);u(this,j);u(this,W);u(this,P,void 0);u(this,U,void 0);u(this,O,void 0);u(this,F,void 0);u(this,B,void 0);u(this,b,void 0);u(this,L,void 0);u(this,$,void 0);p(this,$,new be({concurrency:1}));const{documentRoot:n="/www/",absoluteUrl:s=typeof location=="object"?location==null?void 0:location.href:""}=t;this.php=e,p(this,P,n);const i=new URL(s);p(this,O,i.hostname),p(this,F,i.port?Number(i.port):i.protocol==="https:"?443:80),p(this,U,(i.protocol||"").replace(":",""));const o=a(this,F)!==443&&a(this,F)!==80;p(this,B,[a(this,O),o?`:${a(this,F)}`:""].join("")),p(this,b,i.pathname.replace(/\/+$/,"")),p(this,L,[`${a(this,U)}://`,a(this,B),a(this,b)].join(""))}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const t=new URL(e);return t.pathname.startsWith(a(this,b))&&(t.pathname=t.pathname.slice(a(this,b).length)),ie(t)}get isRequestRunning(){return a(this,$).running>0}get absoluteUrl(){return a(this,L)}get documentRoot(){return a(this,P)}async request(e){const t=e.url.startsWith("http://")||e.url.startsWith("https://"),n=new URL(e.url,t?void 0:ve),s=oe(n.pathname,a(this,b)),i=`${a(this,P)}${s}`;return pt(i)?await m(this,j,He).call(this,e,n):m(this,M,Fe).call(this,i)}}P=new WeakMap,U=new WeakMap,O=new WeakMap,F=new WeakMap,B=new WeakMap,b=new WeakMap,L=new WeakMap,$=new WeakMap,M=new WeakSet,Fe=function(e){if(!this.php.fileExists(e))return new T(404,{"x-file-type":["static"]},new TextEncoder().encode("404 File not found"));const t=this.php.readFileAsBuffer(e);return new T(200,{"content-length":[`${t.byteLength}`],"content-type":[ft(e)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},t)},j=new WeakSet,He=async function(e,t){var s;const n=await a(this,$).acquire();try{this.php.addServerGlobalEntry("DOCUMENT_ROOT",a(this,P)),this.php.addServerGlobalEntry("HTTPS",a(this,L).startsWith("https://")?"on":"");let i="GET";const o={host:a(this,B),...Me(e.headers||{})},l=[];if(e.files&&Object.keys(e.files).length){i="POST";for(const h in e.files){const E=e.files[h];l.push({key:h,name:E.name,type:E.type,data:new Uint8Array(await E.arrayBuffer())})}(s=o["content-type"])!=null&&s.startsWith("multipart/form-data")&&(e.formData=dt(e.body||""),o["content-type"]="application/x-www-form-urlencoded",delete e.body)}let d;e.formData!==void 0?(i="POST",o["content-type"]=o["content-type"]||"application/x-www-form-urlencoded",d=new URLSearchParams(e.formData).toString()):d=e.body;let f;try{f=m(this,W,ke).call(this,t.pathname)}catch{return new T(404,{},new TextEncoder().encode("404 File not found"))}return await this.php.run({relativeUri:_e(ie(t),a(this,b)),protocol:a(this,U),method:e.method||i,body:d,fileInfos:l,scriptPath:f,headers:o})}finally{n()}},W=new WeakSet,ke=function(e){let t=oe(e,a(this,b));t.includes(".php")?t=t.split(".php")[0]+".php":(t.endsWith("/")||(t+="/"),t.endsWith("index.php")||(t+="index.php"));const n=`${a(this,P)}${t}`;if(this.php.fileExists(n))return n;if(!this.php.fileExists(`${a(this,P)}/index.php`))throw new Error(`File not found: ${n}`);return`${a(this,P)}/index.php`};function dt(r){const e={},t=r.match(/--(.*)\r\n/);if(!t)return e;const n=t[1],s=r.split(`--${n}`);return s.shift(),s.pop(),s.forEach(i=>{const o=i.indexOf(`\r
|
|
36
36
|
\r
|
|
37
|
-
`),l=i.substring(0,o).trim(),d=i.substring(o+4).trim(),f=l.match(/name="([^"]+)"/);if(f){const h=f[1];e[h]=d}}),e}function ft(r){switch(r.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 pt(r){return mt(r)||yt(r)}function mt(r){return r.endsWith(".php")||r.includes(".php/")}function yt(r){return!r.split("/").pop().includes(".")}const D={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 wt(r){const e=typeof r=="object"?r==null?void 0:r.errno:null;if(e in D)return D[e]}function g(r=""){return function(t,s
|
|
37
|
+
`),l=i.substring(0,o).trim(),d=i.substring(o+4).trim(),f=l.match(/name="([^"]+)"/);if(f){const h=f[1];e[h]=d}}),e}function ft(r){switch(r.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 pt(r){return mt(r)||yt(r)}function mt(r){return r.endsWith(".php")||r.includes(".php/")}function yt(r){return!r.split("/").pop().includes(".")}const D={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 wt(r){const e=typeof r=="object"?r==null?void 0:r.errno:null;if(e in D)return D[e]}function g(r=""){return function(t,n,s){const i=s.value;s.value=function(...o){try{return i.apply(this,o)}catch(l){const d=typeof l=="object"?l==null?void 0:l.errno:null;if(d in D){const f=D[d],h=typeof o[0]=="string"?o[0]:null,E=h!==null?r.replaceAll("{path}",h):r;throw new Error(`${E}: ${f}`,{cause:l})}throw l}}}}const gt=Symbol("RuntimeId"),q=new Map;async function Pt(r,e={},t=[]){const[n,s,i]=ye(),[o,l]=ye(),d=r.init(St,{onAbort(h){i(h),l(),console.error(h)},ENV:{},locateFile:h=>h,...e,noInitialRun:!0,onRuntimeInitialized(){e.onRuntimeInitialized&&e.onRuntimeInitialized(),s()},monitorRunDependencies(h){h===0&&(delete d.monitorRunDependencies,l())}});await Promise.all(t.map(({default:h})=>h(d))),t.length||l(),await o,await n;const f=q.size;return d.originalExit=d._exit,d._exit=function(h){return q.delete(f),d.originalExit(h)},d[gt]=f,q.set(f,d),f}function bt(r){return q.get(r)}const St=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"}(),ye=()=>{const r=[],e=new Promise((t,n)=>{r.push(t,n)});return r.unshift(e),r};var Et=Object.defineProperty,Rt=Object.getOwnPropertyDescriptor,S=(r,e,t,n)=>{for(var s=n>1?void 0:n?Rt(e,t):e,i=r.length-1,o;i>=0;i--)(o=r[i])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&Et(e,t,s),s};const y="string",C="number",c=Symbol("__private__dont__use");var H,v,k,_,R,I,N,z,Te,G,Ce,V,Ae,J,Ue,Y,Be,K,Le,Z,$e,Q,Ie,X,Oe,ee,Ne,te,qe,re,De;class w{constructor(e,t){u(this,z);u(this,G);u(this,V);u(this,J);u(this,Y);u(this,K);u(this,Z);u(this,Q);u(this,X);u(this,ee);u(this,te);u(this,re);u(this,H,void 0);u(this,v,void 0);u(this,k,void 0);u(this,_,void 0);u(this,R,void 0);u(this,I,void 0);u(this,N,void 0);p(this,H,[]),p(this,v,!1),p(this,k,null),p(this,_,{}),p(this,R,new Map),p(this,I,[]),p(this,N,new be({concurrency:1})),e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new Re(new xe(this,t)))}addEventListener(e,t){a(this,R).has(e)||a(this,R).set(e,new Set),a(this,R).get(e).add(t)}removeEventListener(e,t){var n;(n=a(this,R).get(e))==null||n.delete(t)}dispatchEvent(e){const t=a(this,R).get(e.type);if(t)for(const n of t)n(e)}async onMessage(e){a(this,I).push(e)}async setSpawnHandler(e){this[c].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[c])throw new Error("PHP runtime already initialized.");const t=bt(e);if(!t)throw new Error("Invalid PHP runtime id.");this[c]=t,t.onMessage=async n=>{for(const s of a(this,I)){const i=await s(n);if(i)return i}return""},p(this,k,Ge(t))}setPhpIniPath(e){if(a(this,v))throw new Error("Cannot set PHP ini path after calling run().");this[c].ccall("wasm_set_phpini_path",null,["string"],[e])}setPhpIniEntry(e,t){if(a(this,v))throw new Error("Cannot set PHP ini entries after calling run().");a(this,H).push([e,t])}chdir(e){this[c].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 a(this,N).acquire();try{a(this,v)||(m(this,z,Te).call(this),p(this,v,!0)),m(this,Q,Ie).call(this,e.scriptPath||""),m(this,V,Ae).call(this,e.relativeUri||""),m(this,Y,Be).call(this,e.method||"GET");const n=Me(e.headers||{}),s=n.host||"example.com:443";if(m(this,J,Ue).call(this,s,e.protocol||"http"),m(this,K,Le).call(this,n),e.body&&m(this,Z,$e).call(this,e.body),e.fileInfos)for(const i of e.fileInfos)m(this,ee,Ne).call(this,i);return e.code&&m(this,te,qe).call(this," ?>"+e.code),m(this,X,Oe).call(this),await m(this,re,De).call(this)}finally{t(),this.dispatchEvent({type:"request.end"})}}addServerGlobalEntry(e,t){a(this,_)[e]=t}defineConstant(e,t){let n={};try{n=JSON.parse(this.fileExists("/tmp/consts.json")&&this.readFileAsText("/tmp/consts.json")||"{}")}catch{}this.writeFile("/tmp/consts.json",JSON.stringify({...n,[e]:t}))}mkdir(e){this[c].FS.mkdirTree(e)}mkdirTree(e){this.mkdir(e)}readFileAsText(e){return new TextDecoder().decode(this.readFileAsBuffer(e))}readFileAsBuffer(e){return this[c].FS.readFile(e)}writeFile(e,t){this[c].FS.writeFile(e,t)}unlink(e){this[c].FS.unlink(e)}mv(e,t){try{this[c].FS.rename(e,t)}catch(n){const s=wt(n);throw s?new Error(`Could not move ${e} to ${t}: ${s}`,{cause:n}):n}}rmdir(e,t={recursive:!0}){t!=null&&t.recursive&&this.listFiles(e).forEach(n=>{const s=`${e}/${n}`;this.isDir(s)?this.rmdir(s,t):this.unlink(s)}),this[c].FS.rmdir(e)}listFiles(e,t={prependPath:!1}){if(!this.fileExists(e))return[];try{const n=this[c].FS.readdir(e).filter(s=>s!=="."&&s!=="..");if(t.prependPath){const s=e.replace(/\/$/,"");return n.map(i=>`${s}/${i}`)}return n}catch(n){return console.error(n,{path:e}),[]}}isDir(e){return this.fileExists(e)?this[c].FS.isDir(this[c].FS.lookupPath(e).node.mode):!1}fileExists(e){try{return this[c].FS.lookupPath(e),!0}catch{return!1}}exit(e=0){return this[c]._exit(e)}}H=new WeakMap,v=new WeakMap,k=new WeakMap,_=new WeakMap,R=new WeakMap,I=new WeakMap,N=new WeakMap,z=new WeakSet,Te=function(){if(this.setPhpIniEntry("auto_prepend_file","/tmp/consts.php"),this.fileExists("/tmp/consts.php")||this.writeFile("/tmp/consts.php",`<?php
|
|
38
38
|
if(file_exists('/tmp/consts.json')) {
|
|
39
39
|
$consts = json_decode(file_get_contents('/tmp/consts.json'), true);
|
|
40
40
|
foreach ($consts as $const => $value) {
|
|
@@ -42,7 +42,7 @@ ${Ke} WASM ERROR${fe}${de}`);for(const e of r.split(`
|
|
|
42
42
|
define($const, $value);
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
|
-
}`),a(this,H).length>0){const e=a(this,H).map(([t,
|
|
45
|
+
}`),a(this,H).length>0){const e=a(this,H).map(([t,n])=>`${t}=${n}`).join(`
|
|
46
46
|
`)+`
|
|
47
47
|
|
|
48
|
-
`;this[c].ccall("wasm_set_phpini_entries",null,[y],[e])}this[c].ccall("php_wasm_init",null,[],[])},G=new WeakSet,Ce=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)),
|
|
48
|
+
`;this[c].ccall("wasm_set_phpini_entries",null,[y],[e])}this[c].ccall("php_wasm_init",null,[],[])},G=new WeakSet,Ce=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)),n={};for(const s of t.headers){if(!s.includes(": "))continue;const i=s.indexOf(": "),o=s.substring(0,i).toLowerCase(),l=s.substring(i+2);o in n||(n[o]=[]),n[o].push(l)}return{headers:n,httpStatusCode:t.status}},V=new WeakSet,Ae=function(e){if(this[c].ccall("wasm_set_request_uri",null,[y],[e]),e.includes("?")){const t=e.substring(e.indexOf("?")+1);this[c].ccall("wasm_set_query_string",null,[y],[t])}},J=new WeakSet,Ue=function(e,t){this[c].ccall("wasm_set_request_host",null,[y],[e]);let n;try{n=parseInt(new URL(e).port,10)}catch{}(!n||isNaN(n)||n===80)&&(n=t==="https"?443:80),this[c].ccall("wasm_set_request_port",null,[C],[n]),(t==="https"||!t&&n===443)&&this.addServerGlobalEntry("HTTPS","on")},Y=new WeakSet,Be=function(e){this[c].ccall("wasm_set_request_method",null,[y],[e])},K=new WeakSet,Le=function(e){e.cookie&&this[c].ccall("wasm_set_cookies",null,[y],[e.cookie]),e["content-type"]&&this[c].ccall("wasm_set_content_type",null,[y],[e["content-type"]]),e["content-length"]&&this[c].ccall("wasm_set_content_length",null,[C],[parseInt(e["content-length"],10)]);for(const t in e){let n="HTTP_";["content-type","content-length"].includes(t.toLowerCase())&&(n=""),this.addServerGlobalEntry(`${n}${t.toUpperCase().replace(/-/g,"_")}`,e[t])}},Z=new WeakSet,$e=function(e){this[c].ccall("wasm_set_request_body",null,[y],[e]),this[c].ccall("wasm_set_content_length",null,[C],[new TextEncoder().encode(e).length])},Q=new WeakSet,Ie=function(e){this[c].ccall("wasm_set_path_translated",null,[y],[e])},X=new WeakSet,Oe=function(){for(const e in a(this,_))this[c].ccall("wasm_add_SERVER_entry",null,[y,y],[e,a(this,_)[e]])},ee=new WeakSet,Ne=function(e){const{key:t,name:n,type:s,data:i}=e,o=`/tmp/${Math.random().toFixed(20)}`;this.writeFile(o,i);const l=0;this[c].ccall("wasm_add_uploaded_file",null,[y,y,y,y,C,C],[t,n,s,o,l,i.byteLength])},te=new WeakSet,qe=function(e){this[c].ccall("wasm_set_php_code",null,[y],[e])},re=new WeakSet,De=async function(){var i;let e,t;try{e=await new Promise((o,l)=>{var f;t=h=>{const E=new Error("Rethrown");E.cause=h.error,E.betterMessage=h.message,l(E)},(f=a(this,k))==null||f.addEventListener("error",t);const d=this[c].ccall("wasm_sapi_handle_request",C,[],[],{async:!0});return d instanceof Promise?d.then(o,l):o(d)})}catch(o){for(const h in this)typeof this[h]=="function"&&(this[h]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=Ve();const l=o,d="betterMessage"in l?l.betterMessage:l.message,f=new Error(d);throw f.cause=l,f}finally{(i=a(this,k))==null||i.removeEventListener("error",t),p(this,_,{})}const{headers:n,httpStatusCode:s}=m(this,G,Ce).call(this);return new T(s,n,this.readFileAsBuffer("/tmp/stdout"),this.readFileAsText("/tmp/stderr"),e)};S([g('Could not create directory "{path}"')],w.prototype,"mkdir",1);S([g('Could not create directory "{path}"')],w.prototype,"mkdirTree",1);S([g('Could not read "{path}"')],w.prototype,"readFileAsText",1);S([g('Could not read "{path}"')],w.prototype,"readFileAsBuffer",1);S([g('Could not write to "{path}"')],w.prototype,"writeFile",1);S([g('Could not unlink "{path}"')],w.prototype,"unlink",1);S([g('Could not remove directory "{path}"')],w.prototype,"rmdir",1);S([g('Could not list files in "{path}"')],w.prototype,"listFiles",1);S([g('Could not stat "{path}"')],w.prototype,"isDir",1);S([g('Could not stat "{path}"')],w.prototype,"fileExists",1);function Me(r){const e={};for(const t in r)e[t.toLowerCase()]=r[t];return e}function je(r){return!(r instanceof w)}function vt(r){return!je(r)}exports.BasePHP=w;exports.DEFAULT_BASE_URL=ve;exports.LatestSupportedPHPVersion=ct;exports.PHPBrowser=Re;exports.PHPRequestHandler=xe;exports.PHPResponse=T;exports.SupportedPHPExtensionBundles=ht;exports.SupportedPHPExtensionsList=Ee;exports.SupportedPHPVersions=ce;exports.SupportedPHPVersionsList=ut;exports.UnhandledRejectionsTarget=Pe;exports.__private__dont__use=c;exports.ensurePathPrefix=_e;exports.isExitCodeZero=ge;exports.isLocalPHP=je;exports.isRemotePHP=vt;exports.iterateFiles=at;exports.loadPHPRuntime=Pt;exports.removePathPrefix=oe;exports.rethrowFileSystemError=g;exports.toRelativeUrl=ie;exports.writeFilesStreamToPhp=lt;
|
package/index.js
CHANGED
|
@@ -36,7 +36,7 @@ typeof Blob.prototype.text > "u" && (Blob.prototype.text = function() {
|
|
|
36
36
|
function Le() {
|
|
37
37
|
const r = new Uint8Array([1, 2, 3, 4]), t = new File([r], "test").stream();
|
|
38
38
|
try {
|
|
39
|
-
return t.getReader({ mode: "byob" }),
|
|
39
|
+
return t.getReader({ mode: "byob" }), !0;
|
|
40
40
|
} catch {
|
|
41
41
|
return !1;
|
|
42
42
|
}
|
|
@@ -189,8 +189,8 @@ CLI option:
|
|
|
189
189
|
`, ce = "\x1B[41m", We = "\x1B[1m", ue = "\x1B[0m", he = "\x1B[K";
|
|
190
190
|
let de = !1;
|
|
191
191
|
function ze(r) {
|
|
192
|
-
if (!de) {
|
|
193
|
-
|
|
192
|
+
if (!de && (de = !0, !(r != null && r.trim().startsWith("Program terminated with exit")))) {
|
|
193
|
+
console.log(`${ce}
|
|
194
194
|
${he}
|
|
195
195
|
${We} WASM ERROR${ue}${ce}`);
|
|
196
196
|
for (const e of r.split(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@php-wasm/universal",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.6",
|
|
4
4
|
"description": "PHP.wasm – emscripten bindings for PHP",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
"main": "./index.cjs",
|
|
37
37
|
"module": "./index.js",
|
|
38
38
|
"license": "GPL-2.0-or-later",
|
|
39
|
-
"gitHead": "
|
|
39
|
+
"gitHead": "72e190ebb407051ccb5ef544e2a62018395395a0",
|
|
40
40
|
"engines": {
|
|
41
41
|
"node": ">=18.18.2",
|
|
42
42
|
"npm": ">=8.11.0"
|