@php-wasm/universal 1.0.11 → 1.0.13
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 +3 -3
- package/index.js +1 -1
- package/package.json +7 -7
package/index.cjs
CHANGED
|
@@ -32,7 +32,7 @@ CLI option:
|
|
|
32
32
|
${eol}
|
|
33
33
|
${bold} WASM ERROR${reset}${redBg}`);for(const e of t.split(`
|
|
34
34
|
`))logger.logger.log(`${eol} ${e} `);logger.logger.log(`${reset}`)}}function extractPHPFunctionsFromStack(t){try{const e=t.split(`
|
|
35
|
-
`).slice(1).map(r=>{const s=r.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:r.includes("wasm://")}}).filter(({fn:r,isWasm:s})=>s&&!r.startsWith("dynCall_")&&!r.startsWith("invoke_")).map(({fn:r})=>r);return Array.from(new Set(e))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(e,r,s){super(e),this.response=r,this.source=s}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php";var x,g,P,_,E,T,J,I,Y,C,Z,A,K,N,X,M,Q,
|
|
35
|
+
`).slice(1).map(r=>{const s=r.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:r.includes("wasm://")}}).filter(({fn:r,isWasm:s})=>s&&!r.startsWith("dynCall_")&&!r.startsWith("invoke_")).map(({fn:r})=>r);return Array.from(new Set(e))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(e,r,s){super(e),this.response=r,this.source=s}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php";var x,g,P,_,E,T,J,I,Y,C,Z,A,K,N,X,M,Q,U,ee,j,te,L,re,q,se,b,G,$,ie,O,ne,B,oe;class PHP{constructor(t){u(this,T);u(this,I);u(this,C);u(this,A);u(this,N);u(this,M);u(this,U);u(this,j);u(this,L);u(this,q);u(this,b);u(this,$);u(this,O);u(this,B);u(this,x,void 0);u(this,g,void 0);u(this,P,void 0);u(this,_,void 0);u(this,E,void 0);h(this,g,!1),h(this,P,null),h(this,_,new Map),h(this,E,[]),this.semaphore=new util.Semaphore({concurrency:1}),t!==void 0&&this.initializeRuntime(t)}addEventListener(t,e){p(this,_).has(t)||p(this,_).set(t,new Set),p(this,_).get(t).add(e)}removeEventListener(t,e){var r;(r=p(this,_).get(t))==null||r.delete(e)}dispatchEvent(t){const e=p(this,_).get(t.type);if(e)for(const r of e)r(t)}onMessage(t){p(this,E).push(t)}async setSpawnHandler(handler){typeof handler=="string"&&(handler=util.createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}pathToInternalUrl(t){return this.requestHandler.pathToInternalUrl(t)}internalUrlToPath(t){return this.requestHandler.internalUrlToPath(t)}initializeRuntime(t){if(this[__private__dont__use])throw new Error("PHP runtime already initialized.");const e=getLoadedRuntime(t);if(!e)throw new Error("Invalid PHP runtime id.");this[__private__dont__use]=e,this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[PHP_INI_PATH]),this.fileExists(PHP_INI_PATH)||this.writeFile(PHP_INI_PATH,["auto_prepend_file="+AUTO_PREPEND_SCRIPT,"memory_limit=256M","ignore_repeated_errors = 1","error_reporting = E_ALL","display_errors = 1","html_errors = 1","display_startup_errors = On","log_errors = 1","always_populate_raw_post_data = -1","upload_max_filesize = 2000M","post_max_size = 2000M","allow_url_fopen = On","allow_url_include = Off","session.save_path = /home/web_user","implicit_flush = 1","output_buffering = 0","max_execution_time = 0","max_input_time = -1"].join(`
|
|
36
36
|
`)),this.fileExists(AUTO_PREPEND_SCRIPT)||this.writeFile(AUTO_PREPEND_SCRIPT,`<?php
|
|
37
37
|
// Define constants set via defineConstant() calls
|
|
38
38
|
if(file_exists('/internal/shared/consts.json')) {
|
|
@@ -47,10 +47,10 @@ ${bold} WASM ERROR${reset}${redBg}`);for(const e of t.split(`
|
|
|
47
47
|
foreach (glob('/internal/shared/preload/*.php') as $file) {
|
|
48
48
|
require_once $file;
|
|
49
49
|
}
|
|
50
|
-
`),e.onMessage=async r=>{for(const s of p(this,E)){const i=await s(r);if(i)return i}return""},h(this,P,improveWASMErrorReporting(e)),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(t){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[t])!==0)throw new Error("Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?");h(this,x,t)}chdir(t){this[__private__dont__use].FS.chdir(t)}async request(t){if(logger.logger.warn("PHP.request() is deprecated. Please use new PHPRequestHandler() instead."),!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(t)}async run(t){const e=await this.semaphore.acquire();let r;try{if(p(this,g)||(d(this,I,Y).call(this),h(this,g,!0)),t.scriptPath&&!this.fileExists(t.scriptPath))throw new Error(`The script path "${t.scriptPath}" does not exist.`);d(this,A,K).call(this,t.relativeUri||""),d(this,U,te).call(this,t.method||"GET");const s=normalizeHeaders(t.headers||{}),i=s.host||"example.com:443",n=d(this,j,ee).call(this,i,t.protocol||"http");if(d(this,N,X).call(this,i),d(this,M,Q).call(this,n),d(this,L,re).call(this,s),t.body&&(r=d(this,q,se).call(this,t.body)),typeof t.code=="string")this.writeFile("/internal/eval.php",t.code),d(this,b,G).call(this,"/internal/eval.php");else if(typeof t.scriptPath=="string")d(this,b,G).call(this,t.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const o=d(this,T,J).call(this,t.$_SERVER,s,n);for(const c in o)d(this,$,ie).call(this,c,o[c]);const a=t.env||{};for(const c in a)d(this,O,ne).call(this,c,a[c]);const l=await d(this,B,oe).call(this);if(l.exitCode!==0){logger.logger.warn("PHP.run() output was:",l.text);const c=new PHPExecutionFailureError(`PHP.run() failed with exit code ${l.exitCode} and the following output: `+l.errors,l,"request");throw logger.logger.error(c),c}return l}catch(s){throw this.dispatchEvent({type:"request.error",error:s,source:s.source??"php-wasm"}),s}finally{try{r&&this[__private__dont__use].free(r)}finally{e(),this.dispatchEvent({type:"request.end"})}}}defineConstant(t,e){let r={};try{r=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...r,[t]:e}))}mkdir(t){return FSHelpers.mkdir(this[__private__dont__use].FS,t)}mkdirTree(t){return FSHelpers.mkdir(this[__private__dont__use].FS,t)}readFileAsText(t){return FSHelpers.readFileAsText(this[__private__dont__use].FS,t)}readFileAsBuffer(t){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,t)}writeFile(t,e){return FSHelpers.writeFile(this[__private__dont__use].FS,t,e)}unlink(t){return FSHelpers.unlink(this[__private__dont__use].FS,t)}mv(t,e){return FSHelpers.mv(this[__private__dont__use].FS,t,e)}rmdir(t,e={recursive:!0}){return FSHelpers.rmdir(this[__private__dont__use].FS,t,e)}listFiles(t,e={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,t,e)}isDir(t){return FSHelpers.isDir(this[__private__dont__use].FS,t)}isFile(t){return FSHelpers.isFile(this[__private__dont__use].FS,t)}symlink(t,e){return FSHelpers.symlink(this[__private__dont__use].FS,t,e)}isSymlink(t){return FSHelpers.isSymlink(this[__private__dont__use].FS,t)}readlink(t){return FSHelpers.readlink(this[__private__dont__use].FS,t)}realpath(t){return FSHelpers.realpath(this[__private__dont__use].FS,t)}fileExists(t){return FSHelpers.fileExists(this[__private__dont__use].FS,t)}hotSwapPHPRuntime(t,e){const r=this[__private__dont__use].FS;try{this.exit()}catch{}this.initializeRuntime(t),p(this,x)&&this.setSapiName(p(this,x)),e&©FS(r,this[__private__dont__use].FS,e)}async mount(t,e){return await e(this,this[__private__dont__use].FS,t)}async cli(t){for(const e of t)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[e]);try{return await this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}catch(e){if(isExitCodeZero(e))return 0;throw e}}setSkipShebang(t){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[t?1:0])}exit(t=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(t)}catch{}h(this,g,!1),h(this,P,null),delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}[Symbol.dispose](){p(this,g)&&this.exit(0)}}x=new WeakMap,g=new WeakMap,P=new WeakMap,_=new WeakMap,E=new WeakMap,T=new WeakSet,J=function(t,e,r){const s={...t||{}};s.HTTPS=s.HTTPS||r===443?"on":"off";for(const i in e){let n="HTTP_";["content-type","content-length"].includes(i.toLowerCase())&&(n=""),s[`${n}${i.toUpperCase().replace(/-/g,"_")}`]=e[i]}return s},I=new WeakSet,Y=function(){this[__private__dont__use].ccall("php_wasm_init",null,[],[])},C=new WeakSet,Z=function(){const t="/internal/headers.json";if(!this.fileExists(t))throw new Error("SAPI Error: Could not find response headers file.");const e=JSON.parse(this.readFileAsText(t)),r={};for(const s of e.headers){if(!s.includes(": "))continue;const i=s.indexOf(": "),n=s.substring(0,i).toLowerCase(),o=s.substring(i+2);n in r||(r[n]=[]),r[n].push(o)}return{headers:r,httpStatusCode:e.status}},A=new WeakSet,K=function(t){if(this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[t]),t.includes("?")){const e=t.substring(t.indexOf("?")+1);this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])}},N=new WeakSet,X=function(t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[t])},M=new WeakSet,Q=function(t){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[t])},j=new WeakSet,ee=function(t,e){let r;try{r=parseInt(new URL(t).port,10)}catch{}return(!r||isNaN(r)||r===80)&&(r=e==="https"?443:80),r},U=new WeakSet,te=function(t){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[t])},L=new WeakSet,re=function(t){t.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[t.cookie]),t["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[t["content-type"]]),t["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(t["content-length"],10)])},q=new WeakSet,se=function(t){let e,r;typeof t=="string"?(logger.logger.warn("Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"),r=this[__private__dont__use].lengthBytesUTF8(t),e=r+1):(r=t.byteLength,e=t.byteLength);const s=this[__private__dont__use].malloc(e);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof t=="string"?this[__private__dont__use].stringToUTF8(t,s,e+1):this[__private__dont__use].HEAPU8.set(t,s),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[s]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[r]),s},b=new WeakSet,G=function(t){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[t])},$=new WeakSet,ie=function(t,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[t,e])},O=new WeakSet,ne=function(t,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[t,e])},B=new WeakSet,oe=async function(){var i;let t,e;try{t=await new Promise((n,o)=>{var l;e=c=>{logger.logger.error(c),logger.logger.error(c.error);const y=new Error("Rethrown");y.cause=c.error,y.betterMessage=c.message,o(y)},(l=p(this,P))==null||l.addEventListener("error",e);const a=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return a instanceof Promise?a.then(n,o):n(a)})}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=getFunctionsMaybeMissingFromAsyncify();const o=n,a="betterMessage"in o?o.betterMessage:o.message,l=new Error(a);throw l.cause=o,logger.logger.error(l),l}finally{(i=p(this,P))==null||i.removeEventListener("error",e)}const{headers:r,httpStatusCode:s}=d(this,C,Z).call(this);return new PHPResponse(t===0?s:500,r,this.readFileAsBuffer("/internal/stdout"),this.readFileAsText("/internal/stderr"),t)};function normalizeHeaders(t){const e={};for(const r in t)e[r.toLowerCase()]=t[r];return e}function copyFS(t,e,r){let s;try{s=t.lookupPath(r)}catch{return}if(!("contents"in s.node))return;if(!t.isDir(s.node.mode)){e.writeFile(r,t.readFile(r));return}e.mkdirTree(r);const i=t.readdir(r).filter(n=>n!=="."&&n!=="..");for(const n of i)copyFS(t,e,util.joinPaths(r,n))}async function getPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));if(e===void 0)return r;const s={};for(const i of e)s[i]=r[i];return s}async function setPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));for(const[s,i]of Object.entries(e))i==null?delete r[s]:r[s]=i;await t.writeFile(PHP_INI_PATH,ini.stringify(r))}async function withPHPIniValues(t,e,r){const s=await t.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(t,e),await r()}finally{await t.writeFile(PHP_INI_PATH,s)}}class HttpCookieStore{constructor(){this.cookies={}}rememberCookiesFromResponseHeaders(e){if(e!=null&&e["set-cookie"])for(const r of e["set-cookie"])try{if(!r.includes("="))continue;const s=r.indexOf("="),i=r.substring(0,s),n=r.substring(s+1).split(";")[0];this.cookies[i]=n}catch(s){logger.logger.error(s)}}getCookieRequestHeader(){const e=[];for(const r in this.cookies)e.push(`${r}=${this.cookies[r]}`);return e.join("; ")}}function streamReadFileFromPHP(t,e){return new ReadableStream({async pull(r){const s=await t.readFileAsBuffer(e);r.enqueue(s),r.close()}})}async function*iteratePhpFiles(t,e,{relativePaths:r=!0,pathPrefix:s,exceptPaths:i=[]}={}){e=util.normalizePath(e);const n=[e];for(;n.length;){const o=n.pop();if(!o)return;const a=await t.listFiles(o);for(const l of a){const c=`${o}/${l}`;if(i.includes(c.substring(e.length+1)))continue;await t.isDir(c)?n.push(c):yield new streamCompression.StreamedFile(streamReadFileFromPHP(t,c),r?util.joinPaths(s||"",c.substring(e.length+1)):c)}}}function writeFilesStreamToPhp(t,e){return new WritableStream({async write(r){const s=util.joinPaths(e,r.name);r.type==="directory"?await t.mkdir(s):(await t.mkdir(util.dirname(s)),await t.writeFile(s,new Uint8Array(await r.arrayBuffer())))}})}class MaxPhpInstancesError extends Error{constructor(e){super(`Requested more concurrent PHP instances than the limit (${e}).`),this.name=this.constructor.name}}class PHPProcessManager{constructor(e){this.primaryIdle=!0,this.nextInstance=null,this.allInstances=[],this.maxPhpInstances=(e==null?void 0:e.maxPhpInstances)??5,this.phpFactory=e==null?void 0:e.phpFactory,this.primaryPhp=e==null?void 0:e.primaryPhp,this.semaphore=new util.Semaphore({concurrency:this.maxPhpInstances,timeout:(e==null?void 0:e.timeout)||5e3})}async getPrimaryPhp(){if(!this.phpFactory&&!this.primaryPhp)throw new Error("phpFactory or primaryPhp must be set before calling getPrimaryPhp().");if(!this.primaryPhp){const e=await this.spawn({isPrimary:!0});this.primaryPhp=e.php}return this.primaryPhp}async acquirePHPInstance(){if(this.primaryIdle)return this.primaryIdle=!1,{php:await this.getPrimaryPhp(),reap:()=>this.primaryIdle=!0};const e=this.nextInstance||this.spawn({isPrimary:!1});return this.semaphore.remaining>0?this.nextInstance=this.spawn({isPrimary:!1}):this.nextInstance=null,await e}spawn(e){if(e.isPrimary&&this.allInstances.length>0)throw new Error("Requested spawning a primary PHP instance when another primary instance already started spawning.");const r=this.doSpawn(e);this.allInstances.push(r);const s=()=>{this.allInstances=this.allInstances.filter(i=>i!==r)};return r.catch(i=>{throw s(),i}).then(i=>({...i,reap:()=>{s(),i.reap()}}))}async doSpawn(e){let r;try{r=await this.semaphore.acquire()}catch(s){throw s instanceof util.AcquireTimeoutError?new MaxPhpInstancesError(this.maxPhpInstances):s}try{const s=await this.phpFactory(e);return{php:s,reap(){s.exit(),r()}}}catch(s){throw r(),s}}async[Symbol.asyncDispose](){this.primaryPhp&&this.primaryPhp.exit(),await Promise.all(this.allInstances.map(e=>e.then(({reap:r})=>r())))}}const SupportedPHPVersions=["8.3","8.2","8.1","8.0","7.4","7.3","7.2","7.1","7.0"],LatestSupportedPHPVersion=SupportedPHPVersions[0],SupportedPHPVersionsList=SupportedPHPVersions,DEFAULT_BASE_URL="http://example.com";function toRelativeUrl(t){return t.toString().substring(t.origin.length)}function removePathPrefix(t,e){return!e||!t.startsWith(e)?t:t.substring(e.length)}function ensurePathPrefix(t,e){return!e||t.startsWith(e)?t:e+t}async function encodeAsMultipart(t){const e=`----${Math.random().toString(36).slice(2)}`,r=`multipart/form-data; boundary=${e}`,s=new TextEncoder,i=[];for(const[l,c]of Object.entries(t))i.push(`--${e}\r
|
|
50
|
+
`),e.onMessage=async r=>{for(const s of p(this,E)){const i=await s(r);if(i)return i}return""},h(this,P,improveWASMErrorReporting(e)),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(t){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[t])!==0)throw new Error("Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?");h(this,x,t)}chdir(t){this[__private__dont__use].FS.chdir(t)}async request(t){if(logger.logger.warn("PHP.request() is deprecated. Please use new PHPRequestHandler() instead."),!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(t)}async run(t){const e=await this.semaphore.acquire();let r;try{if(p(this,g)||(d(this,I,Y).call(this),h(this,g,!0)),t.scriptPath&&!this.fileExists(t.scriptPath))throw new Error(`The script path "${t.scriptPath}" does not exist.`);d(this,A,K).call(this,t.relativeUri||""),d(this,j,te).call(this,t.method||"GET");const s=normalizeHeaders(t.headers||{}),i=s.host||"example.com:443",n=d(this,U,ee).call(this,i,t.protocol||"http");if(d(this,N,X).call(this,i),d(this,M,Q).call(this,n),d(this,L,re).call(this,s),t.body&&(r=d(this,q,se).call(this,t.body)),typeof t.code=="string")this.writeFile("/internal/eval.php",t.code),d(this,b,G).call(this,"/internal/eval.php");else if(typeof t.scriptPath=="string")d(this,b,G).call(this,t.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const o=d(this,T,J).call(this,t.$_SERVER,s,n);for(const c in o)d(this,$,ie).call(this,c,o[c]);const a=t.env||{};for(const c in a)d(this,O,ne).call(this,c,a[c]);const l=await d(this,B,oe).call(this);if(l.exitCode!==0){logger.logger.warn("PHP.run() output was:",l.text);const c=new PHPExecutionFailureError(`PHP.run() failed with exit code ${l.exitCode} and the following output: `+l.errors,l,"request");throw logger.logger.error(c),c}return l}catch(s){throw this.dispatchEvent({type:"request.error",error:s,source:s.source??"php-wasm"}),s}finally{try{r&&this[__private__dont__use].free(r)}finally{e(),this.dispatchEvent({type:"request.end"})}}}defineConstant(t,e){let r={};try{r=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...r,[t]:e}))}mkdir(t){return FSHelpers.mkdir(this[__private__dont__use].FS,t)}mkdirTree(t){return FSHelpers.mkdir(this[__private__dont__use].FS,t)}readFileAsText(t){return FSHelpers.readFileAsText(this[__private__dont__use].FS,t)}readFileAsBuffer(t){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,t)}writeFile(t,e){return FSHelpers.writeFile(this[__private__dont__use].FS,t,e)}unlink(t){return FSHelpers.unlink(this[__private__dont__use].FS,t)}mv(t,e){return FSHelpers.mv(this[__private__dont__use].FS,t,e)}rmdir(t,e={recursive:!0}){return FSHelpers.rmdir(this[__private__dont__use].FS,t,e)}listFiles(t,e={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,t,e)}isDir(t){return FSHelpers.isDir(this[__private__dont__use].FS,t)}isFile(t){return FSHelpers.isFile(this[__private__dont__use].FS,t)}symlink(t,e){return FSHelpers.symlink(this[__private__dont__use].FS,t,e)}isSymlink(t){return FSHelpers.isSymlink(this[__private__dont__use].FS,t)}readlink(t){return FSHelpers.readlink(this[__private__dont__use].FS,t)}realpath(t){return FSHelpers.realpath(this[__private__dont__use].FS,t)}fileExists(t){return FSHelpers.fileExists(this[__private__dont__use].FS,t)}hotSwapPHPRuntime(t,e){const r=this[__private__dont__use].FS;try{this.exit()}catch{}this.initializeRuntime(t),p(this,x)&&this.setSapiName(p(this,x)),e&©FS(r,this[__private__dont__use].FS,e)}async mount(t,e){return await e(this,this[__private__dont__use].FS,t)}async cli(t){for(const e of t)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[e]);try{return await this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}catch(e){if(isExitCodeZero(e))return 0;throw e}}setSkipShebang(t){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[t?1:0])}exit(t=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(t)}catch{}h(this,g,!1),h(this,P,null),delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}[Symbol.dispose](){p(this,g)&&this.exit(0)}}x=new WeakMap,g=new WeakMap,P=new WeakMap,_=new WeakMap,E=new WeakMap,T=new WeakSet,J=function(t,e,r){const s={...t||{}};s.HTTPS=s.HTTPS||r===443?"on":"off";for(const i in e){let n="HTTP_";["content-type","content-length"].includes(i.toLowerCase())&&(n=""),s[`${n}${i.toUpperCase().replace(/-/g,"_")}`]=e[i]}return s},I=new WeakSet,Y=function(){this[__private__dont__use].ccall("php_wasm_init",null,[],[])},C=new WeakSet,Z=function(){const t="/internal/headers.json";if(!this.fileExists(t))throw new Error("SAPI Error: Could not find response headers file.");const e=JSON.parse(this.readFileAsText(t)),r={};for(const s of e.headers){if(!s.includes(": "))continue;const i=s.indexOf(": "),n=s.substring(0,i).toLowerCase(),o=s.substring(i+2);n in r||(r[n]=[]),r[n].push(o)}return{headers:r,httpStatusCode:e.status}},A=new WeakSet,K=function(t){if(this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[t]),t.includes("?")){const e=t.substring(t.indexOf("?")+1);this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])}},N=new WeakSet,X=function(t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[t])},M=new WeakSet,Q=function(t){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[t])},U=new WeakSet,ee=function(t,e){let r;try{r=parseInt(new URL(t).port,10)}catch{}return(!r||isNaN(r)||r===80)&&(r=e==="https"?443:80),r},j=new WeakSet,te=function(t){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[t])},L=new WeakSet,re=function(t){t.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[t.cookie]),t["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[t["content-type"]]),t["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(t["content-length"],10)])},q=new WeakSet,se=function(t){let e,r;typeof t=="string"?(logger.logger.warn("Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"),r=this[__private__dont__use].lengthBytesUTF8(t),e=r+1):(r=t.byteLength,e=t.byteLength);const s=this[__private__dont__use].malloc(e);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof t=="string"?this[__private__dont__use].stringToUTF8(t,s,e+1):this[__private__dont__use].HEAPU8.set(t,s),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[s]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[r]),s},b=new WeakSet,G=function(t){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[t])},$=new WeakSet,ie=function(t,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[t,e])},O=new WeakSet,ne=function(t,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[t,e])},B=new WeakSet,oe=async function(){var i;let t,e;try{t=await new Promise((n,o)=>{var l;e=c=>{logger.logger.error(c),logger.logger.error(c.error);const y=new Error("Rethrown");y.cause=c.error,y.betterMessage=c.message,o(y)},(l=p(this,P))==null||l.addEventListener("error",e);const a=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return a instanceof Promise?a.then(n,o):n(a)})}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=getFunctionsMaybeMissingFromAsyncify();const o=n,a="betterMessage"in o?o.betterMessage:o.message,l=new Error(a);throw l.cause=o,logger.logger.error(l),l}finally{(i=p(this,P))==null||i.removeEventListener("error",e)}const{headers:r,httpStatusCode:s}=d(this,C,Z).call(this);return new PHPResponse(t===0?s:500,r,this.readFileAsBuffer("/internal/stdout"),this.readFileAsText("/internal/stderr"),t)};function normalizeHeaders(t){const e={};for(const r in t)e[r.toLowerCase()]=t[r];return e}function copyFS(t,e,r){let s;try{s=t.lookupPath(r)}catch{return}if(!("contents"in s.node))return;if(!t.isDir(s.node.mode)){e.writeFile(r,t.readFile(r));return}e.mkdirTree(r);const i=t.readdir(r).filter(n=>n!=="."&&n!=="..");for(const n of i)copyFS(t,e,util.joinPaths(r,n))}async function getPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));if(e===void 0)return r;const s={};for(const i of e)s[i]=r[i];return s}async function setPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));for(const[s,i]of Object.entries(e))i==null?delete r[s]:r[s]=i;await t.writeFile(PHP_INI_PATH,ini.stringify(r))}async function withPHPIniValues(t,e,r){const s=await t.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(t,e),await r()}finally{await t.writeFile(PHP_INI_PATH,s)}}class HttpCookieStore{constructor(){this.cookies={}}rememberCookiesFromResponseHeaders(e){if(e!=null&&e["set-cookie"])for(const r of e["set-cookie"])try{if(!r.includes("="))continue;const s=r.indexOf("="),i=r.substring(0,s),n=r.substring(s+1).split(";")[0];this.cookies[i]=n}catch(s){logger.logger.error(s)}}getCookieRequestHeader(){const e=[];for(const r in this.cookies)e.push(`${r}=${this.cookies[r]}`);return e.join("; ")}}function streamReadFileFromPHP(t,e){return new ReadableStream({async pull(r){const s=await t.readFileAsBuffer(e);r.enqueue(s),r.close()}})}async function*iteratePhpFiles(t,e,{relativePaths:r=!0,pathPrefix:s,exceptPaths:i=[]}={}){e=util.normalizePath(e);const n=[e];for(;n.length;){const o=n.pop();if(!o)return;const a=await t.listFiles(o);for(const l of a){const c=`${o}/${l}`;if(i.includes(c.substring(e.length+1)))continue;await t.isDir(c)?n.push(c):yield new streamCompression.StreamedFile(streamReadFileFromPHP(t,c),r?util.joinPaths(s||"",c.substring(e.length+1)):c)}}}function writeFilesStreamToPhp(t,e){return new WritableStream({async write(r){const s=util.joinPaths(e,r.name);r.type==="directory"?await t.mkdir(s):(await t.mkdir(util.dirname(s)),await t.writeFile(s,new Uint8Array(await r.arrayBuffer())))}})}class MaxPhpInstancesError extends Error{constructor(e){super(`Requested more concurrent PHP instances than the limit (${e}).`),this.name=this.constructor.name}}class PHPProcessManager{constructor(e){this.primaryIdle=!0,this.nextInstance=null,this.allInstances=[],this.maxPhpInstances=(e==null?void 0:e.maxPhpInstances)??5,this.phpFactory=e==null?void 0:e.phpFactory,this.primaryPhp=e==null?void 0:e.primaryPhp,this.semaphore=new util.Semaphore({concurrency:this.maxPhpInstances,timeout:(e==null?void 0:e.timeout)||5e3})}async getPrimaryPhp(){if(!this.phpFactory&&!this.primaryPhp)throw new Error("phpFactory or primaryPhp must be set before calling getPrimaryPhp().");if(!this.primaryPhp){const e=await this.spawn({isPrimary:!0});this.primaryPhp=e.php}return this.primaryPhp}async acquirePHPInstance(){if(this.primaryIdle)return this.primaryIdle=!1,{php:await this.getPrimaryPhp(),reap:()=>this.primaryIdle=!0};const e=this.nextInstance||this.spawn({isPrimary:!1});return this.semaphore.remaining>0?this.nextInstance=this.spawn({isPrimary:!1}):this.nextInstance=null,await e}spawn(e){if(e.isPrimary&&this.allInstances.length>0)throw new Error("Requested spawning a primary PHP instance when another primary instance already started spawning.");const r=this.doSpawn(e);this.allInstances.push(r);const s=()=>{this.allInstances=this.allInstances.filter(i=>i!==r)};return r.catch(i=>{throw s(),i}).then(i=>({...i,reap:()=>{s(),i.reap()}}))}async doSpawn(e){let r;try{r=await this.semaphore.acquire()}catch(s){throw s instanceof util.AcquireTimeoutError?new MaxPhpInstancesError(this.maxPhpInstances):s}try{const s=await this.phpFactory(e);return{php:s,reap(){s.exit(),r()}}}catch(s){throw r(),s}}async[Symbol.asyncDispose](){this.primaryPhp&&this.primaryPhp.exit(),await Promise.all(this.allInstances.map(e=>e.then(({reap:r})=>r())))}}const SupportedPHPVersions=["8.3","8.2","8.1","8.0","7.4","7.3","7.2","7.1","7.0"],LatestSupportedPHPVersion=SupportedPHPVersions[0],SupportedPHPVersionsList=SupportedPHPVersions,DEFAULT_BASE_URL="http://example.com";function toRelativeUrl(t){return t.toString().substring(t.origin.length)}function removePathPrefix(t,e){return!e||!t.startsWith(e)?t:t.substring(e.length)}function ensurePathPrefix(t,e){return!e||t.startsWith(e)?t:e+t}async function encodeAsMultipart(t){const e=`----${Math.random().toString(36).slice(2)}`,r=`multipart/form-data; boundary=${e}`,s=new TextEncoder,i=[];for(const[l,c]of Object.entries(t))i.push(`--${e}\r
|
|
51
51
|
`),i.push(`Content-Disposition: form-data; name="${l}"`),c instanceof File&&i.push(`; filename="${c.name}"`),i.push(`\r
|
|
52
52
|
`),c instanceof File&&(i.push("Content-Type: application/octet-stream"),i.push(`\r
|
|
53
53
|
`)),i.push(`\r
|
|
54
54
|
`),c instanceof File?i.push(await fileToUint8Array(c)):i.push(c),i.push(`\r
|
|
55
55
|
`);i.push(`--${e}--\r
|
|
56
|
-
`);const n=i.reduce((l,c)=>l+c.length,0),o=new Uint8Array(n);let a=0;for(const l of i)o.set(typeof l=="string"?s.encode(l):l,a),a+=l.length;return{bytes:o,contentType:r}}function fileToUint8Array(t){return new Promise(e=>{const r=new FileReader;r.onload=()=>{e(new Uint8Array(r.result))},r.readAsArrayBuffer(t)})}const _default="application/octet-stream",asx="video/x-ms-asf",atom="application/atom+xml",avi="video/x-msvideo",avif="image/avif",bin="application/octet-stream",bmp="image/x-ms-bmp",cco="application/x-cocoa",css="text/css",data="application/octet-stream",deb="application/octet-stream",der="application/x-x509-ca-cert",dmg="application/octet-stream",doc="application/msword",docx="application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot="application/vnd.ms-fontobject",flv="video/x-flv",gif="image/gif",gz="application/gzip",hqx="application/mac-binhex40",htc="text/x-component",html="text/html",ico="image/x-icon",iso="application/octet-stream",jad="text/vnd.sun.j2me.app-descriptor",jar="application/java-archive",jardiff="application/x-java-archive-diff",jng="image/x-jng",jnlp="application/x-java-jnlp-file",jpg="image/jpeg",jpeg="image/jpeg",js="application/javascript",json="application/json",kml="application/vnd.google-earth.kml+xml",kmz="application/vnd.google-earth.kmz",m3u8="application/vnd.apple.mpegurl",m4a="audio/x-m4a",m4v="video/x-m4v",md="text/plain",mid="audio/midi",mml="text/mathml",mng="video/x-mng",mov="video/quicktime",mp3="audio/mpeg",mp4="video/mp4",mpeg="video/mpeg",msi="application/octet-stream",odg="application/vnd.oasis.opendocument.graphics",odp="application/vnd.oasis.opendocument.presentation",ods="application/vnd.oasis.opendocument.spreadsheet",odt="application/vnd.oasis.opendocument.text",ogg="audio/ogg",otf="font/otf",pdf="application/pdf",pl="application/x-perl",png="image/png",ppt="application/vnd.ms-powerpoint",pptx="application/vnd.openxmlformats-officedocument.presentationml.presentation",prc="application/x-pilot",ps="application/postscript",ra="audio/x-realaudio",rar="application/x-rar-compressed",rpm="application/x-redhat-package-manager",rss="application/rss+xml",rtf="application/rtf",run="application/x-makeself",sea="application/x-sea",sit="application/x-stuffit",svg="image/svg+xml",swf="application/x-shockwave-flash",tcl="application/x-tcl",tar="application/x-tar",tif="image/tiff",ts="video/mp2t",ttf="font/ttf",txt="text/plain",wasm="application/wasm",wbmp="image/vnd.wap.wbmp",webm="video/webm",webp="image/webp",wml="text/vnd.wap.wml",wmlc="application/vnd.wap.wmlc",wmv="video/x-ms-wmv",woff="font/woff",woff2="font/woff2",xhtml="application/xhtml+xml",xls="application/vnd.ms-excel",xlsx="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml="text/xml",xpi="application/x-xpinstall",xspf="application/xspf+xml",zip="application/zip",mimeTypes={_default,"3gpp":"video/3gpp","7z":"application/x-7z-compressed",asx,atom,avi,avif,bin,bmp,cco,css,data,deb,der,dmg,doc,docx,eot,flv,gif,gz,hqx,htc,html,ico,iso,jad,jar,jardiff,jng,jnlp,jpg,jpeg,js,json,kml,kmz,m3u8,m4a,m4v,md,mid,mml,mng,mov,mp3,mp4,mpeg,msi,odg,odp,ods,odt,ogg,otf,pdf,pl,png,ppt,pptx,prc,ps,ra,rar,rpm,rss,rtf,run,sea,sit,svg,swf,tcl,tar,tif,ts,ttf,txt,wasm,wbmp,webm,webp,wml,wmlc,wmv,woff,woff2,xhtml,xls,xlsx,xml,xpi,xspf,zip};var w,R,k,v,F,f,S,H,D,ae,z,le,W,ce;class PHPRequestHandler{constructor(e){u(this,D);u(this,z);u(this,W);u(this,w,void 0);u(this,R,void 0);u(this,k,void 0);u(this,v,void 0);u(this,F,void 0);u(this,f,void 0);u(this,S,void 0);u(this,H,void 0);const{documentRoot:r="/www/",absoluteUrl:s=typeof location=="object"?location==null?void 0:location.href:"",rewriteRules:i=[],getFileNotFoundAction:n=()=>({type:"404"})}=e;"processManager"in e?this.processManager=e.processManager:this.processManager=new PHPProcessManager({phpFactory:async l=>{const c=await e.phpFactory({...l,requestHandler:this});return c.requestHandler=this,c},maxPhpInstances:e.maxPhpInstances}),h(this,H,new HttpCookieStore),h(this,w,r);const o=new URL(s);h(this,k,o.hostname),h(this,v,o.port?Number(o.port):o.protocol==="https:"?443:80),h(this,R,(o.protocol||"").replace(":",""));const a=p(this,v)!==443&&p(this,v)!==80;h(this,F,[p(this,k),a?`:${p(this,v)}`:""].join("")),h(this,f,o.pathname.replace(/\/+$/,"")),h(this,S,[`${p(this,R)}://`,p(this,F),p(this,f)].join("")),this.rewriteRules=i,this.getFileNotFoundAction=n}async getPrimaryPhp(){return await this.processManager.getPrimaryPhp()}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const r=new URL(e);return r.pathname.startsWith(p(this,f))&&(r.pathname=r.pathname.slice(p(this,f).length)),toRelativeUrl(r)}get absoluteUrl(){return p(this,S)}get documentRoot(){return p(this,w)}async request(e){const r=
|
|
56
|
+
`);const n=i.reduce((l,c)=>l+c.length,0),o=new Uint8Array(n);let a=0;for(const l of i)o.set(typeof l=="string"?s.encode(l):l,a),a+=l.length;return{bytes:o,contentType:r}}function fileToUint8Array(t){return new Promise(e=>{const r=new FileReader;r.onload=()=>{e(new Uint8Array(r.result))},r.readAsArrayBuffer(t)})}const _default="application/octet-stream",asx="video/x-ms-asf",atom="application/atom+xml",avi="video/x-msvideo",avif="image/avif",bin="application/octet-stream",bmp="image/x-ms-bmp",cco="application/x-cocoa",css="text/css",data="application/octet-stream",deb="application/octet-stream",der="application/x-x509-ca-cert",dmg="application/octet-stream",doc="application/msword",docx="application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot="application/vnd.ms-fontobject",flv="video/x-flv",gif="image/gif",gz="application/gzip",hqx="application/mac-binhex40",htc="text/x-component",html="text/html",ico="image/x-icon",iso="application/octet-stream",jad="text/vnd.sun.j2me.app-descriptor",jar="application/java-archive",jardiff="application/x-java-archive-diff",jng="image/x-jng",jnlp="application/x-java-jnlp-file",jpg="image/jpeg",jpeg="image/jpeg",js="application/javascript",json="application/json",kml="application/vnd.google-earth.kml+xml",kmz="application/vnd.google-earth.kmz",m3u8="application/vnd.apple.mpegurl",m4a="audio/x-m4a",m4v="video/x-m4v",md="text/plain",mid="audio/midi",mml="text/mathml",mng="video/x-mng",mov="video/quicktime",mp3="audio/mpeg",mp4="video/mp4",mpeg="video/mpeg",msi="application/octet-stream",odg="application/vnd.oasis.opendocument.graphics",odp="application/vnd.oasis.opendocument.presentation",ods="application/vnd.oasis.opendocument.spreadsheet",odt="application/vnd.oasis.opendocument.text",ogg="audio/ogg",otf="font/otf",pdf="application/pdf",pl="application/x-perl",png="image/png",ppt="application/vnd.ms-powerpoint",pptx="application/vnd.openxmlformats-officedocument.presentationml.presentation",prc="application/x-pilot",ps="application/postscript",ra="audio/x-realaudio",rar="application/x-rar-compressed",rpm="application/x-redhat-package-manager",rss="application/rss+xml",rtf="application/rtf",run="application/x-makeself",sea="application/x-sea",sit="application/x-stuffit",svg="image/svg+xml",swf="application/x-shockwave-flash",tcl="application/x-tcl",tar="application/x-tar",tif="image/tiff",ts="video/mp2t",ttf="font/ttf",txt="text/plain",wasm="application/wasm",wbmp="image/vnd.wap.wbmp",webm="video/webm",webp="image/webp",wml="text/vnd.wap.wml",wmlc="application/vnd.wap.wmlc",wmv="video/x-ms-wmv",woff="font/woff",woff2="font/woff2",xhtml="application/xhtml+xml",xls="application/vnd.ms-excel",xlsx="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml="text/xml",xpi="application/x-xpinstall",xspf="application/xspf+xml",zip="application/zip",mimeTypes={_default,"3gpp":"video/3gpp","7z":"application/x-7z-compressed",asx,atom,avi,avif,bin,bmp,cco,css,data,deb,der,dmg,doc,docx,eot,flv,gif,gz,hqx,htc,html,ico,iso,jad,jar,jardiff,jng,jnlp,jpg,jpeg,js,json,kml,kmz,m3u8,m4a,m4v,md,mid,mml,mng,mov,mp3,mp4,mpeg,msi,odg,odp,ods,odt,ogg,otf,pdf,pl,png,ppt,pptx,prc,ps,ra,rar,rpm,rss,rtf,run,sea,sit,svg,swf,tcl,tar,tif,ts,ttf,txt,wasm,wbmp,webm,webp,wml,wmlc,wmv,woff,woff2,xhtml,xls,xlsx,xml,xpi,xspf,zip};var w,R,k,v,F,f,S,H,D,ae,z,le,W,ce;class PHPRequestHandler{constructor(e){u(this,D);u(this,z);u(this,W);u(this,w,void 0);u(this,R,void 0);u(this,k,void 0);u(this,v,void 0);u(this,F,void 0);u(this,f,void 0);u(this,S,void 0);u(this,H,void 0);const{documentRoot:r="/www/",absoluteUrl:s=typeof location=="object"?location==null?void 0:location.href:"",rewriteRules:i=[],getFileNotFoundAction:n=()=>({type:"404"})}=e;"processManager"in e?this.processManager=e.processManager:this.processManager=new PHPProcessManager({phpFactory:async l=>{const c=await e.phpFactory({...l,requestHandler:this});return c.requestHandler=this,c},maxPhpInstances:e.maxPhpInstances}),h(this,H,new HttpCookieStore),h(this,w,r);const o=new URL(s);h(this,k,o.hostname),h(this,v,o.port?Number(o.port):o.protocol==="https:"?443:80),h(this,R,(o.protocol||"").replace(":",""));const a=p(this,v)!==443&&p(this,v)!==80;h(this,F,[p(this,k),a?`:${p(this,v)}`:""].join("")),h(this,f,o.pathname.replace(/\/+$/,"")),h(this,S,[`${p(this,R)}://`,p(this,F),p(this,f)].join("")),this.rewriteRules=i,this.getFileNotFoundAction=n}async getPrimaryPhp(){return await this.processManager.getPrimaryPhp()}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const r=new URL(e);return r.pathname.startsWith(p(this,f))&&(r.pathname=r.pathname.slice(p(this,f).length)),toRelativeUrl(r)}get absoluteUrl(){return p(this,S)}get documentRoot(){return p(this,w)}async request(e){const r=URL.canParse(e.url),s=new URL(e.url.split("#")[0],r?void 0:DEFAULT_BASE_URL),i=applyRewriteRules(removePathPrefix(decodeURIComponent(s.pathname),p(this,f)),this.rewriteRules),n=await this.getPrimaryPhp();let o=util.joinPaths(p(this,w),i);if(n.isDir(o)){if(!o.endsWith("/"))return new PHPResponse(301,{Location:[`${s.pathname}/`]},new Uint8Array(0));for(const a of["index.php","index.html"]){const l=util.joinPaths(o,a);if(n.isFile(l)){o=l;break}}}if(!n.isFile(o)){const a=this.getFileNotFoundAction(i);switch(a.type){case"response":return a.response;case"internal-redirect":o=util.joinPaths(p(this,w),a.uri);break;case"404":return PHPResponse.forHttpCode(404);default:throw new Error(`Unsupported file-not-found action type: '${a.type}'`)}}if(n.isFile(o))if(o.endsWith(".php")){const a={...e,url:s.toString()};return d(this,z,le).call(this,a,o)}else return d(this,D,ae).call(this,n,o);else return PHPResponse.forHttpCode(404)}}w=new WeakMap,R=new WeakMap,k=new WeakMap,v=new WeakMap,F=new WeakMap,f=new WeakMap,S=new WeakMap,H=new WeakMap,D=new WeakSet,ae=function(e,r){const s=e.readFileAsBuffer(r);return new PHPResponse(200,{"content-length":[`${s.byteLength}`],"content-type":[inferMimeType(r)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},s)},z=new WeakSet,le=async function(e,r){let s;try{s=await this.processManager.acquirePHPInstance()}catch(i){return i instanceof MaxPhpInstancesError?PHPResponse.forHttpCode(502):PHPResponse.forHttpCode(500)}try{return await d(this,W,ce).call(this,s.php,e,r)}finally{s.reap()}},W=new WeakSet,ce=async function(e,r,s){let i="GET";const n={host:p(this,F),...normalizeHeaders(r.headers||{}),cookie:p(this,H).getCookieRequestHeader()};let o=r.body;if(typeof o=="object"&&!(o instanceof Uint8Array)){i="POST";const{bytes:a,contentType:l}=await encodeAsMultipart(o);o=a,n["content-type"]=l}try{const a=await e.run({relativeUri:ensurePathPrefix(toRelativeUrl(new URL(r.url)),p(this,f)),protocol:p(this,R),method:r.method||i,$_SERVER:{REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:p(this,w),HTTPS:p(this,S).startsWith("https://")?"on":""},body:o,scriptPath:s,headers:n});return p(this,H).rememberCookiesFromResponseHeaders(a.headers),a}catch(a){const l=a;if(l!=null&&l.response)return l.response;throw a}};function inferMimeType(t){const e=t.split(".").pop();return mimeTypes[e]||mimeTypes._default}function applyRewriteRules(t,e){for(const r of e)if(new RegExp(r.match).test(t))return t.replace(r.match,r.replacement);return t}function rotatePHPRuntime({php:t,cwd:e,recreateRuntime:r,maxRequests:s=400}){let i=0;async function n(){const l=await t.semaphore.acquire();try{t.hotSwapPHPRuntime(await r(),e),i=0}finally{l()}}async function o(){++i<s||await n()}async function a(l){l.type==="request.error"&&l.source==="php-wasm"&&await n()}return t.addEventListener("request.error",a),t.addEventListener("request.end",o),function(){t.removeEventListener("request.error",a),t.removeEventListener("request.end",o)}}async function writeFiles(t,e,r,{rmRoot:s=!1}={}){s&&await t.isDir(e)&&await t.rmdir(e,{recursive:!0});for(const[i,n]of Object.entries(r)){const o=util.joinPaths(e,i);await t.fileExists(util.dirname(o))||await t.mkdir(util.dirname(o)),n instanceof Uint8Array||typeof n=="string"?await t.writeFile(o,n):await writeFiles(t,o,n)}}function proxyFileSystem(t,e,r){const s=Object.getOwnPropertySymbols(t)[0];for(const i of r)e.fileExists(i)||e.mkdir(i),t.fileExists(i)||t.mkdir(i),e[s].FS.mount(e[s].PROXYFS,{root:i,fs:t[s].FS},i)}exports.DEFAULT_BASE_URL=DEFAULT_BASE_URL;exports.FSHelpers=FSHelpers;exports.HttpCookieStore=HttpCookieStore;exports.LatestSupportedPHPVersion=LatestSupportedPHPVersion;exports.PHP=PHP;exports.PHPProcessManager=PHPProcessManager;exports.PHPRequestHandler=PHPRequestHandler;exports.PHPResponse=PHPResponse;exports.PHPWorker=PHPWorker;exports.SupportedPHPVersions=SupportedPHPVersions;exports.SupportedPHPVersionsList=SupportedPHPVersionsList;exports.UnhandledRejectionsTarget=UnhandledRejectionsTarget;exports.__private__dont__use=__private__dont__use;exports.applyRewriteRules=applyRewriteRules;exports.ensurePathPrefix=ensurePathPrefix;exports.getLoadedRuntime=getLoadedRuntime;exports.getPhpIniEntries=getPhpIniEntries;exports.isExitCodeZero=isExitCodeZero;exports.iterateFiles=iteratePhpFiles;exports.loadPHPRuntime=loadPHPRuntime;exports.proxyFileSystem=proxyFileSystem;exports.removePathPrefix=removePathPrefix;exports.rotatePHPRuntime=rotatePHPRuntime;exports.setPhpIniEntries=setPhpIniEntries;exports.toRelativeUrl=toRelativeUrl;exports.withPHPIniValues=withPHPIniValues;exports.writeFiles=writeFiles;exports.writeFilesStreamToPhp=writeFilesStreamToPhp;
|
package/index.js
CHANGED
|
@@ -1967,7 +1967,7 @@ class PHPRequestHandler {
|
|
|
1967
1967
|
* @param request - PHP Request data.
|
|
1968
1968
|
*/
|
|
1969
1969
|
async request(e) {
|
|
1970
|
-
const r =
|
|
1970
|
+
const r = URL.canParse(e.url), s = new URL(
|
|
1971
1971
|
// Remove the hash part of the URL as it's not meant for the server.
|
|
1972
1972
|
e.url.split("#")[0],
|
|
1973
1973
|
r ? void 0 : DEFAULT_BASE_URL
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@php-wasm/universal",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.13",
|
|
4
4
|
"description": "PHP.wasm – emscripten bindings for PHP",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"module": "./index.js",
|
|
38
38
|
"types": "index.d.ts",
|
|
39
39
|
"license": "GPL-2.0-or-later",
|
|
40
|
-
"gitHead": "
|
|
40
|
+
"gitHead": "22888c009b54e0b1e5a5c9961b9d97c08b39f672",
|
|
41
41
|
"engines": {
|
|
42
42
|
"node": ">=18.18.0",
|
|
43
43
|
"npm": ">=8.11.0"
|
|
@@ -45,10 +45,10 @@
|
|
|
45
45
|
"dependencies": {
|
|
46
46
|
"comlink": "^4.4.1",
|
|
47
47
|
"ini": "4.1.2",
|
|
48
|
-
"@php-wasm/node-polyfills": "1.0.
|
|
49
|
-
"@php-wasm/logger": "1.0.
|
|
50
|
-
"@php-wasm/util": "1.0.
|
|
51
|
-
"@php-wasm/stream-compression": "1.0.
|
|
52
|
-
"@php-wasm/progress": "1.0.
|
|
48
|
+
"@php-wasm/node-polyfills": "1.0.13",
|
|
49
|
+
"@php-wasm/logger": "1.0.13",
|
|
50
|
+
"@php-wasm/util": "1.0.13",
|
|
51
|
+
"@php-wasm/stream-compression": "1.0.13",
|
|
52
|
+
"@php-wasm/progress": "1.0.13"
|
|
53
53
|
}
|
|
54
54
|
}
|