Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@php-wasm/cli

Package Overview
Dependencies
Maintainers
3
Versions
134
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@php-wasm/cli - npm Package Compare versions

Comparing version 0.1.56 to 0.1.58

10

main.js

@@ -1,2 +0,2 @@

import{existsSync as I,writeFileSync as L}from"fs";import{rootCertificates as B}from"tls";import{NodePHP as M}from"@php-wasm/node";const q="modulepreload",D=function(s){return"/"+s},S={},W=function(e,t,r){if(!t||t.length===0)return e();const o=document.getElementsByTagName("link");return Promise.all(t.map(n=>{if(n=D(n),n in S)return;S[n]=!0;const i=n.endsWith(".css"),l=i?'[rel="stylesheet"]':"";if(!!r)for(let d=o.length-1;d>=0;d--){const y=o[d];if(y.href===n&&(!i||y.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${n}"]${l}`))return;const c=document.createElement("link");if(c.rel=i?"stylesheet":q,i||(c.as="script",c.crossOrigin=""),c.href=n,document.head.appendChild(c),i)return new Promise((d,y)=>{c.addEventListener("load",d),c.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${n}`)))})})).then(()=>e())},R=Symbol("error"),x=Symbol("message");class E extends Event{constructor(e,t={}){super(e),this[R]=t.error===void 0?null:t.error,this[x]=t.message===void 0?"":t.message}get error(){return this[R]}get message(){return this[x]}}Object.defineProperty(E.prototype,"error",{enumerable:!0});Object.defineProperty(E.prototype,"message",{enumerable:!0});const j=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:E;class G 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 z(s){s.asm={...s.asm};const e=new G;for(const t in s.asm)if(typeof s.asm[t]=="function"){const r=s.asm[t];s.asm[t]=function(...o){try{return r(...o)}catch(n){if(!(n instanceof Error))throw n;if("exitCode"in n&&n?.exitCode===0)return;const i=Y(n,s.lastAsyncifyStackSource?.stack);if(s.lastAsyncifyStackSource&&(n.cause=s.lastAsyncifyStackSource),!e.hasListeners())throw Q(i),n;e.dispatchEvent(new j("error",{error:n,message:i}))}}}return e}let b=[];function V(){return b}function Y(s,e){if(s.message==="unreachable"){let t=J;e||(t+=`
import{existsSync as I,writeFileSync as L}from"fs";import{rootCertificates as B}from"tls";import{NodePHP as M}from"@php-wasm/node";const q="modulepreload",D=function(s){return"/"+s},S={},W=function(e,t,r){if(!t||t.length===0)return e();const n=document.getElementsByTagName("link");return Promise.all(t.map(o=>{if(o=D(o),o in S)return;S[o]=!0;const i=o.endsWith(".css"),l=i?'[rel="stylesheet"]':"";if(!!r)for(let d=n.length-1;d>=0;d--){const y=n[d];if(y.href===o&&(!i||y.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${o}"]${l}`))return;const c=document.createElement("link");if(c.rel=i?"stylesheet":q,i||(c.as="script",c.crossOrigin=""),c.href=o,document.head.appendChild(c),i)return new Promise((d,y)=>{c.addEventListener("load",d),c.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${o}`)))})})).then(()=>e())},R=Symbol("error"),x=Symbol("message");class E extends Event{constructor(e,t={}){super(e),this[R]=t.error===void 0?null:t.error,this[x]=t.message===void 0?"":t.message}get error(){return this[R]}get message(){return this[x]}}Object.defineProperty(E.prototype,"error",{enumerable:!0});Object.defineProperty(E.prototype,"message",{enumerable:!0});const j=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:E;class G 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 z(s){s.asm={...s.asm};const e=new G;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;if("exitCode"in o&&o?.exitCode===0)return;const i=Y(o,s.lastAsyncifyStackSource?.stack);if(s.lastAsyncifyStackSource&&(o.cause=s.lastAsyncifyStackSource),!e.hasListeners())throw Q(i),o;e.dispatchEvent(new j("error",{error:o,message:i}))}}}return e}let b=[];function V(){return b}function Y(s,e){if(s.message==="unreachable"){let t=J;e||(t+=`

@@ -35,8 +35,8 @@ This stack trace is lacking. For a better one initialize

`))console.log(`${C} ${e} `);console.log(`${T}`)}}function X(s){try{const e=s.split(`
`).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 w{constructor(e,t,r,o="",n=0){this.httpStatusCode=e,this.headers=t,this.bytes=r,this.exitCode=n,this.errors=o}static fromRawData(e){return new w(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 A=["8.2","8.1","8.0","7.4","7.3","7.2","7.1","7.0","5.6"],Z=A[0],ee=A;class te{#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 o=new URL(r.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:o.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("="),o=t.substring(0,r),n=t.substring(r+1).split(";")[0];this.#e[o]=n}catch(r){console.error(r)}}#r(){const e=[];for(const t in this.#e)e.push(`${t}=${this.#e[t]}`);return e.join("; ")}}class re{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 return this._running++,()=>{this._running--,this.queue.length>0&&this.queue.shift()()}}async run(e){const t=await this.acquire();try{return await e()}finally{t()}}}const se="http://example.com";function H(s){return s.toString().substring(s.origin.length)}function U(s,e){return!e||!s.startsWith(e)?s:s.substring(e.length)}function ne(s,e){return!e||s.startsWith(e)?s:e+s}class oe{#e;#t;#s;#r;#o;#n;#i;#a;#l;constructor(e,t={}){this.#a=new re({concurrency:1});const{documentRoot:r="/www/",absoluteUrl:o=typeof location=="object"?location?.href:"",isStaticFilePath:n=()=>!1}=t;this.php=e,this.#e=r,this.#l=n;const i=new URL(o);this.#s=i.hostname,this.#r=i.port?Number(i.port):i.protocol==="https:"?443:80,this.#t=(i.protocol||"").replace(":","");const l=this.#r!==443&&this.#r!==80;this.#o=[this.#s,l?`:${this.#r}`:""].join(""),this.#n=i.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)),H(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:se),o=U(r.pathname,this.#n);return this.#l(o)?this.#c(o):await this.#h(e,r)}#c(e){const t=`${this.#e}${e}`;if(!this.php.fileExists(t))return new w(404,{},new TextEncoder().encode("404 File not found"));const r=this.php.readFileAsBuffer(t);return new w(200,{"content-length":[`${r.byteLength}`],"content-type":[ae(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},r)}async#h(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 o="GET";const n={host:this.#o,...N(e.headers||{})},i=[];if(e.files&&Object.keys(e.files).length){o="POST";for(const c in e.files){const d=e.files[c];i.push({key:c,name:d.name,type:d.type,data:new Uint8Array(await d.arrayBuffer())})}n["content-type"]?.startsWith("multipart/form-data")&&(e.formData=ie(e.body||""),n["content-type"]="application/x-www-form-urlencoded",delete e.body)}let l;e.formData!==void 0?(o="POST",n["content-type"]=n["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 w(404,{},new TextEncoder().encode("404 File not found"))}return await this.php.run({relativeUri:ne(H(t),this.#n),protocol:this.#t,method:e.method||o,body:l,fileInfos:i,scriptPath:u,headers:n})}finally{r()}}#u(e){let t=U(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 ie(s){const e={},t=s.match(/--(.*)\r\n/);if(!t)return e;const r=t[1],o=s.split(`--${r}`);return o.shift(),o.pop(),o.forEach(n=>{const i=n.indexOf(`\r
`).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 w{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 w(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 $=["8.2","8.1","8.0","7.4","7.3","7.2","7.1","7.0","5.6"],Z=$[0],ee=$;class te{#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 re{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 return this._running++,()=>{this._running--,this.queue.length>0&&this.queue.shift()()}}async run(e){const t=await this.acquire();try{return await e()}finally{t()}}}const se="http://example.com";function H(s){return s.toString().substring(s.origin.length)}function U(s,e){return!e||!s.startsWith(e)?s:s.substring(e.length)}function ne(s,e){return!e||s.startsWith(e)?s:e+s}class oe{#e;#t;#s;#r;#o;#n;#i;#a;#l;constructor(e,t={}){this.#a=new re({concurrency:1});const{documentRoot:r="/www/",absoluteUrl:n=typeof location=="object"?location?.href:"",isStaticFilePath:o=()=>!1}=t;this.php=e,this.#e=r,this.#l=o;const i=new URL(n);this.#s=i.hostname,this.#r=i.port?Number(i.port):i.protocol==="https:"?443:80,this.#t=(i.protocol||"").replace(":","");const l=this.#r!==443&&this.#r!==80;this.#o=[this.#s,l?`:${this.#r}`:""].join(""),this.#n=i.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)),H(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:se),n=U(r.pathname,this.#n);return this.#l(n)?this.#c(n):await this.#h(e,r)}#c(e){const t=`${this.#e}${e}`;if(!this.php.fileExists(t))return new w(404,{},new TextEncoder().encode("404 File not found"));const r=this.php.readFileAsBuffer(t);return new w(200,{"content-length":[`${r.byteLength}`],"content-type":[ae(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},r)}async#h(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,...A(e.headers||{})},i=[];if(e.files&&Object.keys(e.files).length){n="POST";for(const c in e.files){const d=e.files[c];i.push({key:c,name:d.name,type:d.type,data:new Uint8Array(await d.arrayBuffer())})}o["content-type"]?.startsWith("multipart/form-data")&&(e.formData=ie(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 w(404,{},new TextEncoder().encode("404 File not found"))}return await this.php.run({relativeUri:ne(H(t),this.#n),protocol:this.#t,method:e.method||n,body:l,fileInfos:i,scriptPath:u,headers:o})}finally{r()}}#u(e){let t=U(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 ie(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
\r
`),l=n.substring(0,i).trim(),u=n.substring(i+4).trim(),c=l.match(/name="([^"]+)"/);if(c){const d=c[1];e[d]=u}}),e}function ae(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"}}const O={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,o){const n=o.value;o.value=function(...i){try{return n.apply(this,i)}catch(l){const u=typeof l=="object"?l?.errno:null;if(u in O){const c=O[u],d=typeof i[0]=="string"?i[0]:null,y=d!==null?s.replaceAll("{path}",d):s;throw new Error(`${y}: ${c}`,{cause:l})}throw l}}}}const le=[];function ce(s){return le[s]}(function(){return typeof process<"u"&&process.release?.name==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();var he=Object.defineProperty,ue=Object.getOwnPropertyDescriptor,f=(s,e,t,r)=>{for(var o=r>1?void 0:r?ue(e,t):e,n=s.length-1,i;n>=0;n--)(i=s[n])&&(o=(r?i(e,t,o):i(o))||o);return r&&o&&he(e,t,o),o};const h="string",g="number",a=Symbol("__private__dont__use");class m{constructor(e,t){this.#e=[],this.#t=!1,this.#s=null,this.#r={},e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new te(new oe(this,t)))}#e;#t;#s;#r;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=ce(e);if(!t)throw new Error("Invalid PHP runtime id.");this[a]=t,this.#s=z(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.#o(),this.#t=!0),this.#u(e.scriptPath||""),this.#i(e.relativeUri||""),this.#l(e.method||"GET");const{host:t,...r}={host:"example.com:443",...N(e.headers||{})};if(this.#a(t,e.protocol||"http"),this.#c(r),e.body&&this.#h(e.body),e.fileInfos)for(const o of e.fileInfos)this.#p(o);return e.code&&this.#f(" ?>"+e.code),this.#d(),await this.#m()}#o(){if(this.#e.length>0){const e=this.#e.map(([t,r])=>`${t}=${r}`).join(`
`),l=o.substring(0,i).trim(),u=o.substring(i+4).trim(),c=l.match(/name="([^"]+)"/);if(c){const d=c[1];e[d]=u}}),e}function ae(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"}}const O={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 O){const c=O[u],d=typeof i[0]=="string"?i[0]:null,y=d!==null?s.replaceAll("{path}",d):s;throw new Error(`${y}: ${c}`,{cause:l})}throw l}}}}const le=[];function ce(s){return le[s]}(function(){return typeof process<"u"&&process.release?.name==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();var he=Object.defineProperty,ue=Object.getOwnPropertyDescriptor,f=(s,e,t,r)=>{for(var n=r>1?void 0:r?ue(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&&he(e,t,n),n};const h="string",g="number",a=Symbol("__private__dont__use");class m{constructor(e,t){this.#e=[],this.#t=!1,this.#s=null,this.#r={},e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new te(new oe(this,t)))}#e;#t;#s;#r;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=ce(e);if(!t)throw new Error("Invalid PHP runtime id.");this[a]=t,this.#s=z(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.#o(),this.#t=!0),this.#u(e.scriptPath||""),this.#i(e.relativeUri||""),this.#l(e.method||"GET");const{host:t,...r}={host:"example.com:443",...A(e.headers||{})};if(this.#a(t,e.protocol||"http"),this.#c(r),e.body&&this.#h(e.body),e.fileInfos)for(const n of e.fileInfos)this.#p(n);return e.code&&this.#f(" ?>"+e.code),this.#d(),await this.#m()}#o(){if(this.#e.length>0){const e=this.#e.map(([t,r])=>`${t}=${r}`).join(`
`)+`
`;this[a].ccall("wasm_set_phpini_entries",null,[h],[e])}this[a].ccall("php_wasm_init",null,[],[])}#n(){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 o of t.headers){if(!o.includes(": "))continue;const n=o.indexOf(": "),i=o.substring(0,n).toLowerCase(),l=o.substring(n+2);i in r||(r[i]=[]),r[i].push(l)}return{headers:r,httpStatusCode:t.status}}#i(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])}}#a(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")}#l(e){this[a].ccall("wasm_set_request_method",null,[h],[e])}#c(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)this.addServerGlobalEntry(`HTTP_${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])}#u(e){this[a].ccall("wasm_set_path_translated",null,[h],[e])}addServerGlobalEntry(e,t){this.#r[e]=t}#d(){for(const e in this.#r)this[a].ccall("wasm_add_SERVER_entry",null,[h,h],[e,this.#r[e]])}#p(e){const{key:t,name:r,type:o,data:n}=e,i=`/tmp/${Math.random().toFixed(20)}`;this.writeFile(i,n);const l=0;this[a].ccall("wasm_add_uploaded_file",null,[h,h,h,h,g,g],[t,r,o,i,l,n.byteLength])}#f(e){this[a].ccall("wasm_set_php_code",null,[h],[e])}async#m(){let e,t;try{e=await new Promise((n,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(n,i):n(l)})}catch(n){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=V();const i=n,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:o}=this.#n();return new w(o,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 o=`${e}/${r}`;this.isDir(o)?this.rmdir(o,t):this.unlink(o)}),this[a].FS.rmdir(e)}listFiles(e){if(!this.fileExists(e))return[];try{return this[a].FS.readdir(e).filter(t=>t!=="."&&t!=="..")}catch(t){return console.error(t,{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}"')],m.prototype,"mkdir",1);f([p('Could not create directory "{path}"')],m.prototype,"mkdirTree",1);f([p('Could not read "{path}"')],m.prototype,"readFileAsText",1);f([p('Could not read "{path}"')],m.prototype,"readFileAsBuffer",1);f([p('Could not write to "{path}"')],m.prototype,"writeFile",1);f([p('Could not unlink "{path}"')],m.prototype,"unlink",1);f([p('Could not move "{path}"')],m.prototype,"mv",1);f([p('Could not remove directory "{path}"')],m.prototype,"rmdir",1);f([p('Could not list files in "{path}"')],m.prototype,"listFiles",1);f([p('Could not stat "{path}"')],m.prototype,"isDir",1);f([p('Could not stat "{path}"')],m.prototype,"fileExists",1);function N(s){const e={};for(const t in s)e[t.toLowerCase()]=s[t];return e}let P=process.argv.slice(2);P.length||(P=["--help"]);const v=new URL("ca-bundle.crt",(import.meta||{}).url).pathname;I(v)||L(v,B.join(`
`));P.unshift("-d",`openssl.cafile=${v}`);const de=await W(()=>import("./assets/php-e1f9edd4.js"),[]),_=process.env.PHP||Z;if(!ee.includes(_))throw new Error(`Unsupported PHP version ${_}`);const $=await M.load(_,{emscriptenOptions:{ENV:{...process.env,TERM:"xterm"}}});$.useHostFilesystem();const pe=P.some(s=>s.startsWith("-c"));pe||P.unshift("-c",de);$.cli(["php",...P]).catch(s=>{throw s.name==="ExitStatus"&&process.exit(s.status===void 0?1:s.status),s});
`;this[a].ccall("wasm_set_phpini_entries",null,[h],[e])}this[a].ccall("php_wasm_init",null,[],[])}#n(){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}}#i(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])}}#a(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")}#l(e){this[a].ccall("wasm_set_request_method",null,[h],[e])}#c(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])}#u(e){this[a].ccall("wasm_set_path_translated",null,[h],[e])}addServerGlobalEntry(e,t){this.#r[e]=t}#d(){for(const e in this.#r)this[a].ccall("wasm_add_SERVER_entry",null,[h,h],[e,this.#r[e]])}#p(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])}#f(e){this[a].ccall("wasm_set_php_code",null,[h],[e])}async#m(){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=V();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.#n();return new w(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}"')],m.prototype,"mkdir",1);f([p('Could not create directory "{path}"')],m.prototype,"mkdirTree",1);f([p('Could not read "{path}"')],m.prototype,"readFileAsText",1);f([p('Could not read "{path}"')],m.prototype,"readFileAsBuffer",1);f([p('Could not write to "{path}"')],m.prototype,"writeFile",1);f([p('Could not unlink "{path}"')],m.prototype,"unlink",1);f([p('Could not move "{path}"')],m.prototype,"mv",1);f([p('Could not remove directory "{path}"')],m.prototype,"rmdir",1);f([p('Could not list files in "{path}"')],m.prototype,"listFiles",1);f([p('Could not stat "{path}"')],m.prototype,"isDir",1);f([p('Could not stat "{path}"')],m.prototype,"fileExists",1);function A(s){const e={};for(const t in s)e[t.toLowerCase()]=s[t];return e}let P=process.argv.slice(2);P.length||(P=["--help"]);const v=new URL("ca-bundle.crt",(import.meta||{}).url).pathname;I(v)||L(v,B.join(`
`));P.unshift("-d",`openssl.cafile=${v}`);const de=await W(()=>import("./assets/php-e1f9edd4.js"),[]),_=process.env.PHP||Z;if(!ee.includes(_))throw new Error(`Unsupported PHP version ${_}`);const N=await M.load(_,{emscriptenOptions:{ENV:{...process.env,TERM:"xterm"}}});N.useHostFilesystem();const pe=P.some(s=>s.startsWith("-c"));pe||P.unshift("-c",de);N.cli(["php",...P]).catch(s=>{throw s.name==="ExitStatus"&&process.exit(s.status===void 0?1:s.status),s});
{
"name": "@php-wasm/cli",
"version": "0.1.56",
"version": "0.1.58",
"description": "PHP.wasm CLI for node.js",

@@ -26,9 +26,9 @@ "repository": {

"bin": "cli.js",
"gitHead": "af3583eb7c6644a9859ea4782702c6e2c3474821",
"gitHead": "dbc77ed4c0b0a2625cfbe08722fade036c69a425",
"dependencies": {
"comlink": "^4.4.1",
"ws": "8.13.0",
"@php-wasm/universal": "0.1.56",
"@php-wasm/node": "0.1.56"
"@php-wasm/universal": "0.1.58",
"@php-wasm/node": "0.1.58"
}
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc