@php-wasm/universal 3.0.15 → 3.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -54,7 +54,7 @@ ${bold} WASM ERROR${reset}${redBg}`);for(const e of t.split(`
54
54
  ${r.text}
55
55
 
56
56
  === Stderr ===
57
- ${r.errors}`,r,"request");return r}async runStream(t){const e=await this.semaphore.acquire();let r;const s=y(this,h,D).call(this,async()=>{if(u(this,b)||(await this[__private__dont__use].ccall("php_wasm_init",null,[],[],{isAsync:!0}),w(this,b,!0)),t.scriptPath&&!this.fileExists(t.scriptPath))throw new Error(`The script path "${t.scriptPath}" does not exist.`);y(this,h,V).call(this,t.relativeUri||""),y(this,h,K).call(this,t.method||"GET");const i=normalizeHeaders(t.headers||{}),o=i.host||"example.com:443",a=y(this,h,Y).call(this,o,t.protocol||"http");if(y(this,h,G).call(this,o),y(this,h,J).call(this,a),y(this,h,X).call(this,i),t.body&&(r=y(this,h,Q).call(this,t.body)),typeof t.code=="string")this.writeFile("/internal/eval.php",t.code),y(this,h,U).call(this,"/internal/eval.php");else if(typeof t.scriptPath=="string")y(this,h,U).call(this,t.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const c=y(this,h,$).call(this,t.$_SERVER,i,a);for(const d in c)y(this,h,Z).call(this,d,c[d]);const l=t.env||{};for(const d in l)y(this,h,q).call(this,d,l[d]);return await this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0})}),n=()=>{if(r)try{this[__private__dont__use].free(r)}catch(i){logger.logger.error(i)}e(),this.dispatchEvent({type:"request.end"})};return s.then(i=>(i.finished.finally(n),i),i=>{try{n()}catch{}finally{throw i}})}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){const e=FSHelpers.mkdir(this[__private__dont__use].FS,t);return this.dispatchEvent({type:"filesystem.write"}),e}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){const r=FSHelpers.writeFile(this[__private__dont__use].FS,t,e);return this.dispatchEvent({type:"filesystem.write"}),r}unlink(t){const e=FSHelpers.unlink(this[__private__dont__use].FS,t);return this.dispatchEvent({type:"filesystem.write"}),e}mv(t,e){const r=FSHelpers.mv(this[__private__dont__use].FS,t,e);return this.dispatchEvent({type:"filesystem.write"}),r}rmdir(t,e={recursive:!0}){const r=FSHelpers.rmdir(this[__private__dont__use].FS,t,e);return this.dispatchEvent({type:"filesystem.write"}),r}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)}enableRuntimeRotation(t){w(this,_,{...u(this,_),enabled:!0,recreateRuntime:t.recreateRuntime,maxRequests:t.maxRequests??400})}async rotateRuntime(){if(!u(this,_).enabled)throw new Error("Runtime rotation is not enabled. Call enableRuntimeRotation() first.");await this.hotSwapPHPRuntime(await u(this,_).recreateRuntime()),u(this,_).requestsMade=0,u(this,_).needsRotating=!1}async hotSwapPHPRuntime(t){const e=this[__private__dont__use].FS,r=this.listFiles("/").map(a=>`/${a}`),s=this[__private__dont__use].spawnProcess,n=e.cwd();e.chdir("/");const i=[];for(const[a,c]of Object.entries(u(this,M)))i.push({mountHandler:c.mountHandler,vfsPath:a}),await c.unmount();try{this.exit()}catch{}this.initializeRuntime(t),s&&(this[__private__dont__use].spawnProcess=s),u(this,C)&&this.setSapiName(u(this,C));const o=this[__private__dont__use].FS;for(const a of r)a&&a!=="/request"&&copyMEMFSNodes(e,o,a);for(const{mountHandler:a,vfsPath:c}of i)this.mkdir(c),await this.mount(c,a);try{o.chdir(n)}catch(a){throw new Error(`Failed to restore CWD to ${n} after PHP runtime rotation.`,{cause:a})}}async mount(t,e){const r=await e(this,this[__private__dont__use].FS,t),s={mountHandler:e,unmount:async()=>{await r(),delete u(this,M)[t]}};return u(this,M)[t]=s,()=>{s.unmount()}}async cli(t,e={}){if(util.basename(t[0]??"")!=="php")return this.subProcess(t,e);u(this,b)&&(u(this,_).needsRotating=!0);const r=await this.semaphore.acquire();return await y(this,h,D).call(this,()=>{const s=e.env||{};for(const[n,i]of Object.entries(s))y(this,h,q).call(this,n,i);t=[t[0],"-c",PHP_INI_PATH,...t.slice(1)];for(const n of t)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[n]);return this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}).then(s=>(s.exitCode.finally(r),s)).finally(()=>{u(this,_).needsRotating=!0})}async subProcess(t,e={}){const r=this[__private__dont__use].spawnProcess(t[0],t.slice(1),{env:e.env,cwd:e.cwd??this.cwd()}),s=await createInvertedReadableStream();r.on("error",i=>{s.controller.error(i)}),r.stderr.on("data",i=>{s.controller.enqueue(i)});const n=await createInvertedReadableStream();return r.stdout.on("data",i=>{n.controller.enqueue(i)}),r.on("exit",()=>{setTimeout(()=>{try{s.controller.close()}catch{}try{n.controller.close()}catch{}},0)}),new StreamedPHPResponse(new ReadableStream({start(i){i.close()}}),n.stream,s.stream,new Promise(i=>{r.on("exit",o=>{i(o)})}))}setSkipShebang(t){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[t?1:0])}exit(t=0){this.dispatchEvent({type:"runtime.beforeExit"});try{this[__private__dont__use]._exit(t)}catch{}w(this,b,!1),w(this,T,null),this[__private__dont__use]&&(delete this[__private__dont__use].onMessage,delete this[__private__dont__use])}[Symbol.dispose](){this.exit(0)}}C=new WeakMap,b=new WeakMap,T=new WeakMap,x=new WeakMap,F=new WeakMap,M=new WeakMap,_=new WeakMap,h=new WeakSet,$=function(t,e,r){const s={...t||{}};s.HTTPS=s.HTTPS||r===443?"on":"off";for(const n in e){let i="HTTP_";["content-type","content-length"].includes(n.toLowerCase())&&(i=""),s[`${i}${n.toUpperCase().replace(/-/g,"_")}`]=e[n]}return s},V=function(t){this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[t]);let e="";t.includes("?")&&(e=t.substring(t.indexOf("?")+1)),this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])},G=function(t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[t])},J=function(t){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[t])},Y=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},K=function(t){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[t])},X=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=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},U=function(t){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[t])},Z=function(t,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[t,e])},q=function(t,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[t,e])},D=async function(t){u(this,_).enabled&&u(this,_).needsRotating&&await this.rotateRuntime(),++u(this,_).requestsMade,u(this,_).requestsMade>=u(this,_).maxRequests&&(u(this,_).needsRotating=!0);const e=this[__private__dont__use],r=await createInvertedReadableStream();e.onHeaders=p=>{a||s||r.controller.enqueue(p.slice())};let s=!1;const n=()=>{s||(s=!0,r.controller.close())},i=await createInvertedReadableStream();e.onStdout=p=>{n(),!a&&i.controller.enqueue(p.slice())};const o=await createInvertedReadableStream();e.onStderr=p=>{a||o.controller.enqueue(p.slice())};let a=!1,c;const d=(async()=>{var p;try{return await Promise.race([t(),new Promise((g,H)=>{var j;c=W=>{isExitCode(W.error)||H(W.error)},(j=u(this,T))==null||j.addEventListener("error",c,{once:!0})})])}catch(f){if(isExitCode(f))return f.status;i.controller.error(f),o.controller.error(f),r.controller.error(f),a=!0;for(const g in this)typeof this[g]=="function"&&(this[g]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});throw this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify(),f}finally{a||(i.controller.close(),o.controller.close(),n(),a=!0),(p=u(this,T))==null||p.removeEventListener("error",c)}})().then(p=>(p!==0&&this.dispatchEvent({type:"request.error",error:new Error(`PHP.run() failed with exit code ${p}.`),source:"php-wasm"}),p),p=>{const f=p.source??"php-wasm";throw this.dispatchEvent({type:"request.error",error:p,source:f}),p});return new StreamedPHPResponse(r.stream,i.stream,o.stream,d)};function normalizeHeaders(t){const e={};for(const r in t)e[r.toLowerCase()]=t[r];return e}function copyMEMFSNodes(t,e,r){if(getNodeType(t,r)!=="memfs"||!["memfs","missing"].includes(getNodeType(e,r)))return;const s=t.lookupPath(r);if(!t.isDir(s.node.mode)){e.writeFile(r,t.readFile(r));return}e.mkdirTree(r);const n=t.readdir(r).filter(i=>i!=="."&&i!=="..");for(const i of n)copyMEMFSNodes(t,e,util.joinPaths(r,i))}async function createInvertedReadableStream(t={}){let e;const r=new Promise(i=>{e=i}),s=new ReadableStream({...t,start(i){if(e(i),t.start)return t.start(i)}}),n=await r;return{stream:s,controller:n}}const getNodeType=(t,e)=>{try{return"contents"in t.lookupPath(e,{follow:!0}).node?"memfs":"not-memfs"}catch{return"missing"}};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 n of e)s[n]=r[n];return s}async function setPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));for(const[s,n]of Object.entries(e))n==null?delete r[s]:r[s]=n;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)}}async function printDebugDetails(t,e){e&&printResponseDebugDetails(await PHPResponse.fromStreamedResponse(e)),await prettyPrintFullStackTrace(t)}async function prettyPrintFullStackTrace(t){let e=t,r=!0;for(;e;)r||process.stderr.write(`
57
+ ${r.errors}`,r,"request");return r}async runStream(t){const e=await this.semaphore.acquire();let r;const s=y(this,h,D).call(this,async()=>{if(u(this,b)||(await this[__private__dont__use].ccall("php_wasm_init",null,[],[],{isAsync:!0}),w(this,b,!0)),t.scriptPath&&!this.fileExists(t.scriptPath))throw new Error(`The script path "${t.scriptPath}" does not exist.`);y(this,h,V).call(this,t.relativeUri||""),y(this,h,K).call(this,t.method||"GET");const i=normalizeHeaders(t.headers||{}),o=i.host||"example.com:443",a=y(this,h,Y).call(this,o,t.protocol||"http");if(y(this,h,G).call(this,o),y(this,h,J).call(this,a),y(this,h,X).call(this,i),t.body&&(r=y(this,h,Q).call(this,t.body)),typeof t.code=="string")this.writeFile("/internal/eval.php",t.code),y(this,h,U).call(this,"/internal/eval.php");else if(typeof t.scriptPath=="string")y(this,h,U).call(this,t.scriptPath||"");else throw new TypeError("The request object must have either a `code` or a `scriptPath` property.");const c=y(this,h,$).call(this,t.$_SERVER,i,a);for(const p in c)y(this,h,Z).call(this,p,c[p]);const l=t.env||{};for(const p in l)y(this,h,q).call(this,p,l[p]);return await this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0})}),n=()=>{if(r)try{this[__private__dont__use].free(r)}catch(i){logger.logger.error(i)}e(),this.dispatchEvent({type:"request.end"})};return s.then(i=>(i.finished.finally(n),i),i=>{try{n()}catch{}finally{throw i}})}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){const e=FSHelpers.mkdir(this[__private__dont__use].FS,t);return this.dispatchEvent({type:"filesystem.write"}),e}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){const r=FSHelpers.writeFile(this[__private__dont__use].FS,t,e);return this.dispatchEvent({type:"filesystem.write"}),r}unlink(t){const e=FSHelpers.unlink(this[__private__dont__use].FS,t);return this.dispatchEvent({type:"filesystem.write"}),e}mv(t,e){const r=FSHelpers.mv(this[__private__dont__use].FS,t,e);return this.dispatchEvent({type:"filesystem.write"}),r}rmdir(t,e={recursive:!0}){const r=FSHelpers.rmdir(this[__private__dont__use].FS,t,e);return this.dispatchEvent({type:"filesystem.write"}),r}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)}enableRuntimeRotation(t){w(this,_,{...u(this,_),enabled:!0,recreateRuntime:t.recreateRuntime,maxRequests:t.maxRequests??400})}async rotateRuntime(){if(!u(this,_).enabled)throw new Error("Runtime rotation is not enabled. Call enableRuntimeRotation() first.");await this.hotSwapPHPRuntime(await u(this,_).recreateRuntime()),u(this,_).requestsMade=0,u(this,_).needsRotating=!1}async hotSwapPHPRuntime(t){const e=this[__private__dont__use].FS,r=this.listFiles("/").map(a=>`/${a}`),s=this[__private__dont__use].spawnProcess,n=e.cwd();e.chdir("/");const i=[];for(const[a,c]of Object.entries(u(this,M)))i.push({mountHandler:c.mountHandler,vfsPath:a}),await c.unmount();try{this.exit()}catch{}this.initializeRuntime(t),s&&(this[__private__dont__use].spawnProcess=s),u(this,C)&&this.setSapiName(u(this,C));const o=this[__private__dont__use].FS;for(const a of r)a&&a!=="/request"&&copyMEMFSNodes(e,o,a);for(const{mountHandler:a,vfsPath:c}of i)this.mkdir(c),await this.mount(c,a);try{o.chdir(n)}catch(a){throw new Error(`Failed to restore CWD to ${n} after PHP runtime rotation.`,{cause:a})}}async mount(t,e){const r=await e(this,this[__private__dont__use].FS,t),s={mountHandler:e,unmount:async()=>{await r(),delete u(this,M)[t]}};return u(this,M)[t]=s,()=>{s.unmount()}}async cli(t,e={}){if(util.basename(t[0]??"")!=="php")return this.subProcess(t,e);u(this,b)&&(u(this,_).needsRotating=!0);const r=await this.semaphore.acquire();return await y(this,h,D).call(this,()=>{const s=e.env||{};for(const[n,i]of Object.entries(s))y(this,h,q).call(this,n,i);t=[t[0],"-c",PHP_INI_PATH,...t.slice(1)];for(const n of t)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[n]);return this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}).then(s=>(s.exitCode.finally(r),s)).finally(()=>{u(this,_).needsRotating=!0})}async subProcess(t,e={}){const r=this[__private__dont__use].spawnProcess(t[0],t.slice(1),{env:e.env,cwd:e.cwd??this.cwd()}),s=await createInvertedReadableStream();r.on("error",i=>{s.controller.error(i)}),r.stderr.on("data",i=>{s.controller.enqueue(i)});const n=await createInvertedReadableStream();return r.stdout.on("data",i=>{n.controller.enqueue(i)}),r.on("exit",()=>{setTimeout(()=>{try{s.controller.close()}catch{}try{n.controller.close()}catch{}},0)}),new StreamedPHPResponse(new ReadableStream({start(i){i.close()}}),n.stream,s.stream,new Promise(i=>{r.on("exit",o=>{i(o)})}))}setSkipShebang(t){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[t?1:0])}exit(t=0){this.dispatchEvent({type:"runtime.beforeExit"});try{this[__private__dont__use]._exit(t)}catch{}w(this,b,!1),w(this,T,null),this[__private__dont__use]&&(delete this[__private__dont__use].onMessage,delete this[__private__dont__use])}[Symbol.dispose](){this.exit(0)}}C=new WeakMap,b=new WeakMap,T=new WeakMap,x=new WeakMap,F=new WeakMap,M=new WeakMap,_=new WeakMap,h=new WeakSet,$=function(t,e,r){const s={...t||{}};s.HTTPS=s.HTTPS||r===443?"on":"off";for(const n in e){let i="HTTP_";["content-type","content-length"].includes(n.toLowerCase())&&(i=""),s[`${i}${n.toUpperCase().replace(/-/g,"_")}`]=e[n]}return s},V=function(t){this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[t]);let e="";t.includes("?")&&(e=t.substring(t.indexOf("?")+1)),this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[e])},G=function(t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[t])},J=function(t){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[t])},Y=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},K=function(t){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[t])},X=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=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},U=function(t){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[t])},Z=function(t,e){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[t,e])},q=function(t,e){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[t,e])},D=async function(t){u(this,_).enabled&&u(this,_).needsRotating&&await this.rotateRuntime(),++u(this,_).requestsMade,u(this,_).requestsMade>=u(this,_).maxRequests&&(u(this,_).needsRotating=!0);const e=this[__private__dont__use],r=await createInvertedReadableStream();e.onHeaders=d=>{a||s||r.controller.enqueue(d.slice())};let s=!1;const n=()=>{s||(s=!0,r.controller.close())},i=await createInvertedReadableStream();e.onStdout=d=>{n(),!a&&i.controller.enqueue(d.slice())};const o=await createInvertedReadableStream();e.onStderr=d=>{a||o.controller.enqueue(d.slice())};let a=!1,c;const p=(async()=>{var d;try{return await Promise.race([t(),new Promise((g,H)=>{var j;c=W=>{isExitCode(W.error)||H(W.error)},(j=u(this,T))==null||j.addEventListener("error",c,{once:!0})})])}catch(f){if(isExitCode(f))return f.status;i.controller.error(f),o.controller.error(f),r.controller.error(f),a=!0;for(const g in this)typeof this[g]=="function"&&(this[g]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});throw this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify(),f}finally{a||(i.controller.close(),o.controller.close(),n(),a=!0),(d=u(this,T))==null||d.removeEventListener("error",c)}})().then(d=>(d!==0&&this.dispatchEvent({type:"request.error",error:new Error(`PHP.run() failed with exit code ${d}.`),source:"php-wasm"}),d),d=>{const f=d.source??"php-wasm";throw this.dispatchEvent({type:"request.error",error:d,source:f}),d});return new StreamedPHPResponse(r.stream,i.stream,o.stream,p)};function normalizeHeaders(t){const e={};for(const r in t)e[r.toLowerCase()]=t[r];return e}function copyMEMFSNodes(t,e,r){if(getNodeType(t,r)!=="memfs"||!["memfs","missing"].includes(getNodeType(e,r)))return;const s=t.lookupPath(r);if(!t.isDir(s.node.mode)){e.writeFile(r,t.readFile(r));return}e.mkdirTree(r);const n=t.readdir(r).filter(i=>i!=="."&&i!=="..");for(const i of n)copyMEMFSNodes(t,e,util.joinPaths(r,i))}async function createInvertedReadableStream(t={}){let e;const r=new Promise(i=>{e=i}),s=new ReadableStream({...t,start(i){if(e(i),t.start)return t.start(i)}}),n=await r;return{stream:s,controller:n}}const getNodeType=(t,e)=>{try{return"contents"in t.lookupPath(e,{follow:!0}).node?"memfs":"not-memfs"}catch{return"missing"}};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 n of e)s[n]=r[n];return s}async function setPhpIniEntries(t,e){const r=ini.parse(await t.readFileAsText(PHP_INI_PATH));for(const[s,n]of Object.entries(e))n==null?delete r[s]:r[s]=n;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)}}async function printDebugDetails(t,e){e&&printResponseDebugDetails(await PHPResponse.fromStreamedResponse(e)),await prettyPrintFullStackTrace(t)}async function prettyPrintFullStackTrace(t){let e=t,r=!0;for(;e;)r||process.stderr.write(`
58
58
  Caused by:
59
59
 
60
60
  `),process.stderr.write(e.originalErrorClassName??e.name),process.stderr.write(": "+e.message+`
@@ -88,7 +88,7 @@ ${JSON.stringify(t.headers,null,2)}
88
88
  `);n.push(`--${e}--\r
89
89
  `);const i=n.reduce((c,l)=>c+l.length,0),o=new Uint8Array(i);let a=0;for(const c of n)o.set(typeof c=="string"?s.encode(c):c,a),a+=c.length;return{bytes:o,contentType:r}}function fileToUint8Array(t){return t.arrayBuffer().then(e=>new Uint8Array(e))}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 S,I,L,k,A,E,N,v,R,ee,te,re;class PHPRequestHandler{constructor(e){m(this,R);m(this,S);m(this,I);m(this,L);m(this,k);m(this,A);m(this,E);m(this,N);m(this,v);const{documentRoot:r="/www/",absoluteUrl:s=typeof location=="object"?location.href:DEFAULT_BASE_URL,rewriteRules:n=[],getFileNotFoundAction:i=()=>({type:"404"})}=e;"processManager"in e?this.processManager=e.processManager:this.processManager=new PHPProcessManager({phpFactory:async c=>{const l=await e.phpFactory({...c,requestHandler:this});return l.isDir(r)||l.mkdir(r),l.chdir(r),l.requestHandler=this,l},maxPhpInstances:e.maxPhpInstances}),w(this,v,e.cookieStore===void 0?new HttpCookieStore:e.cookieStore),w(this,S,r);const o=new URL(s);w(this,L,o.hostname),w(this,k,o.port?Number(o.port):o.protocol==="https:"?443:80),w(this,I,(o.protocol||"").replace(":",""));const a=u(this,k)!==443&&u(this,k)!==80;w(this,A,[u(this,L),a?`:${u(this,k)}`:""].join("")),w(this,E,o.pathname.replace(/\/+$/,"")),w(this,N,[`${u(this,I)}://`,u(this,A),u(this,E)].join("")),this.rewriteRules=n,this.getFileNotFoundAction=i}async getPrimaryPhp(){return await this.processManager.getPrimaryPhp()}pathToInternalUrl(e){return e.startsWith("/")||(e=`/${e}`),`${this.absoluteUrl}${e}`}internalUrlToPath(e){const r=new URL(e,"https://playground.internal");return r.pathname.startsWith(u(this,E))&&(r.pathname=r.pathname.slice(u(this,E).length)),toRelativeUrl(r)}get absoluteUrl(){return u(this,N)}get documentRoot(){return u(this,S)}async request(e){const r=URL.canParse(e.url),s=new URL(e.url.split("#")[0],r?void 0:DEFAULT_BASE_URL),n=applyRewriteRules(removePathPrefix(decodeURIComponent(s.pathname),u(this,E)),this.rewriteRules),i=await this.getPrimaryPhp();let o=util.joinPaths(u(this,S),n);if(i.isDir(o)){if(!o.endsWith("/"))return new PHPResponse(301,{Location:[`${s.pathname}/`]},new Uint8Array(0));for(const a of["index.php","index.html"]){const c=util.joinPaths(o,a);if(i.isFile(c)){o=c;break}}}if(!i.isFile(o)){const a=this.getFileNotFoundAction(n);switch(a.type){case"response":return a.response;case"internal-redirect":o=util.joinPaths(u(this,S),a.uri);break;case"404":return PHPResponse.forHttpCode(404);default:throw new Error(`Unsupported file-not-found action type: '${a.type}'`)}}if(i.isFile(o))if(o.endsWith(".php")){const a={...e,url:s.toString()},c=await y(this,R,te).call(this,a,o);return c.ok()&&c.exitCode!==0?new PHPResponse(500,c.headers,c.bytes,c.errors,c.exitCode):c}else return y(this,R,ee).call(this,i,o);else return PHPResponse.forHttpCode(404)}async[Symbol.asyncDispose](){await this.processManager[Symbol.asyncDispose]()}}S=new WeakMap,I=new WeakMap,L=new WeakMap,k=new WeakMap,A=new WeakMap,E=new WeakMap,N=new WeakMap,v=new WeakMap,R=new WeakSet,ee=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)},te=async function(e,r){let s;try{s=await this.processManager.acquirePHPInstance({considerPrimary:!0})}catch(n){return n instanceof MaxPhpInstancesError?PHPResponse.forHttpCode(502):PHPResponse.forHttpCode(500)}try{return await y(this,R,re).call(this,s.php,e,r)}finally{s.reap()}},re=async function(e,r,s){let n="GET";const i={host:u(this,A),...normalizeHeaders(r.headers||{})};u(this,v)&&(i.cookie=u(this,v).getCookieRequestHeader());let o=r.body;if(typeof o=="object"&&!(o instanceof Uint8Array)){n="POST";const{bytes:a,contentType:c}=await encodeAsMultipart(o);o=a,i["content-type"]=c}try{const a=await e.run({relativeUri:ensurePathPrefix(toRelativeUrl(new URL(r.url)),u(this,E)),protocol:u(this,I),method:r.method||n,$_SERVER:{REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:u(this,S),HTTPS:u(this,N).startsWith("https://")?"on":""},body:o,scriptPath:s,headers:i});return u(this,v)&&u(this,v).rememberCookiesFromResponseHeaders(a.headers),a}catch(a){const c=a;if(c!=null&&c.response)return c.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,recreateRuntime:e,maxRequests:r=400}){return t.enableRuntimeRotation({recreateRuntime:e,maxRequests:r})}async function writeFiles(t,e,r,{rmRoot:s=!1}={}){s&&await t.isDir(e)&&await t.rmdir(e,{recursive:!0});for(const[n,i]of Object.entries(r)){const o=util.joinPaths(e,n);await t.fileExists(util.dirname(o))||await t.mkdir(util.dirname(o)),i instanceof Uint8Array||typeof i=="string"?await t.writeFile(o,i):await writeFiles(t,o,i)}}function proxyFileSystem(t,e,r){const s=Object.getOwnPropertySymbols(t)[0];for(const n of r)e.fileExists(n)||e.mkdir(n),t.fileExists(n)||t.mkdir(n),e[s].FS.mount(e[s].PROXYFS,{root:n,fs:t[s].FS},n)}function isPathToSharedFS(t,e){var i;const r=Object.getOwnPropertySymbols(t)[0],n=t[r].FS.lookupPath(e,{noent_okay:!0});return((i=n==null?void 0:n.node)==null?void 0:i.isSharedFS)??!1}function sandboxedSpawnHandlerFactory(t){return util.createSpawnHandler(async function(e,r,s){r.notifySpawn(),e[0]==="exec"&&e.shift(),(e[0].endsWith(".php")||e[0].endsWith(".phar"))&&e.unshift("php");const n=e[0].split("/").pop();if(e[0]==="/usr/bin/env"&&e[1]==="stty"&&e[2]==="size")r.stdout("18 140"),r.exit(0);else if(n==="tput"&&e[1]==="cols")r.stdout("140"),r.exit(0);else if(n==="less"){r.on("stdin",a=>{r.stdout(a)}),await new Promise(a=>{r.childProcess.stdin.on("finish",()=>{a(!0)})}),r.exit(0);return}if(!["php","ls","pwd"].includes(n??"")){r.exit(127);return}const{php:i,reap:o}=await t.acquirePHPInstance({considerPrimary:!1});try{s.cwd&&i.chdir(s.cwd);const a=i.cwd();switch(n){case"php":{const c=await i.cli(e,{env:{...s.env,SCRIPT_PATH:e[1],SHELL_PIPE:"0"}});c.stdout.pipeTo(new WritableStream({write(l){r.stdout(l)}})),c.stderr.pipeTo(new WritableStream({write(l){r.stderr(l)}})),r.exit(await c.exitCode);break}case"ls":{const c=i.listFiles(e[1]??a);for(const l of c)r.stdout(l+`
90
90
  `);await new Promise(l=>setTimeout(l,10)),r.exit(0);break}case"pwd":{r.stdout(a+`
91
- `),await new Promise(c=>setTimeout(c,10)),r.exit(0);break}}}catch(a){throw r.exit(1),a}finally{o()}})}function exposeSync(t,e,r,s=["*"]){return expose(t,e,s,r.afterResponseSent)}function createSyncProxy(t,e=[],r){return new Proxy(()=>{},{get(s,n){return n==="then"&&!e.length?{then:(i,o)=>o(createSyncProxy(t,[],r))}:createSyncProxy(t,[...e,n],r)},set(s,n,i){const[o,a]=toWireValue(i);return r.send(t,{type:MessageType.SET,path:[...e,n].map(String),value:o},a),!0},apply(s,n,i){if(e.at(-1)==="bind")return createSyncProxy(t,e.slice(0,-1),r);const[a,c]=processArguments(i),l=r.send(t,{type:MessageType.APPLY,path:e.map(String),argumentList:a},c);return fromWireValue(l)},construct(s,n){const[i,o]=processArguments(n),a=r.send(t,{type:MessageType.CONSTRUCT,path:e.map(String),argumentList:i},o);return fromWireValue(a)}})}function wrapSync(t,e){return createSyncProxy(t,[],e)}class NodeSABSyncReceiveMessageTransport{static async create(){if(!NodeSABSyncReceiveMessageTransport.receiveMessageOnPort)try{NodeSABSyncReceiveMessageTransport.receiveMessageOnPort=require("worker_threads").receiveMessageOnPort}catch{NodeSABSyncReceiveMessageTransport.receiveMessageOnPort=await import("worker_threads").then(e=>e.receiveMessageOnPort)}return new NodeSABSyncReceiveMessageTransport}constructor(){}afterResponseSent(e){const{notifyBuffer:r}=e.data;if(r){const s=new Int32Array(r);s[0]=1,Atomics.notify(s,0)}}send(e,r,s){var l;const n=new SharedArrayBuffer(4),i=new Int32Array(n);i[0]=0;const o=generateUUID();if(e.postMessage({...r,id:o,notifyBuffer:n},s),Atomics.wait(i,0,0,5e3)==="timed-out")throw new Error("Timeout waiting for response");for(;;){const d=NodeSABSyncReceiveMessageTransport.receiveMessageOnPort(e);if(((l=d.message)==null?void 0:l.id)===o)return d.message;if(!d)throw new Error("No response received")}}}/**
91
+ `),await new Promise(c=>setTimeout(c,10)),r.exit(0);break}}}catch(a){throw r.exit(1),a}finally{o()}})}function exposeSync(t,e,r,s=["*"]){return expose(t,e,s,r.afterResponseSent)}function createSyncProxy(t,e=[],r){return new Proxy(()=>{},{get(s,n){return n==="then"&&!e.length?{then:(i,o)=>o(createSyncProxy(t,[],r))}:createSyncProxy(t,[...e,n],r)},set(s,n,i){const[o,a]=toWireValue(i);return r.send(t,{type:MessageType.SET,path:[...e,n].map(String),value:o},a),!0},apply(s,n,i){if(e.at(-1)==="bind")return createSyncProxy(t,e.slice(0,-1),r);const[a,c]=processArguments(i),l=r.send(t,{type:MessageType.APPLY,path:e.map(String),argumentList:a},c);return fromWireValue(l)},construct(s,n){const[i,o]=processArguments(n),a=r.send(t,{type:MessageType.CONSTRUCT,path:e.map(String),argumentList:i},o);return fromWireValue(a)}})}function wrapSync(t,e){return createSyncProxy(t,[],e)}class NodeSABSyncReceiveMessageTransport{static async create(){if(!NodeSABSyncReceiveMessageTransport.receiveMessageOnPort)try{NodeSABSyncReceiveMessageTransport.receiveMessageOnPort=require("worker_threads").receiveMessageOnPort}catch{NodeSABSyncReceiveMessageTransport.receiveMessageOnPort=await import("worker_threads").then(e=>e.receiveMessageOnPort)}return new NodeSABSyncReceiveMessageTransport}constructor(){}afterResponseSent(e){const{notifyBuffer:r}=e.data;if(r){const s=new Int32Array(r);s[0]=1,Atomics.notify(s,0)}}send(e,r,s){var l;const n=new SharedArrayBuffer(4),i=new Int32Array(n);i[0]=0;const o=generateUUID();if(e.postMessage({...r,id:o,notifyBuffer:n},s),Atomics.wait(i,0,0,5e3)==="timed-out")throw new Error("Timeout waiting for response");for(;;){const p=NodeSABSyncReceiveMessageTransport.receiveMessageOnPort(e);if(((l=p.message)==null?void 0:l.id)===o)return p.message;if(!p)throw new Error("No response received")}}}/**
92
92
  * Original, unmodified Comlink library from Google:
93
93
  *
94
94
  * @license
@@ -98,5 +98,5 @@ ${JSON.stringify(t.headers,null,2)}
98
98
  * @license
99
99
  * Copyright 2019 Google LLC
100
100
  * SPDX-License-Identifier: Apache-2.0
101
- */const WireValueType={RAW:"RAW",HANDLER:"HANDLER"},MessageType={GET:"GET",SET:"SET",APPLY:"APPLY",CONSTRUCT:"CONSTRUCT",ENDPOINT:"ENDPOINT",RELEASE:"RELEASE"},isObject=t=>typeof t=="object"&&t!==null||typeof t=="function",proxyTransferHandler={canHandle:t=>isObject(t)&&t[proxyMarker],serialize(t){const{port1:e,port2:r}=new MessageChannel;return expose(t,e),[r,[r]]},deserialize(t){return t.start(),wrap(t)}},throwTransferHandler$1={canHandle:t=>isObject(t)&&throwMarker in t,serialize({value:t}){let e;return t instanceof Error?e={isError:!0,value:{message:t.message,name:t.name,stack:t.stack}}:e={isError:!1,value:t},[e,[]]},deserialize(t){throw t.isError?Object.assign(new Error(t.value.message),t.value):t.value}},transferHandlers=new Map([["proxy",proxyTransferHandler],["throw",throwTransferHandler$1]]);function isAllowedOrigin(t,e){for(const r of t)if(e===r||r==="*"||r instanceof RegExp&&r.test(e))return!0;return!1}function expose(t,e=globalThis,r=["*"],s){e.addEventListener("message",function n(i){if(!i||!i.data)return;if(!isAllowedOrigin(r,i.origin)){console.warn(`Invalid origin '${i.origin}' for comlink proxy`);return}const{id:o,type:a,path:c}={path:[],...i.data},l=(i.data.argumentList||[]).map(fromWireValue);let d;try{const p=c.slice(0,-1).reduce((g,H)=>g[H],t),f=c.reduce((g,H)=>g[H],t);switch(a){case MessageType.GET:d=f;break;case MessageType.SET:p[c.slice(-1)[0]]=fromWireValue(i.data.value),d=!0;break;case MessageType.APPLY:d=f.apply(p,l);break;case MessageType.CONSTRUCT:{const g=new f(...l);d=proxy(g)}break;case MessageType.ENDPOINT:{const{port1:g,port2:H}=new MessageChannel;expose(t,H),d=transfer(g,[g])}break;case MessageType.RELEASE:d=void 0;break;default:return}}catch(p){d={value:p,[throwMarker]:0}}Promise.resolve(d).catch(p=>({value:p,[throwMarker]:0})).then(p=>{const[f,g]=toWireValue(p);e.postMessage({...f,id:o},g),a===MessageType.RELEASE&&(e.removeEventListener("message",n),closeEndPoint(e),finalizer in t&&typeof t[finalizer]=="function"&&t[finalizer]())}).catch(()=>{const[p,f]=toWireValue({value:new TypeError("Unserializable return value"),[throwMarker]:0});e.postMessage({...p,id:o},f)}).finally(()=>{s==null||s(i)})}),e.start&&e.start()}function isMessagePort(t){return t.constructor.name==="MessagePort"}function closeEndPoint(t){isMessagePort(t)&&t.close()}function wrap(t,e){const r=new Map;return t.addEventListener("message",function(n){const{data:i}=n;if(!i||!i.id)return;const o=r.get(i.id);if(o)try{o(i)}finally{r.delete(i.id)}}),createProxy(t,r,[],e)}function throwIfProxyReleased(t){if(t)throw new Error("Proxy has been released and is not useable")}function releaseEndpoint(t){return requestResponseMessage(t,new Map,{type:MessageType.RELEASE}).then(()=>{closeEndPoint(t)})}const proxyCounter=new WeakMap,proxyFinalizers="FinalizationRegistry"in globalThis&&new FinalizationRegistry(t=>{const e=(proxyCounter.get(t)||0)-1;proxyCounter.set(t,e),e===0&&releaseEndpoint(t)});function registerProxy(t,e){const r=(proxyCounter.get(e)||0)+1;proxyCounter.set(e,r),proxyFinalizers&&proxyFinalizers.register(t,e,t)}function unregisterProxy(t){proxyFinalizers&&proxyFinalizers.unregister(t)}function createProxy(t,e,r=[],s=function(){}){let n=!1;const i=new Proxy(s,{get(o,a){if(throwIfProxyReleased(n),a===releaseProxy)return()=>{unregisterProxy(i),releaseEndpoint(t),e.clear(),n=!0};if(a==="then"){if(r.length===0)return{then:()=>i};const c=requestResponseMessage(t,e,{type:MessageType.GET,path:r.map(l=>l.toString())}).then(fromWireValue);return c.then.bind(c)}return createProxy(t,e,[...r,a])},set(o,a,c){throwIfProxyReleased(n);const[l,d]=toWireValue(c);return requestResponseMessage(t,e,{type:MessageType.SET,path:[...r,a].map(p=>p.toString()),value:l},d).then(fromWireValue)},apply(o,a,c){throwIfProxyReleased(n);const l=r[r.length-1];if(l===createEndpoint)return requestResponseMessage(t,e,{type:MessageType.ENDPOINT}).then(fromWireValue);if(l==="bind")return createProxy(t,e,r.slice(0,-1));const[d,p]=processArguments(c);return requestResponseMessage(t,e,{type:MessageType.APPLY,path:r.map(f=>f.toString()),argumentList:d},p).then(fromWireValue)},construct(o,a){throwIfProxyReleased(n);const[c,l]=processArguments(a);return requestResponseMessage(t,e,{type:MessageType.CONSTRUCT,path:r.map(d=>d.toString()),argumentList:c},l).then(fromWireValue)}});return registerProxy(i,t),i}function myFlat(t){return Array.prototype.concat.apply([],t)}function processArguments(t){const e=t.map(toWireValue);return[e.map(r=>r[0]),myFlat(e.map(r=>r[1]))]}const transferCache=new WeakMap;function transfer(t,e){return transferCache.set(t,e),t}function proxy(t){return Object.assign(t,{[proxyMarker]:!0})}function windowEndpoint(t,e=globalThis,r="*"){return{postMessage:(s,n)=>t.postMessage(s,r,n),addEventListener:e.addEventListener.bind(e),removeEventListener:e.removeEventListener.bind(e)}}function toWireValue(t){for(const[e,r]of transferHandlers)if(r.canHandle(t)){const[s,n]=r.serialize(t);return[{type:WireValueType.HANDLER,name:e,value:s},n]}return[{type:WireValueType.RAW,value:t},transferCache.get(t)||[]]}function fromWireValue(t){switch(t.type){case WireValueType.HANDLER:return transferHandlers.get(t.name).deserialize(t.value);case WireValueType.RAW:return t.value}}function requestResponseMessage(t,e,r,s){return new Promise(n=>{const i=generateUUID();e.set(i,n),t.start&&t.start(),t.postMessage({id:i,...r},s)})}function generateUUID(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function nodeEndpoint(t){const e=new WeakMap;return{postMessage:t.postMessage.bind(t),addEventListener:(r,s)=>{const n=i=>{"handleEvent"in s?s.handleEvent({data:i}):s({data:i})};t.on("message",n),e.set(s,n)},removeEventListener:(r,s)=>{const n=e.get(s);n&&(t.off("message",n),e.delete(s))},start:t.start&&t.start.bind(t)}}const list=[Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError,globalThis.DOMException,globalThis.AssertionError,globalThis.SystemError].filter(Boolean).map(t=>[t.name,t]),errorConstructors=new Map(list);class NonError extends Error{constructor(e){super(NonError._prepareSuperMessage(e)),this.name="NonError"}static _prepareSuperMessage(e){try{return JSON.stringify(e)}catch{return String(e)}}}const errorProperties=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1},{property:"errors",enumerable:!1}],toJsonWasCalled=new WeakSet,toJSON=t=>{toJsonWasCalled.add(t);const e=t.toJSON();return toJsonWasCalled.delete(t),e},newError=t=>{const e=errorConstructors.get(t)??Error;return e===AggregateError?new e([]):new e},destroyCircular=({from:t,seen:e,to:r,forceEnumerable:s,maxDepth:n,depth:i,useToJSON:o,serialize:a})=>{if(r||(Array.isArray(t)?r=[]:!a&&isErrorLike(t)?r=newError(t.name):r={}),e.push(t),i>=n)return r;if(o&&typeof t.toJSON=="function"&&!toJsonWasCalled.has(t))return toJSON(t);const c=l=>destroyCircular({from:l,seen:[...e],forceEnumerable:s,maxDepth:n,depth:i,useToJSON:o,serialize:a});for(const[l,d]of Object.entries(t)){if(d&&d instanceof Uint8Array&&d.constructor.name==="Buffer"){r[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){r[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){try{r[l]=d}catch{}continue}if(!e.includes(t[l])){i++,r[l]=c(t[l]);continue}r[l]="[Circular]"}}if(a||r instanceof Error)for(const{property:l,enumerable:d}of errorProperties)t[l]!==void 0&&t[l]!==null&&Object.defineProperty(r,l,{value:isErrorLike(t[l])||Array.isArray(t[l])?c(t[l]):t[l],enumerable:s?!0:d,configurable:!0,writable:!0});return r};function serializeError(t,e={}){const{maxDepth:r=Number.POSITIVE_INFINITY,useToJSON:s=!0}=e;return typeof t=="object"&&t!==null?destroyCircular({from:t,seen:[],forceEnumerable:!0,maxDepth:r,depth:0,useToJSON:s,serialize:!0}):typeof t=="function"?`[Function: ${t.name||"anonymous"}]`:t}function deserializeError(t,e={}){const{maxDepth:r=Number.POSITIVE_INFINITY}=e;return t instanceof Error?t:isMinimumViableSerializedError(t)?destroyCircular({from:t,seen:[],to:newError(t.name),maxDepth:r,depth:0,serialize:!1}):new NonError(t)}function isErrorLike(t){return!!t&&typeof t=="object"&&typeof t.name=="string"&&typeof t.message=="string"&&typeof t.stack=="string"}function isMinimumViableSerializedError(t){return!!t&&typeof t=="object"&&typeof t.message=="string"&&!Array.isArray(t)}async function consumeAPISync(t){setupTransferHandlers();const e=await NodeSABSyncReceiveMessageTransport.create();return wrapSync(t,e)}function consumeAPI(t,e=void 0){setupTransferHandlers();let r;(typeof document>"u"?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&_documentCurrentScript.tagName.toUpperCase()==="SCRIPT"&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href).startsWith("file://")?r=nodeEndpoint(t):r=t instanceof Worker?t:windowEndpoint(t,e);const n=wrap(r),i=proxyClone(n);return new Proxy(i,{get:(o,a)=>a==="isConnected"?async()=>{for(;;)try{await runWithTimeout(n.isConnected(),200);break}catch{}}:n[a]})}async function runWithTimeout(t,e){return new Promise((r,s)=>{setTimeout(s,e),t.then(r)})}function exposeAPI(t,e,r){const{setReady:s,setFailed:n,exposedApi:i}=prepareForExpose(t,e);let o;return r?o=nodeEndpoint(r):o=typeof window<"u"?windowEndpoint(self.parent):void 0,expose(i,o),[s,n,i]}async function exposeSyncAPI(t,e){const{setReady:r,setFailed:s,exposedApi:n}=prepareForExpose(t),i=await NodeSABSyncReceiveMessageTransport.create(),o=nodeEndpoint(e);return exposeSync(n,o,i),[r,s,n]}function prepareForExpose(t,e){setupTransferHandlers();const r=Promise.resolve();let s,n;const i=new Promise((c,l)=>{s=c,n=l}),o=proxyClone(t),a=new Proxy(o,{get:(c,l)=>l==="isConnected"?()=>r:l==="isReady"?()=>i:l in c?c[l]:e==null?void 0:e[l]});return{setReady:s,setFailed:n,exposedApi:a}}let isTransferHandlersSetup=!1;function setupTransferHandlers(){if(isTransferHandlersSetup)return;isTransferHandlersSetup=!0,transferHandlers.set("EVENT",{canHandle:r=>r instanceof CustomEvent,serialize:r=>[{detail:r.detail},[]],deserialize:r=>r}),transferHandlers.set("FUNCTION",{canHandle:r=>typeof r=="function",serialize(r){const{port1:s,port2:n}=new MessageChannel;return expose(r,s),[n,[n]]},deserialize(r){return r.start(),wrap(r)}}),transferHandlers.set("MESSAGE_PORT",{canHandle:r=>r instanceof MessagePort,serialize(r){return[r,[r]]},deserialize(r){return r}}),transferHandlers.set("PHPResponse",{canHandle:r=>typeof r=="object"&&r!==null&&"headers"in r&&"bytes"in r&&"errors"in r&&"exitCode"in r&&"httpStatusCode"in r,serialize(r){return[r.toRawData(),[]]},deserialize(r){return PHPResponse.fromRawData(r)}});const t=transferHandlers.get("throw"),e=t==null?void 0:t.serialize;t.serialize=({value:r})=>{const s=e({value:r});return r.response&&(s[0].value.response=r.response),r.source&&(s[0].value.source=r.source),s},transferHandlers.set("StreamedPHPResponse",{canHandle:r=>r instanceof StreamedPHPResponse,serialize(r){const s=supportsTransferableStreams(),n=promiseToPort(r.exitCode);if(s)return[{__type:"StreamedPHPResponse",headers:r.headersStream,stdout:r.stdout,stderr:r.stderr,exitCodePort:n},[n]];const i=streamToPort(r.headersStream),o=streamToPort(r.stdout),a=streamToPort(r.stderr);return[{__type:"StreamedPHPResponse",headersPort:i,stdoutPort:o,stderrPort:a,exitCodePort:n},[i,o,a,n]]},deserialize(r){if(r.headers&&r.stdout&&r.stderr){const a=portToPromise(r.exitCodePort);return new StreamedPHPResponse(r.headers,r.stdout,r.stderr,a)}const s=portToStream(r.headersPort),n=portToStream(r.stdoutPort),i=portToStream(r.stderrPort),o=portToPromise(r.exitCodePort);return new StreamedPHPResponse(s,n,i,o)}})}function supportsTransferableStreams(){try{if(typeof ReadableStream>"u")return!1;const{port1:t}=new MessageChannel,e=new ReadableStream;t.postMessage(e);try{t.close()}catch{}return!0}catch{return!1}}function streamToPort(t){const{port1:e,port2:r}=new MessageChannel;return(async()=>{const s=t.getReader();try{for(;;){const{done:n,value:i}=await s.read();if(n){try{e.postMessage({t:"close"})}catch{}try{e.close()}catch{}break}if(i){const o=i.byteOffset===0&&i.byteLength===i.buffer.byteLength?i:i.slice(),a=o.buffer;try{e.postMessage({t:"chunk",b:a},[a])}catch{e.postMessage({t:"chunk",b:o.buffer.slice(0)})}}}}catch(n){try{e.postMessage({t:"error",m:(n==null?void 0:n.message)||String(n)})}catch{}}finally{try{e.close()}catch{}}})(),r}function portToStream(t){return new ReadableStream({start(e){const r=n=>{const i=n.data;if(i)switch(i.t){case"chunk":e.enqueue(new Uint8Array(i.b));break;case"close":e.close(),s();break;case"error":e.error(new Error(i.m||"Stream error")),s();break}},s=()=>{var n;try{(n=t.removeEventListener)==null||n.call(t,"message",r)}catch{}try{t.onmessage=null}catch{}try{t.close()}catch{}};t.addEventListener?t.addEventListener("message",r):t.on?t.on("message",n=>r({data:n})):t.onmessage=r,typeof t.start=="function"&&t.start()},cancel(){try{t.close()}catch{}}})}function promiseToPort(t){const{port1:e,port2:r}=new MessageChannel;return t.then(s=>{try{e.postMessage({t:"resolve",v:s})}catch{}}).catch(s=>{try{e.postMessage({t:"reject",m:(s==null?void 0:s.message)||String(s)})}catch{}}).finally(()=>{try{e.close()}catch{}}),r}function portToPromise(t){return new Promise((e,r)=>{const s=i=>{const o=i.data;o&&(o.t==="resolve"?(n(),e(o.v)):o.t==="reject"&&(n(),r(new Error(o.m||""))))},n=()=>{var i;try{(i=t.removeEventListener)==null||i.call(t,"message",s)}catch{}try{t.onmessage=null}catch{}try{t.close()}catch{}};t.addEventListener?t.addEventListener("message",s):t.on?t.on("message",i=>s({data:i})):t.onmessage=s,typeof t.start=="function"&&t.start()})}const throwTransferHandler=transferHandlers.get("throw"),throwTransferHandlerCustom={canHandle:throwTransferHandler.canHandle,serialize:({value:t})=>{let e;return t instanceof Error?(e={isError:!0,value:serializeError(t)},e.value.originalErrorClassName=t.constructor.name):e={isError:!1,value:t},[e,[]]},deserialize:t=>{if(t.isError){const e=deserializeError(t.value),r=new Error("Comlink method call failed");let s=e;for(;s.cause;)s=s.cause;throw s.cause=r,e}throw t.value}};transferHandlers.set("throw",throwTransferHandlerCustom);function proxyClone(t){return new Proxy(t,{get(e,r){switch(typeof e[r]){case"function":return(...s)=>e[r](...s);case"object":return e[r]===null?e[r]:proxyClone(e[r]);case"undefined":case"number":case"string":return e[r];default:return proxy(e[r])}}})}exports.DEFAULT_BASE_URL=DEFAULT_BASE_URL;exports.FSHelpers=FSHelpers;exports.HttpCookieStore=HttpCookieStore;exports.LatestSupportedPHPVersion=LatestSupportedPHPVersion;exports.PHP=PHP;exports.PHPExecutionFailureError=PHPExecutionFailureError;exports.PHPProcessManager=PHPProcessManager;exports.PHPRequestHandler=PHPRequestHandler;exports.PHPResponse=PHPResponse;exports.PHPWorker=PHPWorker;exports.StreamedPHPResponse=StreamedPHPResponse;exports.SupportedPHPVersions=SupportedPHPVersions;exports.SupportedPHPVersionsList=SupportedPHPVersionsList;exports.UnhandledRejectionsTarget=UnhandledRejectionsTarget;exports.__private__dont__use=__private__dont__use;exports.applyRewriteRules=applyRewriteRules;exports.consumeAPI=consumeAPI;exports.consumeAPISync=consumeAPISync;exports.ensurePathPrefix=ensurePathPrefix;exports.exposeAPI=exposeAPI;exports.exposeSyncAPI=exposeSyncAPI;exports.getLoadedRuntime=getLoadedRuntime;exports.getPhpIniEntries=getPhpIniEntries;exports.isExitCode=isExitCode;exports.isPathToSharedFS=isPathToSharedFS;exports.iterateFiles=iteratePhpFiles;exports.loadPHPRuntime=loadPHPRuntime;exports.prettyPrintFullStackTrace=prettyPrintFullStackTrace;exports.printDebugDetails=printDebugDetails;exports.printResponseDebugDetails=printResponseDebugDetails;exports.proxyFileSystem=proxyFileSystem;exports.removePathPrefix=removePathPrefix;exports.rotatePHPRuntime=rotatePHPRuntime;exports.sandboxedSpawnHandlerFactory=sandboxedSpawnHandlerFactory;exports.setPhpIniEntries=setPhpIniEntries;exports.toRelativeUrl=toRelativeUrl;exports.withPHPIniValues=withPHPIniValues;exports.writeFiles=writeFiles;exports.writeFilesStreamToPhp=writeFilesStreamToPhp;
101
+ */const WireValueType={RAW:"RAW",HANDLER:"HANDLER"},MessageType={GET:"GET",SET:"SET",APPLY:"APPLY",CONSTRUCT:"CONSTRUCT",ENDPOINT:"ENDPOINT",RELEASE:"RELEASE"},isObject=t=>typeof t=="object"&&t!==null||typeof t=="function",proxyTransferHandler={canHandle:t=>isObject(t)&&t[proxyMarker],serialize(t){const{port1:e,port2:r}=new MessageChannel;return expose(t,e),[r,[r]]},deserialize(t){return t.start(),wrap(t)}},throwTransferHandler$1={canHandle:t=>isObject(t)&&throwMarker in t,serialize({value:t}){let e;return t instanceof Error?e={isError:!0,value:{message:t.message,name:t.name,stack:t.stack}}:e={isError:!1,value:t},[e,[]]},deserialize(t){throw t.isError?Object.assign(new Error(t.value.message),t.value):t.value}},transferHandlers=new Map([["proxy",proxyTransferHandler],["throw",throwTransferHandler$1]]);function isAllowedOrigin(t,e){for(const r of t)if(e===r||r==="*"||r instanceof RegExp&&r.test(e))return!0;return!1}function expose(t,e=globalThis,r=["*"],s){e.addEventListener("message",function n(i){if(!i||!i.data)return;if(!isAllowedOrigin(r,i.origin)){console.warn(`Invalid origin '${i.origin}' for comlink proxy`);return}const{id:o,type:a,path:c}={path:[],...i.data},l=(i.data.argumentList||[]).map(fromWireValue);let p;try{const d=c.slice(0,-1).reduce((g,H)=>g[H],t),f=c.reduce((g,H)=>g[H],t);switch(a){case MessageType.GET:p=f;break;case MessageType.SET:d[c.slice(-1)[0]]=fromWireValue(i.data.value),p=!0;break;case MessageType.APPLY:p=f.apply(d,l);break;case MessageType.CONSTRUCT:{const g=new f(...l);p=proxy(g)}break;case MessageType.ENDPOINT:{const{port1:g,port2:H}=new MessageChannel;expose(t,H),p=transfer(g,[g])}break;case MessageType.RELEASE:p=void 0;break;default:return}}catch(d){p={value:d,[throwMarker]:0}}Promise.resolve(p).catch(d=>({value:d,[throwMarker]:0})).then(d=>{const[f,g]=toWireValue(d);e.postMessage({...f,id:o},g),a===MessageType.RELEASE&&(e.removeEventListener("message",n),closeEndPoint(e),finalizer in t&&typeof t[finalizer]=="function"&&t[finalizer]())}).catch(()=>{const[d,f]=toWireValue({value:new TypeError("Unserializable return value"),[throwMarker]:0});e.postMessage({...d,id:o},f)}).finally(()=>{s==null||s(i)})}),e.start&&e.start()}function isMessagePort(t){return t.constructor.name==="MessagePort"}function closeEndPoint(t){isMessagePort(t)&&t.close()}function wrap(t,e){const r=new Map;return t.addEventListener("message",function(n){const{data:i}=n;if(!i||!i.id)return;const o=r.get(i.id);if(o)try{o(i)}finally{r.delete(i.id)}}),createProxy(t,r,[],e)}function throwIfProxyReleased(t){if(t)throw new Error("Proxy has been released and is not useable")}function releaseEndpoint(t){return requestResponseMessage(t,new Map,{type:MessageType.RELEASE}).then(()=>{closeEndPoint(t)})}const proxyCounter=new WeakMap,proxyFinalizers="FinalizationRegistry"in globalThis&&new FinalizationRegistry(t=>{const e=(proxyCounter.get(t)||0)-1;proxyCounter.set(t,e),e===0&&releaseEndpoint(t)});function registerProxy(t,e){const r=(proxyCounter.get(e)||0)+1;proxyCounter.set(e,r),proxyFinalizers&&proxyFinalizers.register(t,e,t)}function unregisterProxy(t){proxyFinalizers&&proxyFinalizers.unregister(t)}function createProxy(t,e,r=[],s=function(){}){let n=!1;const i=new Proxy(s,{get(o,a){if(throwIfProxyReleased(n),a===releaseProxy)return()=>{unregisterProxy(i),releaseEndpoint(t),e.clear(),n=!0};if(a==="then"){if(r.length===0)return{then:()=>i};const c=requestResponseMessage(t,e,{type:MessageType.GET,path:r.map(l=>l.toString())}).then(fromWireValue);return c.then.bind(c)}return createProxy(t,e,[...r,a])},set(o,a,c){throwIfProxyReleased(n);const[l,p]=toWireValue(c);return requestResponseMessage(t,e,{type:MessageType.SET,path:[...r,a].map(d=>d.toString()),value:l},p).then(fromWireValue)},apply(o,a,c){throwIfProxyReleased(n);const l=r[r.length-1];if(l===createEndpoint)return requestResponseMessage(t,e,{type:MessageType.ENDPOINT}).then(fromWireValue);if(l==="bind")return createProxy(t,e,r.slice(0,-1));const[p,d]=processArguments(c);return requestResponseMessage(t,e,{type:MessageType.APPLY,path:r.map(f=>f.toString()),argumentList:p},d).then(fromWireValue)},construct(o,a){throwIfProxyReleased(n);const[c,l]=processArguments(a);return requestResponseMessage(t,e,{type:MessageType.CONSTRUCT,path:r.map(p=>p.toString()),argumentList:c},l).then(fromWireValue)}});return registerProxy(i,t),i}function myFlat(t){return Array.prototype.concat.apply([],t)}function processArguments(t){const e=t.map(toWireValue);return[e.map(r=>r[0]),myFlat(e.map(r=>r[1]))]}const transferCache=new WeakMap;function transfer(t,e){return transferCache.set(t,e),t}function proxy(t){return Object.assign(t,{[proxyMarker]:!0})}function windowEndpoint(t,e=globalThis,r="*"){return{postMessage:(s,n)=>t.postMessage(s,r,n),addEventListener:e.addEventListener.bind(e),removeEventListener:e.removeEventListener.bind(e)}}function toWireValue(t){for(const[e,r]of transferHandlers)if(r.canHandle(t)){const[s,n]=r.serialize(t);return[{type:WireValueType.HANDLER,name:e,value:s},n]}return[{type:WireValueType.RAW,value:t},transferCache.get(t)||[]]}function fromWireValue(t){switch(t.type){case WireValueType.HANDLER:return transferHandlers.get(t.name).deserialize(t.value);case WireValueType.RAW:return t.value}}function requestResponseMessage(t,e,r,s){return new Promise(n=>{const i=generateUUID();e.set(i,n),t.start&&t.start(),t.postMessage({id:i,...r},s)})}function generateUUID(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function nodeEndpoint(t){const e=new WeakMap;return{postMessage:t.postMessage.bind(t),addEventListener:(r,s)=>{const n=i=>{"handleEvent"in s?s.handleEvent({data:i}):s({data:i})};t.on("message",n),e.set(s,n)},removeEventListener:(r,s)=>{const n=e.get(s);n&&(t.off("message",n),e.delete(s))},start:t.start&&t.start.bind(t)}}const list=[Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError,globalThis.DOMException,globalThis.AssertionError,globalThis.SystemError].filter(Boolean).map(t=>[t.name,t]),errorConstructors=new Map(list);class NonError extends Error{constructor(e){super(NonError._prepareSuperMessage(e)),this.name="NonError"}static _prepareSuperMessage(e){try{return JSON.stringify(e)}catch{return String(e)}}}const errorProperties=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1},{property:"errors",enumerable:!1}],toJsonWasCalled=new WeakSet,toJSON=t=>{toJsonWasCalled.add(t);const e=t.toJSON();return toJsonWasCalled.delete(t),e},newError=t=>{const e=errorConstructors.get(t)??Error;return e===AggregateError?new e([]):new e},destroyCircular=({from:t,seen:e,to:r,forceEnumerable:s,maxDepth:n,depth:i,useToJSON:o,serialize:a})=>{if(r||(Array.isArray(t)?r=[]:!a&&isErrorLike(t)?r=newError(t.name):r={}),e.push(t),i>=n)return r;if(o&&typeof t.toJSON=="function"&&!toJsonWasCalled.has(t))return toJSON(t);const c=l=>destroyCircular({from:l,seen:[...e],forceEnumerable:s,maxDepth:n,depth:i,useToJSON:o,serialize:a});for(const[l,p]of Object.entries(t)){if(p&&p instanceof Uint8Array&&p.constructor.name==="Buffer"){r[l]="[object Buffer]";continue}if(p!==null&&typeof p=="object"&&typeof p.pipe=="function"){r[l]="[object Stream]";continue}if(typeof p!="function"){if(!p||typeof p!="object"){try{r[l]=p}catch{}continue}if(!e.includes(t[l])){i++,r[l]=c(t[l]);continue}r[l]="[Circular]"}}if(a||r instanceof Error)for(const{property:l,enumerable:p}of errorProperties)t[l]!==void 0&&t[l]!==null&&Object.defineProperty(r,l,{value:isErrorLike(t[l])||Array.isArray(t[l])?c(t[l]):t[l],enumerable:s?!0:p,configurable:!0,writable:!0});return r};function serializeError(t,e={}){const{maxDepth:r=Number.POSITIVE_INFINITY,useToJSON:s=!0}=e;return typeof t=="object"&&t!==null?destroyCircular({from:t,seen:[],forceEnumerable:!0,maxDepth:r,depth:0,useToJSON:s,serialize:!0}):typeof t=="function"?`[Function: ${t.name||"anonymous"}]`:t}function deserializeError(t,e={}){const{maxDepth:r=Number.POSITIVE_INFINITY}=e;return t instanceof Error?t:isMinimumViableSerializedError(t)?destroyCircular({from:t,seen:[],to:newError(t.name),maxDepth:r,depth:0,serialize:!1}):new NonError(t)}function isErrorLike(t){return!!t&&typeof t=="object"&&typeof t.name=="string"&&typeof t.message=="string"&&typeof t.stack=="string"}function isMinimumViableSerializedError(t){return!!t&&typeof t=="object"&&typeof t.message=="string"&&!Array.isArray(t)}async function consumeAPISync(t){setupTransferHandlers();const e=await NodeSABSyncReceiveMessageTransport.create();return wrapSync(t,e)}function consumeAPI(t,e=void 0){setupTransferHandlers();let r;(typeof document>"u"?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&_documentCurrentScript.tagName.toUpperCase()==="SCRIPT"&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href).startsWith("file://")?r=nodeEndpoint(t):r=t instanceof Worker?t:windowEndpoint(t,e);const n=wrap(r),i=proxyClone(n);return new Proxy(i,{get:(o,a)=>a==="isConnected"?async()=>{for(;;)try{await runWithTimeout(n.isConnected(),200);break}catch{}}:n[a]})}async function runWithTimeout(t,e){return new Promise((r,s)=>{setTimeout(s,e),t.then(r)})}function exposeAPI(t,e,r){const{setReady:s,setFailed:n,exposedApi:i}=prepareForExpose(t,e);let o;return r?o=nodeEndpoint(r):o=typeof window<"u"?windowEndpoint(self.parent):void 0,expose(i,o),[s,n,i]}async function exposeSyncAPI(t,e){const{setReady:r,setFailed:s,exposedApi:n}=prepareForExpose(t),i=await NodeSABSyncReceiveMessageTransport.create(),o=nodeEndpoint(e);return exposeSync(n,o,i),[r,s,n]}function prepareForExpose(t,e){setupTransferHandlers();const r=Promise.resolve();let s,n;const i=new Promise((c,l)=>{s=c,n=l}),o=proxyClone(t),a=new Proxy(o,{get:(c,l)=>l==="isConnected"?()=>r:l==="isReady"?()=>i:l in c?c[l]:e==null?void 0:e[l]});return{setReady:s,setFailed:n,exposedApi:a}}let isTransferHandlersSetup=!1;function setupTransferHandlers(){if(isTransferHandlersSetup)return;isTransferHandlersSetup=!0,transferHandlers.set("EVENT",{canHandle:r=>r instanceof CustomEvent,serialize:r=>[{detail:r.detail},[]],deserialize:r=>r}),transferHandlers.set("FUNCTION",{canHandle:r=>typeof r=="function",serialize(r){const{port1:s,port2:n}=new MessageChannel;return expose(r,s),[n,[n]]},deserialize(r){return r.start(),wrap(r)}}),transferHandlers.set("MESSAGE_PORT",{canHandle:r=>r instanceof MessagePort,serialize(r){return[r,[r]]},deserialize(r){return r}}),transferHandlers.set("PHPResponse",{canHandle:r=>typeof r=="object"&&r!==null&&"headers"in r&&"bytes"in r&&"errors"in r&&"exitCode"in r&&"httpStatusCode"in r,serialize(r){return[r.toRawData(),[]]},deserialize(r){return PHPResponse.fromRawData(r)}});const t=transferHandlers.get("throw"),e=t==null?void 0:t.serialize;t.serialize=({value:r})=>{const s=e({value:r});return r.response&&(s[0].value.response=r.response),r.source&&(s[0].value.source=r.source),s},transferHandlers.set("StreamedPHPResponse",{canHandle:r=>r instanceof StreamedPHPResponse,serialize(r){const s=supportsTransferableStreams(),n=promiseToPort(r.exitCode);if(s)return[{__type:"StreamedPHPResponse",headers:r.headersStream,stdout:r.stdout,stderr:r.stderr,exitCodePort:n},[n]];const i=streamToPort(r.headersStream),o=streamToPort(r.stdout),a=streamToPort(r.stderr);return[{__type:"StreamedPHPResponse",headersPort:i,stdoutPort:o,stderrPort:a,exitCodePort:n},[i,o,a,n]]},deserialize(r){if(r.headers&&r.stdout&&r.stderr){const a=portToPromise(r.exitCodePort);return new StreamedPHPResponse(r.headers,r.stdout,r.stderr,a)}const s=portToStream(r.headersPort),n=portToStream(r.stdoutPort),i=portToStream(r.stderrPort),o=portToPromise(r.exitCodePort);return new StreamedPHPResponse(s,n,i,o)}})}function supportsTransferableStreams(){try{if(typeof ReadableStream>"u")return!1;const{port1:t}=new MessageChannel,e=new ReadableStream;t.postMessage(e);try{t.close()}catch{}return!0}catch{return!1}}function streamToPort(t){const{port1:e,port2:r}=new MessageChannel;return(async()=>{const s=t.getReader();try{for(;;){const{done:n,value:i}=await s.read();if(n){try{e.postMessage({t:"close"})}catch{}try{e.close()}catch{}break}if(i){const o=i.byteOffset===0&&i.byteLength===i.buffer.byteLength?i:i.slice(),a=o.buffer;try{e.postMessage({t:"chunk",b:a},[a])}catch{e.postMessage({t:"chunk",b:o.buffer.slice(0)})}}}}catch(n){try{e.postMessage({t:"error",m:(n==null?void 0:n.message)||String(n)})}catch{}}finally{try{e.close()}catch{}}})(),r}function portToStream(t){return new ReadableStream({start(e){const r=n=>{const i=n.data;if(i)switch(i.t){case"chunk":e.enqueue(new Uint8Array(i.b));break;case"close":e.close(),s();break;case"error":e.error(new Error(i.m||"Stream error")),s();break}},s=()=>{var n;try{(n=t.removeEventListener)==null||n.call(t,"message",r)}catch{}try{t.onmessage=null}catch{}try{t.close()}catch{}};t.addEventListener?t.addEventListener("message",r):t.on?t.on("message",n=>r({data:n})):t.onmessage=r,typeof t.start=="function"&&t.start()},cancel(){try{t.close()}catch{}}})}function promiseToPort(t){const{port1:e,port2:r}=new MessageChannel;return t.then(s=>{try{e.postMessage({t:"resolve",v:s})}catch{}}).catch(s=>{try{e.postMessage({t:"reject",m:(s==null?void 0:s.message)||String(s)})}catch{}}).finally(()=>{try{e.close()}catch{}}),r}function portToPromise(t){return new Promise((e,r)=>{const s=i=>{const o=i.data;o&&(o.t==="resolve"?(n(),e(o.v)):o.t==="reject"&&(n(),r(new Error(o.m||""))))},n=()=>{var i;try{(i=t.removeEventListener)==null||i.call(t,"message",s)}catch{}try{t.onmessage=null}catch{}try{t.close()}catch{}};t.addEventListener?t.addEventListener("message",s):t.on?t.on("message",i=>s({data:i})):t.onmessage=s,typeof t.start=="function"&&t.start()})}const throwTransferHandler=transferHandlers.get("throw"),throwTransferHandlerCustom={canHandle:throwTransferHandler.canHandle,serialize:({value:t})=>{let e;return t instanceof Error?(e={isError:!0,value:serializeError(t)},e.value.originalErrorClassName=t.constructor.name):e={isError:!1,value:t},[e,[]]},deserialize:t=>{if(t.isError){const e=deserializeError(t.value),r=new Error("Comlink method call failed");let s=e;for(;s.cause;)s=s.cause;throw s.cause=r,e}throw t.value}};transferHandlers.set("throw",throwTransferHandlerCustom);function proxyClone(t){return new Proxy(t,{get(e,r){switch(typeof e[r]){case"function":return(...s)=>e[r](...s);case"object":return e[r]===null?e[r]:proxyClone(e[r]);case"undefined":case"number":case"string":return e[r];default:return proxy(e[r])}}})}exports.DEFAULT_BASE_URL=DEFAULT_BASE_URL;exports.FSHelpers=FSHelpers;exports.HttpCookieStore=HttpCookieStore;exports.LatestSupportedPHPVersion=LatestSupportedPHPVersion;exports.PHP=PHP;exports.PHPExecutionFailureError=PHPExecutionFailureError;exports.PHPProcessManager=PHPProcessManager;exports.PHPRequestHandler=PHPRequestHandler;exports.PHPResponse=PHPResponse;exports.PHPWorker=PHPWorker;exports.StreamedPHPResponse=StreamedPHPResponse;exports.SupportedPHPVersions=SupportedPHPVersions;exports.SupportedPHPVersionsList=SupportedPHPVersionsList;exports.UnhandledRejectionsTarget=UnhandledRejectionsTarget;exports.__private__dont__use=__private__dont__use;exports.applyRewriteRules=applyRewriteRules;exports.consumeAPI=consumeAPI;exports.consumeAPISync=consumeAPISync;exports.ensurePathPrefix=ensurePathPrefix;exports.exposeAPI=exposeAPI;exports.exposeSyncAPI=exposeSyncAPI;exports.getLoadedRuntime=getLoadedRuntime;exports.getPhpIniEntries=getPhpIniEntries;exports.inferMimeType=inferMimeType;exports.isExitCode=isExitCode;exports.isPathToSharedFS=isPathToSharedFS;exports.iterateFiles=iteratePhpFiles;exports.loadPHPRuntime=loadPHPRuntime;exports.prettyPrintFullStackTrace=prettyPrintFullStackTrace;exports.printDebugDetails=printDebugDetails;exports.printResponseDebugDetails=printResponseDebugDetails;exports.proxyFileSystem=proxyFileSystem;exports.removePathPrefix=removePathPrefix;exports.rotatePHPRuntime=rotatePHPRuntime;exports.sandboxedSpawnHandlerFactory=sandboxedSpawnHandlerFactory;exports.setPhpIniEntries=setPhpIniEntries;exports.toRelativeUrl=toRelativeUrl;exports.withPHPIniValues=withPHPIniValues;exports.writeFiles=writeFiles;exports.writeFilesStreamToPhp=writeFilesStreamToPhp;
102
102
  //# sourceMappingURL=index.cjs.map