@php-wasm/fs-journal 0.6.1 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Z=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var a=(e,t,r)=>(Z(e,t,"read from private field"),r?r.call(e):t.get(e)),l=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},d=(e,t,r,s)=>(Z(e,t,"write to private field"),s?s.call(e,r):t.set(e,r),r);var p=(e,t,r)=>(Z(e,t,"access private method"),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});if(typeof File>"u"){class e extends Blob{constructor(r,s,i){super(r);let n;i!=null&&i.lastModified&&(n=new Date),(!n||isNaN(n.getFullYear()))&&(n=new Date),this.lastModifiedDate=n,this.lastModified=n.getMilliseconds(),this.name=s||""}}global.File=e}function asPromise(e){return new Promise(function(t,r){e.onload=e.onerror=function(s){e.onload=e.onerror=null,s.type==="load"?t(e.result):r(new Error("Failed to read the blob/file"))}})}typeof Blob.prototype.arrayBuffer>"u"&&(Blob.prototype.arrayBuffer=function(){const t=new FileReader;return t.readAsArrayBuffer(this),asPromise(t)});typeof Blob.prototype.text>"u"&&(Blob.prototype.text=function(){const t=new FileReader;return t.readAsText(this),asPromise(t)});function isByobSupported(){const e=new Uint8Array([1,2,3,4]),r=new File([e],"test").stream();try{return r.getReader({mode:"byob"}),!0}catch{return!1}}(typeof Blob.prototype.stream>"u"||!isByobSupported())&&(Blob.prototype.stream=function(){let e=0;const t=this;return new ReadableStream({type:"bytes",autoAllocateChunkSize:512*1024,async pull(r){const s=r.byobRequest.view,n=await t.slice(e,e+s.byteLength).arrayBuffer(),o=new Uint8Array(n);new Uint8Array(s.buffer).set(o);const c=o.byteLength;r.byobRequest.respond(c),e+=c,e>=t.size&&r.close()}})});if(typeof CustomEvent>"u"){class e extends Event{constructor(r,s={}){super(r,s),this.detail=s.detail}initCustomEvent(){}}globalThis.CustomEvent=e}typeof crypto>"u"&&Promise.resolve().then(()=>require("./__vite-browser-external-b3701507.cjs")).then(e=>{global.crypto=e});const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends Event{constructor(t,r={}){super(t),this[kError]=r.error===void 0?null:r.error,this[kMessage]=r.message===void 0?"":r.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent2.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent2.prototype,"message",{enumerable:!0});const ErrorEvent=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:ErrorEvent2;function isExitCodeZero(e){return e instanceof Error?"exitCode"in e&&(e==null?void 0:e.exitCode)===0||(e==null?void 0:e.name)==="ExitStatus"&&"status"in e&&e.status===0:!1}class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(t,r){++this.listenersCount,super.addEventListener(t,r)}removeEventListener(t,r){--this.listenersCount,super.removeEventListener(t,r)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(e){e.asm={...e.asm};const t=new UnhandledRejectionsTarget;for(const r in e.asm)if(typeof e.asm[r]=="function"){const s=e.asm[r];e.asm[r]=function(...i){var n;try{return s(...i)}catch(o){if(!(o instanceof Error))throw o;const c=clarifyErrorMessage(o,(n=e.lastAsyncifyStackSource)==null?void 0:n.stack);if(e.lastAsyncifyStackSource&&(o.cause=e.lastAsyncifyStackSource),t.hasListeners()){t.dispatchEvent(new ErrorEvent("error",{error:o,message:c}));return}throw isExitCodeZero(o)||showCriticalErrorBox(c),o}}}return t}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(e,t){if(e.message==="unreachable"){let r=UNREACHABLE_ERROR;t||(r+=`
1
+ "use strict";var Y=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var o=(e,t,r)=>(Y(e,t,"read from private field"),r?r.call(e):t.get(e)),l=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},h=(e,t,r,s)=>(Y(e,t,"write to private field"),s?s.call(e,r):t.set(e,r),r);var f=(e,t,r)=>(Y(e,t,"access private method"),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});if(typeof File>"u"){class e extends Blob{constructor(r,s,n){super(r);let i;n!=null&&n.lastModified&&(i=new Date),(!i||isNaN(i.getFullYear()))&&(i=new Date),this.lastModifiedDate=i,this.lastModified=i.getMilliseconds(),this.name=s||""}}global.File=e}function asPromise(e){return new Promise(function(t,r){e.onload=e.onerror=function(s){e.onload=e.onerror=null,s.type==="load"?t(e.result):r(new Error("Failed to read the blob/file"))}})}typeof Blob.prototype.arrayBuffer>"u"&&(Blob.prototype.arrayBuffer=function(){const t=new FileReader;return t.readAsArrayBuffer(this),asPromise(t)});typeof Blob.prototype.text>"u"&&(Blob.prototype.text=function(){const t=new FileReader;return t.readAsText(this),asPromise(t)});function isByobSupported(){const e=new Uint8Array([1,2,3,4]),r=new File([e],"test").stream();try{return r.getReader({mode:"byob"}),!0}catch{return!1}}(typeof Blob.prototype.stream>"u"||!isByobSupported())&&(Blob.prototype.stream=function(){let e=0;const t=this;return new ReadableStream({type:"bytes",autoAllocateChunkSize:512*1024,async pull(r){const s=r.byobRequest.view,i=await t.slice(e,e+s.byteLength).arrayBuffer(),a=new Uint8Array(i);new Uint8Array(s.buffer).set(a);const c=a.byteLength;r.byobRequest.respond(c),e+=c,e>=t.size&&r.close()}})});if(typeof CustomEvent>"u"){class e extends Event{constructor(r,s={}){super(r,s),this.detail=s.detail}initCustomEvent(){}}globalThis.CustomEvent=e}const kError=Symbol("error"),kMessage=Symbol("message");class ErrorEvent2 extends Event{constructor(t,r={}){super(t),this[kError]=r.error===void 0?null:r.error,this[kMessage]=r.message===void 0?"":r.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent2.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent2.prototype,"message",{enumerable:!0});const ErrorEvent=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:ErrorEvent2;function isExitCodeZero(e){return e instanceof Error?"exitCode"in e&&(e==null?void 0:e.exitCode)===0||(e==null?void 0:e.name)==="ExitStatus"&&"status"in e&&e.status===0:!1}class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(t,r){++this.listenersCount,super.addEventListener(t,r)}removeEventListener(t,r){--this.listenersCount,super.removeEventListener(t,r)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(e){e.asm={...e.asm};const t=new UnhandledRejectionsTarget;for(const r in e.asm)if(typeof e.asm[r]=="function"){const s=e.asm[r];e.asm[r]=function(...n){var i;try{return s(...n)}catch(a){if(!(a instanceof Error))throw a;const c=clarifyErrorMessage(a,(i=e.lastAsyncifyStackSource)==null?void 0:i.stack);if(e.lastAsyncifyStackSource&&(a.cause=e.lastAsyncifyStackSource),t.hasListeners()){t.dispatchEvent(new ErrorEvent("error",{error:a,message:c}));return}throw isExitCodeZero(a)||showCriticalErrorBox(c),a}}}return t}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(e,t){if(e.message==="unreachable"){let r=UNREACHABLE_ERROR;t||(r+=`
2
2
 
3
3
  This stack trace is lacking. For a better one initialize
4
4
  the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
@@ -32,9 +32,13 @@ CLI option:
32
32
  ${eol}
33
33
  ${bold} WASM ERROR${reset}${redBg}`);for(const t of e.split(`
34
34
  `))console.log(`${eol} ${t} `);console.log(`${reset}`)}}function extractPHPFunctionsFromStack(e){try{const t=e.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(t))}catch{return[]}}class Semaphore{constructor({concurrency:t}){this._running=0,this.concurrency=t,this.queue=[]}get running(){return this._running}async acquire(){for(;;)if(this._running>=this.concurrency)await new Promise(t=>this.queue.push(t));else{this._running++;let t=!1;return()=>{t||(t=!0,this._running--,this.queue.length>0&&this.queue.shift()())}}}async run(t){const r=await this.acquire();try{return await t()}finally{r()}}}function joinPaths(...e){let t=e.join("/");const r=t[0]==="/",s=t.substring(t.length-1)==="/";return t=normalizePath$1(t),!t&&!r&&(t="."),t&&s&&(t+="/"),t}function basename(e){if(e==="/")return"/";e=normalizePath$1(e);const t=e.lastIndexOf("/");return t===-1?e:e.substr(t+1)}function normalizePath$1(e){const t=e[0]==="/";return e=normalizePathsArray(e.split("/").filter(r=>!!r),!t).join("/"),(t?"/":"")+e.replace(/\/$/,"")}function normalizePathsArray(e,t){let r=0;for(let s=e.length-1;s>=0;s--){const i=e[s];i==="."?e.splice(s,1):i===".."?(e.splice(s,1),r++):r&&(e.splice(s,1),r--)}if(t)for(;r;r--)e.unshift("..");return e}function createSpawnHandler(e){return function(t){const r=new ChildProcess,s=new ProcessApi(r);return setTimeout(async()=>{await e(t,s),r.emit("spawn",!0)}),r}}class EventEmitter{constructor(){this.listeners={}}emit(t,r){this.listeners[t]&&this.listeners[t].forEach(function(s){s(r)})}on(t,r){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(r)}}class ProcessApi extends EventEmitter{constructor(t){super(),this.childProcess=t,this.exited=!1,this.stdinData=[],t.on("stdin",r=>{this.stdinData?this.stdinData.push(r.slice()):this.emit("stdin",r)})}stdout(t){typeof t=="string"&&(t=new TextEncoder().encode(t)),this.childProcess.stdout.emit("data",t)}stderr(t){typeof t=="string"&&(t=new TextEncoder().encode(t)),this.childProcess.stderr.emit("data",t)}exit(t){this.exited||(this.exited=!0,this.childProcess.emit("exit",t))}flushStdin(){if(this.stdinData)for(let t=0;t<this.stdinData.length;t++)this.emit("stdin",this.stdinData[t]);this.stdinData=null}}let lastPid=9743;class ChildProcess extends EventEmitter{constructor(t=lastPid++){super(),this.pid=t,this.stdout=new EventEmitter,this.stderr=new EventEmitter;const r=this;this.stdin={write:s=>{r.emit("stdin",s)}}}}ReadableStream.prototype[Symbol.asyncIterator]||(ReadableStream.prototype[Symbol.asyncIterator]=async function*(){const e=this.getReader();try{for(;;){const{done:t,value:r}=await e.read();if(t)return;yield r}}finally{e.releaseLock()}},ReadableStream.prototype.iterate=ReadableStream.prototype[Symbol.asyncIterator]);class PHPResponse{constructor(t,r,s,i="",n=0){this.httpStatusCode=t,this.headers=r,this.bytes=s,this.exitCode=n,this.errors=i}static fromRawData(t){return new PHPResponse(t.httpStatusCode,t.headers,t.bytes,t.errors,t.exitCode)}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}var b,F;class PHPBrowser{constructor(t,r={}){l(this,b,void 0);l(this,F,void 0);this.requestHandler=t,d(this,b,{}),d(this,F,{handleRedirects:!1,maxRedirects:4,...r})}async request(t,r=0){const s=await this.requestHandler.request({...t,headers:{...t.headers,cookie:this.serializeCookies()}});if(s.headers["set-cookie"]&&this.setCookies(s.headers["set-cookie"]),a(this,F).handleRedirects&&s.headers.location&&r<a(this,F).maxRedirects){const i=new URL(s.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:i.toString(),method:"GET",headers:{}},r+1)}return s}pathToInternalUrl(t){return this.requestHandler.pathToInternalUrl(t)}internalUrlToPath(t){return this.requestHandler.internalUrlToPath(t)}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}setCookies(t){for(const r of t)try{if(!r.includes("="))continue;const s=r.indexOf("="),i=r.substring(0,s),n=r.substring(s+1).split(";")[0];a(this,b)[i]=n}catch(s){console.error(s)}}serializeCookies(){const t=[];for(const r in a(this,b))t.push(`${r}=${a(this,b)[r]}`);return t.join("; ")}}b=new WeakMap,F=new WeakMap;const DEFAULT_BASE_URL="http://example.com";function toRelativeUrl(e){return e.toString().substring(e.origin.length)}function removePathPrefix(e,t){return!t||!e.startsWith(t)?e:e.substring(t.length)}function ensurePathPrefix(e,t){return!t||e.startsWith(t)?e:t+e}var E,x,N,R,k,m,C,S,B,Q,O,X,L,ee;class PHPRequestHandler{constructor(t,r={}){l(this,B);l(this,O);l(this,L);l(this,E,void 0);l(this,x,void 0);l(this,N,void 0);l(this,R,void 0);l(this,k,void 0);l(this,m,void 0);l(this,C,void 0);l(this,S,void 0);d(this,S,new Semaphore({concurrency:1}));const{documentRoot:s="/www/",absoluteUrl:i=typeof location=="object"?location==null?void 0:location.href:""}=r;this.php=t,d(this,E,s);const n=new URL(i);d(this,N,n.hostname),d(this,R,n.port?Number(n.port):n.protocol==="https:"?443:80),d(this,x,(n.protocol||"").replace(":",""));const o=a(this,R)!==443&&a(this,R)!==80;d(this,k,[a(this,N),o?`:${a(this,R)}`:""].join("")),d(this,m,n.pathname.replace(/\/+$/,"")),d(this,C,[`${a(this,x)}://`,a(this,k),a(this,m)].join(""))}pathToInternalUrl(t){return`${this.absoluteUrl}${t}`}internalUrlToPath(t){const r=new URL(t);return r.pathname.startsWith(a(this,m))&&(r.pathname=r.pathname.slice(a(this,m).length)),toRelativeUrl(r)}get isRequestRunning(){return a(this,S).running>0}get absoluteUrl(){return a(this,C)}get documentRoot(){return a(this,E)}async request(t){const r=t.url.startsWith("http://")||t.url.startsWith("https://"),s=new URL(t.url,r?void 0:DEFAULT_BASE_URL),i=removePathPrefix(s.pathname,a(this,m)),n=`${a(this,E)}${i}`;return seemsLikeAPHPRequestHandlerPath(n)?await p(this,O,X).call(this,t,s):p(this,B,Q).call(this,n)}}E=new WeakMap,x=new WeakMap,N=new WeakMap,R=new WeakMap,k=new WeakMap,m=new WeakMap,C=new WeakMap,S=new WeakMap,B=new WeakSet,Q=function(t){if(!this.php.fileExists(t))return new PHPResponse(404,{"x-file-type":["static"]},new TextEncoder().encode("404 File not found"));const r=this.php.readFileAsBuffer(t);return new PHPResponse(200,{"content-length":[`${r.byteLength}`],"content-type":[inferMimeType(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},r)},O=new WeakSet,X=async function(t,r){var i,n,o;if(a(this,S).running>0&&((i=t.headers)==null?void 0:i["x-request-issuer"])==="php")return console.warn("Possible deadlock: Called request() before the previous request() have finished. PHP likely issued an HTTP call to itself. Normally this would lead to infinite waiting as Request 1 holds the lock that the Request 2 is waiting to acquire. That's not useful, so PHPRequestHandler will return error 502 instead."),new PHPResponse(502,{},new TextEncoder().encode("502 Bad Gateway"));const s=await a(this,S).acquire();try{this.php.addServerGlobalEntry("REMOTE_ADDR","127.0.0.1"),this.php.addServerGlobalEntry("DOCUMENT_ROOT",a(this,E)),this.php.addServerGlobalEntry("HTTPS",a(this,C).startsWith("https://")?"on":"");let c="GET";const h={host:a(this,k),...normalizeHeaders(t.headers||{})},f=[];if(t.files&&Object.keys(t.files).length){c="POST";for(const y in t.files){const M=t.files[y];f.push({key:y,name:M.name,type:M.type,data:new Uint8Array(await M.arrayBuffer())})}(n=h["content-type"])!=null&&n.startsWith("multipart/form-data")&&(t.formData=parseMultipartFormDataString(t.body||""),h["content-type"]="application/x-www-form-urlencoded",delete t.body)}let u;t.formData!==void 0?(c="POST",h["content-type"]=h["content-type"]||"application/x-www-form-urlencoded",u=new URLSearchParams(t.formData).toString()):u=t.body;let _;try{let y=r.pathname;if((o=t.headers)!=null&&o["x-rewrite-url"])try{y=new URL(t.headers["x-rewrite-url"]).pathname}catch{}_=p(this,L,ee).call(this,y)}catch{return new PHPResponse(404,{},new TextEncoder().encode("404 File not found"))}return await this.php.run({relativeUri:ensurePathPrefix(toRelativeUrl(r),a(this,m)),protocol:a(this,x),method:t.method||c,body:u,fileInfos:f,scriptPath:_,headers:h})}finally{s()}},L=new WeakSet,ee=function(t){let r=removePathPrefix(t,a(this,m));r.includes(".php")?r=r.split(".php")[0]+".php":(r.endsWith("/")||(r+="/"),r.endsWith("index.php")||(r+="index.php"));const s=`${a(this,E)}${r}`;if(this.php.fileExists(s))return s;throw new Error(`File not found: ${s}`)};function parseMultipartFormDataString(e){const t={},r=e.match(/--(.*)\r\n/);if(!r)return t;const s=r[1],i=e.split(`--${s}`);return i.shift(),i.pop(),i.forEach(n=>{const o=n.indexOf(`\r
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(t))}catch{return[]}}class Semaphore{constructor({concurrency:t}){this._running=0,this.concurrency=t,this.queue=[]}get running(){return this._running}async acquire(){for(;;)if(this._running>=this.concurrency)await new Promise(t=>this.queue.push(t));else{this._running++;let t=!1;return()=>{t||(t=!0,this._running--,this.queue.length>0&&this.queue.shift()())}}}async run(t){const r=await this.acquire();try{return await t()}finally{r()}}}function joinPaths(...e){let t=e.join("/");const r=t[0]==="/",s=t.substring(t.length-1)==="/";return t=normalizePath$1(t),!t&&!r&&(t="."),t&&s&&(t+="/"),t}function basename(e){if(e==="/")return"/";e=normalizePath$1(e);const t=e.lastIndexOf("/");return t===-1?e:e.substr(t+1)}function normalizePath$1(e){const t=e[0]==="/";return e=normalizePathsArray(e.split("/").filter(r=>!!r),!t).join("/"),(t?"/":"")+e.replace(/\/$/,"")}function normalizePathsArray(e,t){let r=0;for(let s=e.length-1;s>=0;s--){const n=e[s];n==="."?e.splice(s,1):n===".."?(e.splice(s,1),r++):r&&(e.splice(s,1),r--)}if(t)for(;r;r--)e.unshift("..");return e}function createSpawnHandler(e){return function(t){const r=new ChildProcess,s=new ProcessApi(r);return setTimeout(async()=>{await e(t,s),r.emit("spawn",!0)}),r}}class EventEmitter{constructor(){this.listeners={}}emit(t,r){this.listeners[t]&&this.listeners[t].forEach(function(s){s(r)})}on(t,r){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(r)}}class ProcessApi extends EventEmitter{constructor(t){super(),this.childProcess=t,this.exited=!1,this.stdinData=[],t.on("stdin",r=>{this.stdinData?this.stdinData.push(r.slice()):this.emit("stdin",r)})}stdout(t){typeof t=="string"&&(t=new TextEncoder().encode(t)),this.childProcess.stdout.emit("data",t)}stderr(t){typeof t=="string"&&(t=new TextEncoder().encode(t)),this.childProcess.stderr.emit("data",t)}exit(t){this.exited||(this.exited=!0,this.childProcess.emit("exit",t))}flushStdin(){if(this.stdinData)for(let t=0;t<this.stdinData.length;t++)this.emit("stdin",this.stdinData[t]);this.stdinData=null}}let lastPid=9743;class ChildProcess extends EventEmitter{constructor(t=lastPid++){super(),this.pid=t,this.stdout=new EventEmitter,this.stderr=new EventEmitter;const r=this;this.stdin={write:s=>{r.emit("stdin",s)}}}}ReadableStream.prototype[Symbol.asyncIterator]||(ReadableStream.prototype[Symbol.asyncIterator]=async function*(){const e=this.getReader();try{for(;;){const{done:t,value:r}=await e.read();if(t)return;yield r}}finally{e.releaseLock()}},ReadableStream.prototype.iterate=ReadableStream.prototype[Symbol.asyncIterator]);class PHPResponse{constructor(t,r,s,n="",i=0){this.httpStatusCode=t,this.headers=r,this.bytes=s,this.exitCode=i,this.errors=n}static fromRawData(t){return new PHPResponse(t.httpStatusCode,t.headers,t.bytes,t.errors,t.exitCode)}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}var v,T;class PHPBrowser{constructor(t,r={}){l(this,v,void 0);l(this,T,void 0);this.requestHandler=t,h(this,v,{}),h(this,T,{handleRedirects:!1,maxRedirects:4,...r})}async request(t,r=0){const s=await this.requestHandler.request({...t,headers:{...t.headers,cookie:this.serializeCookies()}});if(s.headers["set-cookie"]&&this.setCookies(s.headers["set-cookie"]),o(this,T).handleRedirects&&s.headers.location&&r<o(this,T).maxRedirects){const n=new URL(s.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:n.toString(),method:"GET",headers:{}},r+1)}return s}pathToInternalUrl(t){return this.requestHandler.pathToInternalUrl(t)}internalUrlToPath(t){return this.requestHandler.internalUrlToPath(t)}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}setCookies(t){for(const r of t)try{if(!r.includes("="))continue;const s=r.indexOf("="),n=r.substring(0,s),i=r.substring(s+1).split(";")[0];o(this,v)[n]=i}catch(s){console.error(s)}}serializeCookies(){const t=[];for(const r in o(this,v))t.push(`${r}=${o(this,v)[r]}`);return t.join("; ")}}v=new WeakMap,T=new WeakMap;const DEFAULT_BASE_URL="http://example.com";function toRelativeUrl(e){return e.toString().substring(e.origin.length)}function removePathPrefix(e,t){return!t||!e.startsWith(t)?e:e.substring(t.length)}function ensurePathPrefix(e,t){return!t||e.startsWith(t)?e:t+e}async function encodeAsMultipart(e){const t=`----${Math.random().toString(36).slice(2)}`,r=`multipart/form-data; boundary=${t}`,s=new TextEncoder,n=[];for(const[d,p]of Object.entries(e))n.push(`--${t}\r
36
+ `),n.push(`Content-Disposition: form-data; name="${d}"`),p instanceof File&&n.push(`; filename="${p.name}"`),n.push(`\r
37
+ `),p instanceof File&&n.push("Content-Type: application/octet-stream"),n.push(`\r
36
38
  \r
37
- `),c=n.substring(0,o).trim(),h=n.substring(o+4).trim(),f=c.match(/name="([^"]+)"/);if(f){const u=f[1];t[u]=h}}),t}function inferMimeType(e){switch(e.split(".").pop()){case"css":return"text/css";case"js":return"application/javascript";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"svg":return"image/svg+xml";case"woff":return"font/woff";case"woff2":return"font/woff2";case"ttf":return"font/ttf";case"otf":return"font/otf";case"eot":return"font/eot";case"ico":return"image/x-icon";case"html":return"text/html";case"json":return"application/json";case"xml":return"application/xml";case"txt":case"md":return"text/plain";default:return"application-octet-stream"}}function seemsLikeAPHPRequestHandlerPath(e){return seemsLikeAPHPFile(e)||seemsLikeADirectoryRoot(e)}function seemsLikeAPHPFile(e){return e.endsWith(".php")||e.includes(".php/")}function seemsLikeADirectoryRoot(e){return!e.split("/").pop().includes(".")}const FileErrorCodes={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function getEmscriptenFsError(e){const t=typeof e=="object"?e==null?void 0:e.errno:null;if(t in FileErrorCodes)return FileErrorCodes[t]}function rethrowFileSystemError(e=""){return function(r,s,i){const n=i.value;i.value=function(...o){try{return n.apply(this,o)}catch(c){const h=typeof c=="object"?c==null?void 0:c.errno:null;if(h in FileErrorCodes){const f=FileErrorCodes[h],u=typeof o[0]=="string"?o[0]:null,_=u!==null?e.replaceAll("{path}",u):e;throw new Error(`${_}: ${f}`,{cause:c})}throw c}}}}const loadedRuntimes=new Map;function getLoadedRuntime(e){return loadedRuntimes.get(e)}(function(){var e;return typeof process<"u"&&((e=process.release)==null?void 0:e.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(e,t,r,s)=>{for(var i=s>1?void 0:s?__getOwnPropDesc(t,r):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(i=(s?o(t,r,i):o(i))||i);return s&&i&&__defProp(t,r,i),i};const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");var T,H,A,w,P,v,g,I,U,te,D,re,$,se,q,ne,W,ie,j,oe,z,ae,G,le,J,ce,Y,ue,V,de,K,he;class BasePHP{constructor(e,t){l(this,U);l(this,D);l(this,$);l(this,q);l(this,W);l(this,j);l(this,z);l(this,G);l(this,J);l(this,Y);l(this,V);l(this,K);l(this,T,void 0);l(this,H,void 0);l(this,A,void 0);l(this,w,void 0);l(this,P,void 0);l(this,v,void 0);l(this,g,void 0);l(this,I,void 0);d(this,T,[]),d(this,w,!1),d(this,P,null),d(this,v,{}),d(this,g,new Map),d(this,I,[]),this.semaphore=new Semaphore({concurrency:1}),e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new PHPBrowser(new PHPRequestHandler(this,t)))}addEventListener(e,t){a(this,g).has(e)||a(this,g).set(e,new Set),a(this,g).get(e).add(t)}removeEventListener(e,t){var r;(r=a(this,g).get(e))==null||r.delete(t)}dispatchEvent(e){const t=a(this,g).get(e.type);if(t)for(const r of t)r(e)}async onMessage(e){a(this,I).push(e)}async setSpawnHandler(handler){typeof handler=="string"&&(handler=createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}get absoluteUrl(){return this.requestHandler.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.requestHandler.documentRoot}pathToInternalUrl(e){return this.requestHandler.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.requestHandler.internalUrlToPath(e)}initializeRuntime(e){if(this[__private__dont__use])throw new Error("PHP runtime already initialized.");const t=getLoadedRuntime(e);if(!t)throw new Error("Invalid PHP runtime id.");this[__private__dont__use]=t,t.onMessage=async r=>{for(const s of a(this,I)){const i=await s(r);if(i)return i}return""},d(this,P,improveWASMErrorReporting(t)),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(e){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[e])!==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?");d(this,A,e)}setPhpIniPath(e){if(a(this,w))throw new Error("Cannot set PHP ini path after calling run().");d(this,H,e),this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[e])}setPhpIniEntry(e,t){if(a(this,w))throw new Error("Cannot set PHP ini entries after calling run().");a(this,T).push([e,t])}chdir(e){this[__private__dont__use].FS.chdir(e)}async request(e,t){if(!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(e,t)}async run(e){const t=await this.semaphore.acquire();let r;try{a(this,w)||(p(this,U,te).call(this),d(this,w,!0)),p(this,G,le).call(this,e.scriptPath||""),p(this,$,se).call(this,e.relativeUri||""),p(this,W,ie).call(this,e.method||"GET");const s=normalizeHeaders(e.headers||{}),i=s.host||"example.com:443";if(p(this,q,ne).call(this,i,e.protocol||"http"),p(this,j,oe).call(this,s),e.body&&(r=p(this,z,ae).call(this,e.body)),e.fileInfos)for(const o of e.fileInfos)p(this,Y,ue).call(this,o);typeof e.code=="string"&&p(this,V,de).call(this," ?>"+e.code),p(this,J,ce).call(this);const n=await p(this,K,he).call(this);if(e.throwOnError&&n.exitCode!==0){const o={stdout:n.text,stderr:n.errors};console.warn("PHP.run() output was:",o);const c=new Error(`PHP.run() failed with exit code ${n.exitCode} and the following output`);throw c.output=o,c}return n}finally{try{r&&this[__private__dont__use].free(r)}finally{t(),this.dispatchEvent({type:"request.end"})}}}addServerGlobalEntry(e,t){a(this,v)[e]=t}defineConstant(e,t){let r={};try{r=JSON.parse(this.fileExists("/tmp/consts.json")&&this.readFileAsText("/tmp/consts.json")||"{}")}catch{}this.writeFile("/tmp/consts.json",JSON.stringify({...r,[e]:t}))}mkdir(e){this[__private__dont__use].FS.mkdirTree(e)}mkdirTree(e){this.mkdir(e)}readFileAsText(e){return new TextDecoder().decode(this.readFileAsBuffer(e))}readFileAsBuffer(e){return this[__private__dont__use].FS.readFile(e)}writeFile(e,t){this[__private__dont__use].FS.writeFile(e,t)}unlink(e){this[__private__dont__use].FS.unlink(e)}mv(e,t){try{this[__private__dont__use].FS.rename(e,t)}catch(r){const s=getEmscriptenFsError(r);throw s?new Error(`Could not move ${e} to ${t}: ${s}`,{cause:r}):r}}rmdir(e,t={recursive:!0}){t!=null&&t.recursive&&this.listFiles(e).forEach(r=>{const s=`${e}/${r}`;this.isDir(s)?this.rmdir(s,t):this.unlink(s)}),this[__private__dont__use].FS.rmdir(e)}listFiles(e,t={prependPath:!1}){if(!this.fileExists(e))return[];try{const r=this[__private__dont__use].FS.readdir(e).filter(s=>s!=="."&&s!=="..");if(t.prependPath){const s=e.replace(/\/$/,"");return r.map(i=>`${s}/${i}`)}return r}catch(r){return console.error(r,{path:e}),[]}}isDir(e){return this.fileExists(e)?this[__private__dont__use].FS.isDir(this[__private__dont__use].FS.lookupPath(e).node.mode):!1}fileExists(e){try{return this[__private__dont__use].FS.lookupPath(e),!0}catch{return!1}}hotSwapPHPRuntime(e){const t=this[__private__dont__use].FS;try{this.exit()}catch{}if(this.initializeRuntime(e),a(this,H)&&this.setPhpIniPath(a(this,H)),a(this,A)&&this.setSapiName(a(this,A)),this.requestHandler){const r=this.documentRoot;recreateMemFS(this[__private__dont__use].FS,t,r)}}exit(e=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(e)}catch{}d(this,w,!1),d(this,P,null),delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}}T=new WeakMap,H=new WeakMap,A=new WeakMap,w=new WeakMap,P=new WeakMap,v=new WeakMap,g=new WeakMap,I=new WeakMap,U=new WeakSet,te=function(){if(this.setPhpIniEntry("auto_prepend_file","/tmp/consts.php"),this.fileExists("/tmp/consts.php")||this.writeFile("/tmp/consts.php",`<?php
39
+ `),p instanceof File?n.push(await fileToUint8Array(p)):n.push(p),n.push(`\r
40
+ `);n.push(`--${t}--\r
41
+ `);const i=n.reduce((d,p)=>d+p.length,0),a=new Uint8Array(i);let c=0;for(const d of n)a.set(typeof d=="string"?s.encode(d):d,c),c+=d.length;return{bytes:a,contentType:r}}function fileToUint8Array(e){return new Promise(t=>{const r=new FileReader;r.onload=()=>{t(new Uint8Array(r.result))},r.readAsArrayBuffer(e)})}var w,F,I,b,x,m,C,R,M,K,N,Z,B,Q;class PHPRequestHandler{constructor(t,r={}){l(this,M);l(this,N);l(this,B);l(this,w,void 0);l(this,F,void 0);l(this,I,void 0);l(this,b,void 0);l(this,x,void 0);l(this,m,void 0);l(this,C,void 0);l(this,R,void 0);h(this,R,new Semaphore({concurrency:1}));const{documentRoot:s="/www/",absoluteUrl:n=typeof location=="object"?location==null?void 0:location.href:""}=r;this.php=t,h(this,w,s);const i=new URL(n);h(this,I,i.hostname),h(this,b,i.port?Number(i.port):i.protocol==="https:"?443:80),h(this,F,(i.protocol||"").replace(":",""));const a=o(this,b)!==443&&o(this,b)!==80;h(this,x,[o(this,I),a?`:${o(this,b)}`:""].join("")),h(this,m,i.pathname.replace(/\/+$/,"")),h(this,C,[`${o(this,F)}://`,o(this,x),o(this,m)].join(""))}pathToInternalUrl(t){return`${this.absoluteUrl}${t}`}internalUrlToPath(t){const r=new URL(t);return r.pathname.startsWith(o(this,m))&&(r.pathname=r.pathname.slice(o(this,m).length)),toRelativeUrl(r)}get isRequestRunning(){return o(this,R).running>0}get absoluteUrl(){return o(this,C)}get documentRoot(){return o(this,w)}async request(t){const r=t.url.startsWith("http://")||t.url.startsWith("https://"),s=new URL(t.url,r?void 0:DEFAULT_BASE_URL),n=removePathPrefix(s.pathname,o(this,m)),i=`${o(this,w)}${n}`;return seemsLikeAPHPRequestHandlerPath(i)?await f(this,N,Z).call(this,t,s):f(this,M,K).call(this,i)}}w=new WeakMap,F=new WeakMap,I=new WeakMap,b=new WeakMap,x=new WeakMap,m=new WeakMap,C=new WeakMap,R=new WeakMap,M=new WeakSet,K=function(t){if(!this.php.fileExists(t))return new PHPResponse(404,{"x-file-type":["static"]},new TextEncoder().encode("404 File not found"));const r=this.php.readFileAsBuffer(t);return new PHPResponse(200,{"content-length":[`${r.byteLength}`],"content-type":[inferMimeType(t)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},r)},N=new WeakSet,Z=async function(t,r){var n,i;if(o(this,R).running>0&&((n=t.headers)==null?void 0:n["x-request-issuer"])==="php")return console.warn("Possible deadlock: Called request() before the previous request() have finished. PHP likely issued an HTTP call to itself. Normally this would lead to infinite waiting as Request 1 holds the lock that the Request 2 is waiting to acquire. That's not useful, so PHPRequestHandler will return error 502 instead."),new PHPResponse(502,{},new TextEncoder().encode("502 Bad Gateway"));const s=await o(this,R).acquire();try{this.php.addServerGlobalEntry("REMOTE_ADDR","127.0.0.1"),this.php.addServerGlobalEntry("DOCUMENT_ROOT",o(this,w)),this.php.addServerGlobalEntry("HTTPS",o(this,C).startsWith("https://")?"on":"");let a="GET";const c={host:o(this,x),...normalizeHeaders(t.headers||{})};let d=t.body;if(typeof d=="object"&&!(d instanceof Uint8Array)){a="POST";const{bytes:u,contentType:_}=await encodeAsMultipart(d);d=u,c["content-type"]=_}let p;try{let u=r.pathname;if((i=t.headers)!=null&&i["x-rewrite-url"])try{u=new URL(t.headers["x-rewrite-url"]).pathname}catch{}p=f(this,B,Q).call(this,u)}catch{return new PHPResponse(404,{},new TextEncoder().encode("404 File not found"))}return await this.php.run({relativeUri:ensurePathPrefix(toRelativeUrl(r),o(this,m)),protocol:o(this,F),method:t.method||a,body:d,scriptPath:p,headers:c})}finally{s()}},B=new WeakSet,Q=function(t){let r=removePathPrefix(t,o(this,m));r.includes(".php")?r=r.split(".php")[0]+".php":(r.endsWith("/")||(r+="/"),r.endsWith("index.php")||(r+="index.php"));const s=`${o(this,w)}${r}`;if(this.php.fileExists(s))return s;throw new Error(`File not found: ${s}`)};function inferMimeType(e){switch(e.split(".").pop()){case"css":return"text/css";case"js":return"application/javascript";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"svg":return"image/svg+xml";case"woff":return"font/woff";case"woff2":return"font/woff2";case"ttf":return"font/ttf";case"otf":return"font/otf";case"eot":return"font/eot";case"ico":return"image/x-icon";case"html":return"text/html";case"json":return"application/json";case"xml":return"application/xml";case"txt":case"md":return"text/plain";default:return"application-octet-stream"}}function seemsLikeAPHPRequestHandlerPath(e){return seemsLikeAPHPFile(e)||seemsLikeADirectoryRoot(e)}function seemsLikeAPHPFile(e){return e.endsWith(".php")||e.includes(".php/")}function seemsLikeADirectoryRoot(e){return!e.split("/").pop().includes(".")}const FileErrorCodes={0:"No error occurred. System call completed successfully.",1:"Argument list too long.",2:"Permission denied.",3:"Address in use.",4:"Address not available.",5:"Address family not supported.",6:"Resource unavailable, or operation would block.",7:"Connection already in progress.",8:"Bad file descriptor.",9:"Bad message.",10:"Device or resource busy.",11:"Operation canceled.",12:"No child processes.",13:"Connection aborted.",14:"Connection refused.",15:"Connection reset.",16:"Resource deadlock would occur.",17:"Destination address required.",18:"Mathematics argument out of domain of function.",19:"Reserved.",20:"File exists.",21:"Bad address.",22:"File too large.",23:"Host is unreachable.",24:"Identifier removed.",25:"Illegal byte sequence.",26:"Operation in progress.",27:"Interrupted function.",28:"Invalid argument.",29:"I/O error.",30:"Socket is connected.",31:"There is a directory under that path.",32:"Too many levels of symbolic links.",33:"File descriptor value too large.",34:"Too many links.",35:"Message too large.",36:"Reserved.",37:"Filename too long.",38:"Network is down.",39:"Connection aborted by network.",40:"Network unreachable.",41:"Too many files open in system.",42:"No buffer space available.",43:"No such device.",44:"There is no such file or directory OR the parent directory does not exist.",45:"Executable file format error.",46:"No locks available.",47:"Reserved.",48:"Not enough space.",49:"No message of the desired type.",50:"Protocol not available.",51:"No space left on device.",52:"Function not supported.",53:"The socket is not connected.",54:"Not a directory or a symbolic link to a directory.",55:"Directory not empty.",56:"State not recoverable.",57:"Not a socket.",58:"Not supported, or operation not supported on socket.",59:"Inappropriate I/O control operation.",60:"No such device or address.",61:"Value too large to be stored in data type.",62:"Previous owner died.",63:"Operation not permitted.",64:"Broken pipe.",65:"Protocol error.",66:"Protocol not supported.",67:"Protocol wrong type for socket.",68:"Result too large.",69:"Read-only file system.",70:"Invalid seek.",71:"No such process.",72:"Reserved.",73:"Connection timed out.",74:"Text file busy.",75:"Cross-device link.",76:"Extension: Capabilities insufficient."};function getEmscriptenFsError(e){const t=typeof e=="object"?e==null?void 0:e.errno:null;if(t in FileErrorCodes)return FileErrorCodes[t]}function rethrowFileSystemError(e=""){return function(r,s,n){const i=n.value;n.value=function(...a){try{return i.apply(this,a)}catch(c){const d=typeof c=="object"?c==null?void 0:c.errno:null;if(d in FileErrorCodes){const p=FileErrorCodes[d],u=typeof a[0]=="string"?a[0]:null,_=u!==null?e.replaceAll("{path}",u):e;throw new Error(`${_}: ${p}`,{cause:c})}throw c}}}}const loadedRuntimes=new Map;function getLoadedRuntime(e){return loadedRuntimes.get(e)}(function(){var e;return typeof process<"u"&&((e=process.release)==null?void 0:e.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(e,t,r,s)=>{for(var n=s>1?void 0:s?__getOwnPropDesc(t,r):t,i=e.length-1,a;i>=0;i--)(a=e[i])&&(n=(s?a(t,r,n):a(n))||n);return s&&n&&__defProp(t,r,n),n};const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");var S,k,A,y,E,P,g,H,L,X,O,ee,U,te,q,re,$,se,D,ne,j,ie,W,oe,z,ae,G,le,J,ce;class BasePHP{constructor(e,t){l(this,L);l(this,O);l(this,U);l(this,q);l(this,$);l(this,D);l(this,j);l(this,W);l(this,z);l(this,G);l(this,J);l(this,S,void 0);l(this,k,void 0);l(this,A,void 0);l(this,y,void 0);l(this,E,void 0);l(this,P,void 0);l(this,g,void 0);l(this,H,void 0);h(this,S,[]),h(this,y,!1),h(this,E,null),h(this,P,{}),h(this,g,new Map),h(this,H,[]),this.semaphore=new Semaphore({concurrency:1}),e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new PHPBrowser(new PHPRequestHandler(this,t)))}addEventListener(e,t){o(this,g).has(e)||o(this,g).set(e,new Set),o(this,g).get(e).add(t)}removeEventListener(e,t){var r;(r=o(this,g).get(e))==null||r.delete(t)}dispatchEvent(e){const t=o(this,g).get(e.type);if(t)for(const r of t)r(e)}async onMessage(e){o(this,H).push(e)}async setSpawnHandler(handler){typeof handler=="string"&&(handler=createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}get absoluteUrl(){return this.requestHandler.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.requestHandler.documentRoot}pathToInternalUrl(e){return this.requestHandler.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.requestHandler.internalUrlToPath(e)}initializeRuntime(e){if(this[__private__dont__use])throw new Error("PHP runtime already initialized.");const t=getLoadedRuntime(e);if(!t)throw new Error("Invalid PHP runtime id.");this[__private__dont__use]=t,t.onMessage=async r=>{for(const s of o(this,H)){const n=await s(r);if(n)return n}return""},h(this,E,improveWASMErrorReporting(t)),this.dispatchEvent({type:"runtime.initialized"})}async setSapiName(e){if(this[__private__dont__use].ccall("wasm_set_sapi_name",NUMBER,[STRING],[e])!==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,A,e)}setPhpIniPath(e){if(o(this,y))throw new Error("Cannot set PHP ini path after calling run().");h(this,k,e),this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[e])}setPhpIniEntry(e,t){if(o(this,y))throw new Error("Cannot set PHP ini entries after calling run().");o(this,S).push([e,t])}chdir(e){this[__private__dont__use].FS.chdir(e)}async request(e,t){if(!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(e,t)}async run(e){const t=await this.semaphore.acquire();let r;try{o(this,y)||(f(this,L,X).call(this),h(this,y,!0)),f(this,W,oe).call(this,e.scriptPath||""),f(this,U,te).call(this,e.relativeUri||""),f(this,$,se).call(this,e.method||"GET");const s=normalizeHeaders(e.headers||{}),n=s.host||"example.com:443";f(this,q,re).call(this,n,e.protocol||"http"),f(this,D,ne).call(this,s),e.body&&(r=f(this,j,ie).call(this,e.body)),typeof e.code=="string"&&f(this,G,le).call(this," ?>"+e.code),f(this,z,ae).call(this);const i=await f(this,J,ce).call(this);if(e.throwOnError&&i.exitCode!==0){const a={stdout:i.text,stderr:i.errors};console.warn("PHP.run() output was:",a);const c=new Error(`PHP.run() failed with exit code ${i.exitCode} and the following output`);throw c.output=a,c}return i}finally{try{r&&this[__private__dont__use].free(r)}finally{t(),this.dispatchEvent({type:"request.end"})}}}addServerGlobalEntry(e,t){o(this,P)[e]=t}defineConstant(e,t){let r={};try{r=JSON.parse(this.fileExists("/tmp/consts.json")&&this.readFileAsText("/tmp/consts.json")||"{}")}catch{}this.writeFile("/tmp/consts.json",JSON.stringify({...r,[e]:t}))}mkdir(e){this[__private__dont__use].FS.mkdirTree(e)}mkdirTree(e){this.mkdir(e)}readFileAsText(e){return new TextDecoder().decode(this.readFileAsBuffer(e))}readFileAsBuffer(e){return this[__private__dont__use].FS.readFile(e)}writeFile(e,t){this[__private__dont__use].FS.writeFile(e,t)}unlink(e){this[__private__dont__use].FS.unlink(e)}mv(e,t){try{this[__private__dont__use].FS.rename(e,t)}catch(r){const s=getEmscriptenFsError(r);throw s?new Error(`Could not move ${e} to ${t}: ${s}`,{cause:r}):r}}rmdir(e,t={recursive:!0}){t!=null&&t.recursive&&this.listFiles(e).forEach(r=>{const s=`${e}/${r}`;this.isDir(s)?this.rmdir(s,t):this.unlink(s)}),this[__private__dont__use].FS.rmdir(e)}listFiles(e,t={prependPath:!1}){if(!this.fileExists(e))return[];try{const r=this[__private__dont__use].FS.readdir(e).filter(s=>s!=="."&&s!=="..");if(t.prependPath){const s=e.replace(/\/$/,"");return r.map(n=>`${s}/${n}`)}return r}catch(r){return console.error(r,{path:e}),[]}}isDir(e){return this.fileExists(e)?this[__private__dont__use].FS.isDir(this[__private__dont__use].FS.lookupPath(e).node.mode):!1}fileExists(e){try{return this[__private__dont__use].FS.lookupPath(e),!0}catch{return!1}}hotSwapPHPRuntime(e){const t=this[__private__dont__use].FS;try{this.exit()}catch{}if(this.initializeRuntime(e),o(this,k)&&this.setPhpIniPath(o(this,k)),o(this,A)&&this.setSapiName(o(this,A)),this.requestHandler){const r=this.documentRoot;recreateMemFS(this[__private__dont__use].FS,t,r)}}exit(e=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(e)}catch{}h(this,y,!1),h(this,E,null),delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}}S=new WeakMap,k=new WeakMap,A=new WeakMap,y=new WeakMap,E=new WeakMap,P=new WeakMap,g=new WeakMap,H=new WeakMap,L=new WeakSet,X=function(){if(this.setPhpIniEntry("auto_prepend_file","/tmp/consts.php"),this.fileExists("/tmp/consts.php")||this.writeFile("/tmp/consts.php",`<?php
38
42
  if(file_exists('/tmp/consts.json')) {
39
43
  $consts = json_decode(file_get_contents('/tmp/consts.json'), true);
40
44
  foreach ($consts as $const => $value) {
@@ -42,7 +46,7 @@ ${bold} WASM ERROR${reset}${redBg}`);for(const t of e.split(`
42
46
  define($const, $value);
43
47
  }
44
48
  }
45
- }`),a(this,T).length>0){const e=a(this,T).map(([t,r])=>`${t}=${r}`).join(`
49
+ }`),o(this,S).length>0){const e=o(this,S).map(([t,r])=>`${t}=${r}`).join(`
46
50
  `)+`
47
51
 
48
- `;this[__private__dont__use].ccall("wasm_set_phpini_entries",null,[STRING],[e])}this[__private__dont__use].ccall("php_wasm_init",null,[],[])},D=new WeakSet,re=function(){const e="/tmp/headers.json";if(!this.fileExists(e))throw new Error("SAPI Error: Could not find response headers file.");const t=JSON.parse(this.readFileAsText(e)),r={};for(const s of t.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:t.status}},$=new WeakSet,se=function(e){if(this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[e]),e.includes("?")){const t=e.substring(e.indexOf("?")+1);this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[t])}},q=new WeakSet,ne=function(e,t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[e]);let r;try{r=parseInt(new URL(e).port,10)}catch{}(!r||isNaN(r)||r===80)&&(r=t==="https"?443:80),this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[r]),(t==="https"||!t&&r===443)&&this.addServerGlobalEntry("HTTPS","on")},W=new WeakSet,ie=function(e){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[e])},j=new WeakSet,oe=function(e){e.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[e.cookie]),e["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[e["content-type"]]),e["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(e["content-length"],10)]);for(const t in e){let r="HTTP_";["content-type","content-length"].includes(t.toLowerCase())&&(r=""),this.addServerGlobalEntry(`${r}${t.toUpperCase().replace(/-/g,"_")}`,e[t])}},z=new WeakSet,ae=function(e){const t=this[__private__dont__use].lengthBytesUTF8(e),r=this[__private__dont__use].malloc(t+1);if(!r)throw new Error("Could not allocate memory for the request body.");return this[__private__dont__use].stringToUTF8(e,r,t+1),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[r]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[new TextEncoder().encode(e).length]),r},G=new WeakSet,le=function(e){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[e])},J=new WeakSet,ce=function(){for(const e in a(this,v))this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[e,a(this,v)[e]])},Y=new WeakSet,ue=function(e){const{key:t,name:r,type:s,data:i}=e,n=`/tmp/${Math.random().toFixed(20)}`;this.writeFile(n,i);const o=0;this[__private__dont__use].ccall("wasm_add_uploaded_file",null,[STRING,STRING,STRING,STRING,NUMBER,NUMBER],[t,r,s,n,o,i.byteLength])},V=new WeakSet,de=function(e){this[__private__dont__use].ccall("wasm_set_php_code",null,[STRING],[e])},K=new WeakSet,he=async function(){var i;let e,t;try{e=await new Promise((n,o)=>{var h;t=f=>{const u=new Error("Rethrown");u.cause=f.error,u.betterMessage=f.message,o(u)},(h=a(this,P))==null||h.addEventListener("error",t);const c=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return c instanceof Promise?c.then(n,o):n(c)})}catch(n){for(const f in this)typeof this[f]=="function"&&(this[f]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify();const o=n,c="betterMessage"in o?o.betterMessage:o.message,h=new Error(c);throw h.cause=o,h}finally{(i=a(this,P))==null||i.removeEventListener("error",t),d(this,v,{})}const{headers:r,httpStatusCode:s}=p(this,D,re).call(this);return new PHPResponse(s,r,this.readFileAsBuffer("/tmp/stdout"),this.readFileAsText("/tmp/stderr"),e)};__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],BasePHP.prototype,"mkdir",1);__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],BasePHP.prototype,"mkdirTree",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],BasePHP.prototype,"readFileAsText",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],BasePHP.prototype,"readFileAsBuffer",1);__decorateClass([rethrowFileSystemError('Could not write to "{path}"')],BasePHP.prototype,"writeFile",1);__decorateClass([rethrowFileSystemError('Could not unlink "{path}"')],BasePHP.prototype,"unlink",1);__decorateClass([rethrowFileSystemError('Could not remove directory "{path}"')],BasePHP.prototype,"rmdir",1);__decorateClass([rethrowFileSystemError('Could not list files in "{path}"')],BasePHP.prototype,"listFiles",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],BasePHP.prototype,"isDir",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],BasePHP.prototype,"fileExists",1);function normalizeHeaders(e){const t={};for(const r in e)t[r.toLowerCase()]=e[r];return t}function recreateMemFS(e,t,r){let s;try{s=t.lookupPath(r)}catch{return}if(!("contents"in s.node))return;try{e=e.lookupPath(r);return}catch{}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)recreateMemFS(e,t,joinPaths(r,n))}function journalFSEvents(e,t,r=()=>{}){function s(){t=normalizePath(t);const n=e[__private__dont__use].FS,o=createFSHooks(n,u=>{if(u.path.startsWith(t))r(u);else if(u.operation==="RENAME"&&u.toPath.startsWith(t))for(const _ of recordExistingPath(e,u.path,u.toPath))r(_)}),c={};for(const[u]of Object.entries(o))c[u]=n[u];function h(){for(const[u,_]of Object.entries(o))n[u]=function(...y){return _(...y),c[u].apply(this,y)}}function f(){for(const[u,_]of Object.entries(c))e[__private__dont__use].FS[u]=_}e[__private__dont__use].journal={bind:h,unbind:f},h()}e.addEventListener("runtime.initialized",s),e[__private__dont__use]&&s();function i(){e[__private__dont__use].journal.unbind(),delete e[__private__dont__use].journal}return e.addEventListener("runtime.beforedestroy",i),function(){return e.removeEventListener("runtime.initialized",s),e.removeEventListener("runtime.beforedestroy",i),e[__private__dont__use].journal.unbind()}}const createFSHooks=(e,t=()=>{})=>({write(r){t({operation:"WRITE",path:r.path,nodeType:"file"})},truncate(r){let s;typeof r=="string"?s=e.lookupPath(r,{follow:!0}).node:s=r,t({operation:"WRITE",path:e.getPath(s),nodeType:"file"})},unlink(r){t({operation:"DELETE",path:r,nodeType:"file"})},mknod(r,s){e.isFile(s)&&t({operation:"CREATE",path:r,nodeType:"file"})},mkdir(r){t({operation:"CREATE",path:r,nodeType:"directory"})},rmdir(r){t({operation:"DELETE",path:r,nodeType:"directory"})},rename(r,s){try{const i=e.lookupPath(r,{follow:!0}),n=e.lookupPath(s,{parent:!0}).path;t({operation:"RENAME",nodeType:e.isDir(i.node.mode)?"directory":"file",path:i.path,toPath:joinPaths(n,basename(s))})}catch{}}});function replayFSJournal(e,t){e[__private__dont__use].journal.unbind();try{for(const r of t)r.operation==="CREATE"?r.nodeType==="file"?e.writeFile(r.path," "):e.mkdir(r.path):r.operation==="DELETE"?r.nodeType==="file"?e.unlink(r.path):e.rmdir(r.path):r.operation==="WRITE"?e.writeFile(r.path,r.data):r.operation==="RENAME"&&e.mv(r.path,r.toPath)}finally{e[__private__dont__use].journal.bind()}}function*recordExistingPath(e,t,r){if(e.isDir(t)){yield{operation:"CREATE",path:r,nodeType:"directory"};for(const s of e.listFiles(t))yield*recordExistingPath(e,joinPaths(t,s),joinPaths(r,s))}else yield{operation:"CREATE",path:r,nodeType:"file"},yield{operation:"WRITE",nodeType:"file",path:r}}function normalizePath(e){return e.replace(/\/$/,"").replace(/\/\/+/g,"/")}function normalizeFilesystemOperations(e){const t={};for(let r=e.length-1;r>=0;r--){for(let s=r-1;s>=0;s--){const i=checkRelationship(e[r],e[s]);if(i==="none")continue;const n=e[r],o=e[s];if(n.operation==="RENAME"&&o.operation==="RENAME"){console.warn("[FS Journal] Normalizing a double rename is not yet supported:",{current:n,last:o});continue}(o.operation==="CREATE"||o.operation==="WRITE")&&(n.operation==="RENAME"?i==="same_node"?(t[s]=[],t[r]=[{...o,path:n.toPath},...t[r]||[]]):i==="descendant"&&(t[s]=[],t[r]=[{...o,path:joinPaths(n.toPath,o.path.substring(n.path.length))},...t[r]||[]]):n.operation==="WRITE"&&i==="same_node"?t[s]=[]:n.operation==="DELETE"&&i==="same_node"&&(t[s]=[],t[r]=[]))}if(Object.entries(t).length>0){const s=e.flatMap((i,n)=>n in t?t[n]:[i]);return normalizeFilesystemOperations(s)}}return e}function checkRelationship(e,t){const r=e.path,s=e.operation!=="WRITE"&&e.nodeType==="directory",i=t.operation!=="WRITE"&&t.nodeType==="directory",n=t.operation==="RENAME"?t.toPath:t.path;return n===r?"same_node":i&&r.startsWith(n+"/")?"ancestor":s&&n.startsWith(r+"/")?"descendant":"none"}async function hydrateUpdateFileOps(e,t){const s=t.filter(i=>i.operation==="WRITE").map(i=>hydrateOp(e,i));return await Promise.all(s),t}const hydrateLock=new Semaphore({concurrency:15});async function hydrateOp(e,t){const r=await hydrateLock.acquire();try{t.data=await e.readFileAsBuffer(t.path)}catch(s){console.warn(`Journal failed to hydrate a file on flush: the path ${t.path} no longer exists`),console.error(s)}r()}exports.hydrateUpdateFileOps=hydrateUpdateFileOps;exports.journalFSEvents=journalFSEvents;exports.normalizeFilesystemOperations=normalizeFilesystemOperations;exports.replayFSJournal=replayFSJournal;
52
+ `;this[__private__dont__use].ccall("wasm_set_phpini_entries",null,[STRING],[e])}this[__private__dont__use].ccall("php_wasm_init",null,[],[])},O=new WeakSet,ee=function(){const e="/tmp/headers.json";if(!this.fileExists(e))throw new Error("SAPI Error: Could not find response headers file.");const t=JSON.parse(this.readFileAsText(e)),r={};for(const s of t.headers){if(!s.includes(": "))continue;const n=s.indexOf(": "),i=s.substring(0,n).toLowerCase(),a=s.substring(n+2);i in r||(r[i]=[]),r[i].push(a)}return{headers:r,httpStatusCode:t.status}},U=new WeakSet,te=function(e){if(this[__private__dont__use].ccall("wasm_set_request_uri",null,[STRING],[e]),e.includes("?")){const t=e.substring(e.indexOf("?")+1);this[__private__dont__use].ccall("wasm_set_query_string",null,[STRING],[t])}},q=new WeakSet,re=function(e,t){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[e]);let r;try{r=parseInt(new URL(e).port,10)}catch{}(!r||isNaN(r)||r===80)&&(r=t==="https"?443:80),this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[r]),(t==="https"||!t&&r===443)&&this.addServerGlobalEntry("HTTPS","on")},$=new WeakSet,se=function(e){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[e])},D=new WeakSet,ne=function(e){e.cookie&&this[__private__dont__use].ccall("wasm_set_cookies",null,[STRING],[e.cookie]),e["content-type"]&&this[__private__dont__use].ccall("wasm_set_content_type",null,[STRING],[e["content-type"]]),e["content-length"]&&this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[parseInt(e["content-length"],10)]);for(const t in e){let r="HTTP_";["content-type","content-length"].includes(t.toLowerCase())&&(r=""),this.addServerGlobalEntry(`${r}${t.toUpperCase().replace(/-/g,"_")}`,e[t])}},j=new WeakSet,ie=function(e){let t,r;typeof e=="string"?(console.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(e),t=r+1):(r=e.byteLength,t=e.byteLength);const s=this[__private__dont__use].malloc(t);if(!s)throw new Error("Could not allocate memory for the request body.");return typeof e=="string"?this[__private__dont__use].stringToUTF8(e,s,t+1):this[__private__dont__use].HEAPU8.set(e,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},W=new WeakSet,oe=function(e){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[e])},z=new WeakSet,ae=function(){for(const e in o(this,P))this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[e,o(this,P)[e]])},G=new WeakSet,le=function(e){this[__private__dont__use].ccall("wasm_set_php_code",null,[STRING],[e])},J=new WeakSet,ce=async function(){var n;let e,t;try{e=await new Promise((i,a)=>{var d;t=p=>{const u=new Error("Rethrown");u.cause=p.error,u.betterMessage=p.message,a(u)},(d=o(this,E))==null||d.addEventListener("error",t);const c=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return c instanceof Promise?c.then(i,a):i(c)})}catch(i){for(const p in this)typeof this[p]=="function"&&(this[p]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify();const a=i,c="betterMessage"in a?a.betterMessage:a.message,d=new Error(c);throw d.cause=a,d}finally{(n=o(this,E))==null||n.removeEventListener("error",t),h(this,P,{})}const{headers:r,httpStatusCode:s}=f(this,O,ee).call(this);return new PHPResponse(s,r,this.readFileAsBuffer("/tmp/stdout"),this.readFileAsText("/tmp/stderr"),e)};__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],BasePHP.prototype,"mkdir",1);__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],BasePHP.prototype,"mkdirTree",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],BasePHP.prototype,"readFileAsText",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],BasePHP.prototype,"readFileAsBuffer",1);__decorateClass([rethrowFileSystemError('Could not write to "{path}"')],BasePHP.prototype,"writeFile",1);__decorateClass([rethrowFileSystemError('Could not unlink "{path}"')],BasePHP.prototype,"unlink",1);__decorateClass([rethrowFileSystemError('Could not remove directory "{path}"')],BasePHP.prototype,"rmdir",1);__decorateClass([rethrowFileSystemError('Could not list files in "{path}"')],BasePHP.prototype,"listFiles",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],BasePHP.prototype,"isDir",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],BasePHP.prototype,"fileExists",1);function normalizeHeaders(e){const t={};for(const r in e)t[r.toLowerCase()]=e[r];return t}function recreateMemFS(e,t,r){let s;try{s=t.lookupPath(r)}catch{return}if(!("contents"in s.node))return;try{e=e.lookupPath(r);return}catch{}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)recreateMemFS(e,t,joinPaths(r,i))}function journalFSEvents(e,t,r=()=>{}){function s(){t=normalizePath(t);const i=e[__private__dont__use].FS,a=createFSHooks(i,u=>{if(u.path.startsWith(t))r(u);else if(u.operation==="RENAME"&&u.toPath.startsWith(t))for(const _ of recordExistingPath(e,u.path,u.toPath))r(_)}),c={};for(const[u]of Object.entries(a))c[u]=i[u];function d(){for(const[u,_]of Object.entries(a))i[u]=function(...V){return _(...V),c[u].apply(this,V)}}function p(){for(const[u,_]of Object.entries(c))e[__private__dont__use].FS[u]=_}e[__private__dont__use].journal={bind:d,unbind:p},d()}e.addEventListener("runtime.initialized",s),e[__private__dont__use]&&s();function n(){e[__private__dont__use].journal.unbind(),delete e[__private__dont__use].journal}return e.addEventListener("runtime.beforedestroy",n),function(){return e.removeEventListener("runtime.initialized",s),e.removeEventListener("runtime.beforedestroy",n),e[__private__dont__use].journal.unbind()}}const createFSHooks=(e,t=()=>{})=>({write(r){t({operation:"WRITE",path:r.path,nodeType:"file"})},truncate(r){let s;typeof r=="string"?s=e.lookupPath(r,{follow:!0}).node:s=r,t({operation:"WRITE",path:e.getPath(s),nodeType:"file"})},unlink(r){t({operation:"DELETE",path:r,nodeType:"file"})},mknod(r,s){e.isFile(s)&&t({operation:"CREATE",path:r,nodeType:"file"})},mkdir(r){t({operation:"CREATE",path:r,nodeType:"directory"})},rmdir(r){t({operation:"DELETE",path:r,nodeType:"directory"})},rename(r,s){try{const n=e.lookupPath(r,{follow:!0}),i=e.lookupPath(s,{parent:!0}).path;t({operation:"RENAME",nodeType:e.isDir(n.node.mode)?"directory":"file",path:n.path,toPath:joinPaths(i,basename(s))})}catch{}}});function replayFSJournal(e,t){e[__private__dont__use].journal.unbind();try{for(const r of t)r.operation==="CREATE"?r.nodeType==="file"?e.writeFile(r.path," "):e.mkdir(r.path):r.operation==="DELETE"?r.nodeType==="file"?e.unlink(r.path):e.rmdir(r.path):r.operation==="WRITE"?e.writeFile(r.path,r.data):r.operation==="RENAME"&&e.mv(r.path,r.toPath)}finally{e[__private__dont__use].journal.bind()}}function*recordExistingPath(e,t,r){if(e.isDir(t)){yield{operation:"CREATE",path:r,nodeType:"directory"};for(const s of e.listFiles(t))yield*recordExistingPath(e,joinPaths(t,s),joinPaths(r,s))}else yield{operation:"CREATE",path:r,nodeType:"file"},yield{operation:"WRITE",nodeType:"file",path:r}}function normalizePath(e){return e.replace(/\/$/,"").replace(/\/\/+/g,"/")}function normalizeFilesystemOperations(e){const t={};for(let r=e.length-1;r>=0;r--){for(let s=r-1;s>=0;s--){const n=checkRelationship(e[r],e[s]);if(n==="none")continue;const i=e[r],a=e[s];if(i.operation==="RENAME"&&a.operation==="RENAME"){console.warn("[FS Journal] Normalizing a double rename is not yet supported:",{current:i,last:a});continue}(a.operation==="CREATE"||a.operation==="WRITE")&&(i.operation==="RENAME"?n==="same_node"?(t[s]=[],t[r]=[{...a,path:i.toPath},...t[r]||[]]):n==="descendant"&&(t[s]=[],t[r]=[{...a,path:joinPaths(i.toPath,a.path.substring(i.path.length))},...t[r]||[]]):i.operation==="WRITE"&&n==="same_node"?t[s]=[]:i.operation==="DELETE"&&n==="same_node"&&(t[s]=[],t[r]=[]))}if(Object.entries(t).length>0){const s=e.flatMap((n,i)=>i in t?t[i]:[n]);return normalizeFilesystemOperations(s)}}return e}function checkRelationship(e,t){const r=e.path,s=e.operation!=="WRITE"&&e.nodeType==="directory",n=t.operation!=="WRITE"&&t.nodeType==="directory",i=t.operation==="RENAME"?t.toPath:t.path;return i===r?"same_node":n&&r.startsWith(i+"/")?"ancestor":s&&i.startsWith(r+"/")?"descendant":"none"}async function hydrateUpdateFileOps(e,t){const s=t.filter(n=>n.operation==="WRITE").map(n=>hydrateOp(e,n));return await Promise.all(s),t}const hydrateLock=new Semaphore({concurrency:15});async function hydrateOp(e,t){const r=await hydrateLock.acquire();try{t.data=await e.readFileAsBuffer(t.path)}catch(s){console.warn(`Journal failed to hydrate a file on flush: the path ${t.path} no longer exists`),console.error(s)}r()}exports.hydrateUpdateFileOps=hydrateUpdateFileOps;exports.journalFSEvents=journalFSEvents;exports.normalizeFilesystemOperations=normalizeFilesystemOperations;exports.replayFSJournal=replayFSJournal;
package/index.js CHANGED
@@ -1,19 +1,19 @@
1
- var Z = (e, t, r) => {
1
+ var Y = (e, t, r) => {
2
2
  if (!t.has(e))
3
3
  throw TypeError("Cannot " + r);
4
4
  };
5
- var a = (e, t, r) => (Z(e, t, "read from private field"), r ? r.call(e) : t.get(e)), l = (e, t, r) => {
5
+ var o = (e, t, r) => (Y(e, t, "read from private field"), r ? r.call(e) : t.get(e)), l = (e, t, r) => {
6
6
  if (t.has(e))
7
7
  throw TypeError("Cannot add the same private member more than once");
8
8
  t instanceof WeakSet ? t.add(e) : t.set(e, r);
9
- }, d = (e, t, r, s) => (Z(e, t, "write to private field"), s ? s.call(e, r) : t.set(e, r), r);
10
- var p = (e, t, r) => (Z(e, t, "access private method"), r);
9
+ }, h = (e, t, r, s) => (Y(e, t, "write to private field"), s ? s.call(e, r) : t.set(e, r), r);
10
+ var f = (e, t, r) => (Y(e, t, "access private method"), r);
11
11
  if (typeof File > "u") {
12
12
  class e extends Blob {
13
- constructor(r, s, i) {
13
+ constructor(r, s, n) {
14
14
  super(r);
15
- let n;
16
- i != null && i.lastModified && (n = /* @__PURE__ */ new Date()), (!n || isNaN(n.getFullYear())) && (n = /* @__PURE__ */ new Date()), this.lastModifiedDate = n, this.lastModified = n.getMilliseconds(), this.name = s || "";
15
+ let i;
16
+ n != null && n.lastModified && (i = /* @__PURE__ */ new Date()), (!i || isNaN(i.getFullYear())) && (i = /* @__PURE__ */ new Date()), this.lastModifiedDate = i, this.lastModified = i.getMilliseconds(), this.name = s || "";
17
17
  }
18
18
  }
19
19
  global.File = e;
@@ -50,9 +50,9 @@ function isByobSupported() {
50
50
  // this if needed.
51
51
  autoAllocateChunkSize: 512 * 1024,
52
52
  async pull(r) {
53
- const s = r.byobRequest.view, n = await t.slice(e, e + s.byteLength).arrayBuffer(), o = new Uint8Array(n);
54
- new Uint8Array(s.buffer).set(o);
55
- const c = o.byteLength;
53
+ const s = r.byobRequest.view, i = await t.slice(e, e + s.byteLength).arrayBuffer(), a = new Uint8Array(i);
54
+ new Uint8Array(s.buffer).set(a);
55
+ const c = a.byteLength;
56
56
  r.byobRequest.respond(c), e += c, e >= t.size && r.close();
57
57
  }
58
58
  });
@@ -67,9 +67,6 @@ if (typeof CustomEvent > "u") {
67
67
  }
68
68
  globalThis.CustomEvent = e;
69
69
  }
70
- typeof crypto > "u" && import("./__vite-browser-external-2447137e.js").then((e) => {
71
- global.crypto = e;
72
- });
73
70
  const kError = Symbol("error"), kMessage = Symbol("message");
74
71
  class ErrorEvent2 extends Event {
75
72
  /**
@@ -117,27 +114,27 @@ function improveWASMErrorReporting(e) {
117
114
  for (const r in e.asm)
118
115
  if (typeof e.asm[r] == "function") {
119
116
  const s = e.asm[r];
120
- e.asm[r] = function(...i) {
121
- var n;
117
+ e.asm[r] = function(...n) {
118
+ var i;
122
119
  try {
123
- return s(...i);
124
- } catch (o) {
125
- if (!(o instanceof Error))
126
- throw o;
120
+ return s(...n);
121
+ } catch (a) {
122
+ if (!(a instanceof Error))
123
+ throw a;
127
124
  const c = clarifyErrorMessage(
128
- o,
129
- (n = e.lastAsyncifyStackSource) == null ? void 0 : n.stack
125
+ a,
126
+ (i = e.lastAsyncifyStackSource) == null ? void 0 : i.stack
130
127
  );
131
- if (e.lastAsyncifyStackSource && (o.cause = e.lastAsyncifyStackSource), t.hasListeners()) {
128
+ if (e.lastAsyncifyStackSource && (a.cause = e.lastAsyncifyStackSource), t.hasListeners()) {
132
129
  t.dispatchEvent(
133
130
  new ErrorEvent("error", {
134
- error: o,
131
+ error: a,
135
132
  message: c
136
133
  })
137
134
  );
138
135
  return;
139
136
  }
140
- throw isExitCodeZero(o) || showCriticalErrorBox(c), o;
137
+ throw isExitCodeZero(a) || showCriticalErrorBox(c), a;
141
138
  }
142
139
  };
143
140
  }
@@ -269,8 +266,8 @@ function normalizePath$1(e) {
269
266
  function normalizePathsArray(e, t) {
270
267
  let r = 0;
271
268
  for (let s = e.length - 1; s >= 0; s--) {
272
- const i = e[s];
273
- i === "." ? e.splice(s, 1) : i === ".." ? (e.splice(s, 1), r++) : r && (e.splice(s, 1), r--);
269
+ const n = e[s];
270
+ n === "." ? e.splice(s, 1) : n === ".." ? (e.splice(s, 1), r++) : r && (e.splice(s, 1), r--);
274
271
  }
275
272
  if (t)
276
273
  for (; r; r--)
@@ -347,8 +344,8 @@ ReadableStream.prototype[Symbol.asyncIterator] || (ReadableStream.prototype[Symb
347
344
  }, ReadableStream.prototype.iterate = // @ts-ignore
348
345
  ReadableStream.prototype[Symbol.asyncIterator]);
349
346
  class PHPResponse {
350
- constructor(t, r, s, i = "", n = 0) {
351
- this.httpStatusCode = t, this.headers = r, this.bytes = s, this.exitCode = n, this.errors = i;
347
+ constructor(t, r, s, n = "", i = 0) {
348
+ this.httpStatusCode = t, this.headers = r, this.bytes = s, this.exitCode = i, this.errors = n;
352
349
  }
353
350
  static fromRawData(t) {
354
351
  return new PHPResponse(
@@ -381,16 +378,16 @@ class PHPResponse {
381
378
  return new TextDecoder().decode(this.bytes);
382
379
  }
383
380
  }
384
- var b, F;
381
+ var v, T;
385
382
  class PHPBrowser {
386
383
  /**
387
384
  * @param server - The PHP server to browse.
388
385
  * @param config - The browser configuration.
389
386
  */
390
387
  constructor(t, r = {}) {
391
- l(this, b, void 0);
392
- l(this, F, void 0);
393
- this.requestHandler = t, d(this, b, {}), d(this, F, {
388
+ l(this, v, void 0);
389
+ l(this, T, void 0);
390
+ this.requestHandler = t, h(this, v, {}), h(this, T, {
394
391
  handleRedirects: !1,
395
392
  maxRedirects: 4,
396
393
  ...r
@@ -418,14 +415,14 @@ class PHPBrowser {
418
415
  cookie: this.serializeCookies()
419
416
  }
420
417
  });
421
- if (s.headers["set-cookie"] && this.setCookies(s.headers["set-cookie"]), a(this, F).handleRedirects && s.headers.location && r < a(this, F).maxRedirects) {
422
- const i = new URL(
418
+ if (s.headers["set-cookie"] && this.setCookies(s.headers["set-cookie"]), o(this, T).handleRedirects && s.headers.location && r < o(this, T).maxRedirects) {
419
+ const n = new URL(
423
420
  s.headers.location[0],
424
421
  this.requestHandler.absoluteUrl
425
422
  );
426
423
  return this.request(
427
424
  {
428
- url: i.toString(),
425
+ url: n.toString(),
429
426
  method: "GET",
430
427
  headers: {}
431
428
  },
@@ -455,20 +452,20 @@ class PHPBrowser {
455
452
  try {
456
453
  if (!r.includes("="))
457
454
  continue;
458
- const s = r.indexOf("="), i = r.substring(0, s), n = r.substring(s + 1).split(";")[0];
459
- a(this, b)[i] = n;
455
+ const s = r.indexOf("="), n = r.substring(0, s), i = r.substring(s + 1).split(";")[0];
456
+ o(this, v)[n] = i;
460
457
  } catch (s) {
461
458
  console.error(s);
462
459
  }
463
460
  }
464
461
  serializeCookies() {
465
462
  const t = [];
466
- for (const r in a(this, b))
467
- t.push(`${r}=${a(this, b)[r]}`);
463
+ for (const r in o(this, v))
464
+ t.push(`${r}=${o(this, v)[r]}`);
468
465
  return t.join("; ");
469
466
  }
470
467
  }
471
- b = new WeakMap(), F = new WeakMap();
468
+ v = new WeakMap(), T = new WeakMap();
472
469
  const DEFAULT_BASE_URL = "http://example.com";
473
470
  function toRelativeUrl(e) {
474
471
  return e.toString().substring(e.origin.length);
@@ -479,7 +476,35 @@ function removePathPrefix(e, t) {
479
476
  function ensurePathPrefix(e, t) {
480
477
  return !t || e.startsWith(t) ? e : t + e;
481
478
  }
482
- var E, x, N, R, k, m, C, S, B, Q, L, X, O, ee;
479
+ async function encodeAsMultipart(e) {
480
+ const t = `----${Math.random().toString(36).slice(2)}`, r = `multipart/form-data; boundary=${t}`, s = new TextEncoder(), n = [];
481
+ for (const [d, p] of Object.entries(e))
482
+ n.push(`--${t}\r
483
+ `), n.push(`Content-Disposition: form-data; name="${d}"`), p instanceof File && n.push(`; filename="${p.name}"`), n.push(`\r
484
+ `), p instanceof File && n.push("Content-Type: application/octet-stream"), n.push(`\r
485
+ \r
486
+ `), p instanceof File ? n.push(await fileToUint8Array(p)) : n.push(p), n.push(`\r
487
+ `);
488
+ n.push(`--${t}--\r
489
+ `);
490
+ const i = n.reduce((d, p) => d + p.length, 0), a = new Uint8Array(i);
491
+ let c = 0;
492
+ for (const d of n)
493
+ a.set(
494
+ typeof d == "string" ? s.encode(d) : d,
495
+ c
496
+ ), c += d.length;
497
+ return { bytes: a, contentType: r };
498
+ }
499
+ function fileToUint8Array(e) {
500
+ return new Promise((t) => {
501
+ const r = new FileReader();
502
+ r.onload = () => {
503
+ t(new Uint8Array(r.result));
504
+ }, r.readAsArrayBuffer(e);
505
+ });
506
+ }
507
+ var w, F, I, b, x, m, C, R, M, K, N, Z, B, Q;
483
508
  class PHPRequestHandler {
484
509
  /**
485
510
  * @param php - The PHP instance.
@@ -492,7 +517,7 @@ class PHPRequestHandler {
492
517
  * @param fsPath - Absolute path of the static file to serve.
493
518
  * @returns The response.
494
519
  */
495
- l(this, B);
520
+ l(this, M);
496
521
  /**
497
522
  * Runs the requested PHP file with all the request and $_SERVER
498
523
  * superglobals populated.
@@ -500,7 +525,7 @@ class PHPRequestHandler {
500
525
  * @param request - The request.
501
526
  * @returns The response.
502
527
  */
503
- l(this, L);
528
+ l(this, N);
504
529
  /**
505
530
  * Resolve the requested path to the filesystem path of the requested PHP file.
506
531
  *
@@ -510,31 +535,31 @@ class PHPRequestHandler {
510
535
  * @throws {Error} If the requested path doesn't exist.
511
536
  * @returns The resolved filesystem path.
512
537
  */
513
- l(this, O);
514
- l(this, E, void 0);
538
+ l(this, B);
539
+ l(this, w, void 0);
540
+ l(this, F, void 0);
541
+ l(this, I, void 0);
542
+ l(this, b, void 0);
515
543
  l(this, x, void 0);
516
- l(this, N, void 0);
517
- l(this, R, void 0);
518
- l(this, k, void 0);
519
544
  l(this, m, void 0);
520
545
  l(this, C, void 0);
521
- l(this, S, void 0);
522
- d(this, S, new Semaphore({ concurrency: 1 }));
546
+ l(this, R, void 0);
547
+ h(this, R, new Semaphore({ concurrency: 1 }));
523
548
  const {
524
549
  documentRoot: s = "/www/",
525
- absoluteUrl: i = typeof location == "object" ? location == null ? void 0 : location.href : ""
550
+ absoluteUrl: n = typeof location == "object" ? location == null ? void 0 : location.href : ""
526
551
  } = r;
527
- this.php = t, d(this, E, s);
528
- const n = new URL(i);
529
- d(this, N, n.hostname), d(this, R, n.port ? Number(n.port) : n.protocol === "https:" ? 443 : 80), d(this, x, (n.protocol || "").replace(":", ""));
530
- const o = a(this, R) !== 443 && a(this, R) !== 80;
531
- d(this, k, [
532
- a(this, N),
533
- o ? `:${a(this, R)}` : ""
534
- ].join("")), d(this, m, n.pathname.replace(/\/+$/, "")), d(this, C, [
535
- `${a(this, x)}://`,
536
- a(this, k),
537
- a(this, m)
552
+ this.php = t, h(this, w, s);
553
+ const i = new URL(n);
554
+ h(this, I, i.hostname), h(this, b, i.port ? Number(i.port) : i.protocol === "https:" ? 443 : 80), h(this, F, (i.protocol || "").replace(":", ""));
555
+ const a = o(this, b) !== 443 && o(this, b) !== 80;
556
+ h(this, x, [
557
+ o(this, I),
558
+ a ? `:${o(this, b)}` : ""
559
+ ].join("")), h(this, m, i.pathname.replace(/\/+$/, "")), h(this, C, [
560
+ `${o(this, F)}://`,
561
+ o(this, x),
562
+ o(this, m)
538
563
  ].join(""));
539
564
  }
540
565
  /** @inheritDoc */
@@ -544,32 +569,32 @@ class PHPRequestHandler {
544
569
  /** @inheritDoc */
545
570
  internalUrlToPath(t) {
546
571
  const r = new URL(t);
547
- return r.pathname.startsWith(a(this, m)) && (r.pathname = r.pathname.slice(a(this, m).length)), toRelativeUrl(r);
572
+ return r.pathname.startsWith(o(this, m)) && (r.pathname = r.pathname.slice(o(this, m).length)), toRelativeUrl(r);
548
573
  }
549
574
  get isRequestRunning() {
550
- return a(this, S).running > 0;
575
+ return o(this, R).running > 0;
551
576
  }
552
577
  /** @inheritDoc */
553
578
  get absoluteUrl() {
554
- return a(this, C);
579
+ return o(this, C);
555
580
  }
556
581
  /** @inheritDoc */
557
582
  get documentRoot() {
558
- return a(this, E);
583
+ return o(this, w);
559
584
  }
560
585
  /** @inheritDoc */
561
586
  async request(t) {
562
587
  const r = t.url.startsWith("http://") || t.url.startsWith("https://"), s = new URL(
563
588
  t.url,
564
589
  r ? void 0 : DEFAULT_BASE_URL
565
- ), i = removePathPrefix(
590
+ ), n = removePathPrefix(
566
591
  s.pathname,
567
- a(this, m)
568
- ), n = `${a(this, E)}${i}`;
569
- return seemsLikeAPHPRequestHandlerPath(n) ? await p(this, L, X).call(this, t, s) : p(this, B, Q).call(this, n);
592
+ o(this, m)
593
+ ), i = `${o(this, w)}${n}`;
594
+ return seemsLikeAPHPRequestHandlerPath(i) ? await f(this, N, Z).call(this, t, s) : f(this, M, K).call(this, i);
570
595
  }
571
596
  }
572
- E = new WeakMap(), x = new WeakMap(), N = new WeakMap(), R = new WeakMap(), k = new WeakMap(), m = new WeakMap(), C = new WeakMap(), S = new WeakMap(), B = new WeakSet(), Q = function(t) {
597
+ w = new WeakMap(), F = new WeakMap(), I = new WeakMap(), b = new WeakMap(), x = new WeakMap(), m = new WeakMap(), C = new WeakMap(), R = new WeakMap(), M = new WeakSet(), K = function(t) {
573
598
  if (!this.php.fileExists(t))
574
599
  return new PHPResponse(
575
600
  404,
@@ -594,9 +619,9 @@ E = new WeakMap(), x = new WeakMap(), N = new WeakMap(), R = new WeakMap(), k =
594
619
  },
595
620
  r
596
621
  );
597
- }, L = new WeakSet(), X = async function(t, r) {
598
- var i, n, o;
599
- if (a(this, S).running > 0 && ((i = t.headers) == null ? void 0 : i["x-request-issuer"]) === "php")
622
+ }, N = new WeakSet(), Z = async function(t, r) {
623
+ var n, i;
624
+ if (o(this, R).running > 0 && ((n = t.headers) == null ? void 0 : n["x-request-issuer"]) === "php")
600
625
  return console.warn(
601
626
  "Possible deadlock: Called request() before the previous request() have finished. PHP likely issued an HTTP call to itself. Normally this would lead to infinite waiting as Request 1 holds the lock that the Request 2 is waiting to acquire. That's not useful, so PHPRequestHandler will return error 502 instead."
602
627
  ), new PHPResponse(
@@ -604,47 +629,34 @@ E = new WeakMap(), x = new WeakMap(), N = new WeakMap(), R = new WeakMap(), k =
604
629
  {},
605
630
  new TextEncoder().encode("502 Bad Gateway")
606
631
  );
607
- const s = await a(this, S).acquire();
632
+ const s = await o(this, R).acquire();
608
633
  try {
609
- this.php.addServerGlobalEntry("REMOTE_ADDR", "127.0.0.1"), this.php.addServerGlobalEntry("DOCUMENT_ROOT", a(this, E)), this.php.addServerGlobalEntry(
634
+ this.php.addServerGlobalEntry("REMOTE_ADDR", "127.0.0.1"), this.php.addServerGlobalEntry("DOCUMENT_ROOT", o(this, w)), this.php.addServerGlobalEntry(
610
635
  "HTTPS",
611
- a(this, C).startsWith("https://") ? "on" : ""
636
+ o(this, C).startsWith("https://") ? "on" : ""
612
637
  );
613
- let c = "GET";
614
- const h = {
615
- host: a(this, k),
638
+ let a = "GET";
639
+ const c = {
640
+ host: o(this, x),
616
641
  ...normalizeHeaders(t.headers || {})
617
- }, f = [];
618
- if (t.files && Object.keys(t.files).length) {
619
- c = "POST";
620
- for (const y in t.files) {
621
- const M = t.files[y];
622
- f.push({
623
- key: y,
624
- name: M.name,
625
- type: M.type,
626
- data: new Uint8Array(await M.arrayBuffer())
627
- });
628
- }
629
- (n = h["content-type"]) != null && n.startsWith("multipart/form-data") && (t.formData = parseMultipartFormDataString(
630
- t.body || ""
631
- ), h["content-type"] = "application/x-www-form-urlencoded", delete t.body);
642
+ };
643
+ let d = t.body;
644
+ if (typeof d == "object" && !(d instanceof Uint8Array)) {
645
+ a = "POST";
646
+ const { bytes: u, contentType: _ } = await encodeAsMultipart(d);
647
+ d = u, c["content-type"] = _;
632
648
  }
633
- let u;
634
- t.formData !== void 0 ? (c = "POST", h["content-type"] = h["content-type"] || "application/x-www-form-urlencoded", u = new URLSearchParams(
635
- t.formData
636
- ).toString()) : u = t.body;
637
- let _;
649
+ let p;
638
650
  try {
639
- let y = r.pathname;
640
- if ((o = t.headers) != null && o["x-rewrite-url"])
651
+ let u = r.pathname;
652
+ if ((i = t.headers) != null && i["x-rewrite-url"])
641
653
  try {
642
- y = new URL(
654
+ u = new URL(
643
655
  t.headers["x-rewrite-url"]
644
656
  ).pathname;
645
657
  } catch {
646
658
  }
647
- _ = p(this, O, ee).call(this, y);
659
+ p = f(this, B, Q).call(this, u);
648
660
  } catch {
649
661
  return new PHPResponse(
650
662
  404,
@@ -655,41 +667,25 @@ E = new WeakMap(), x = new WeakMap(), N = new WeakMap(), R = new WeakMap(), k =
655
667
  return await this.php.run({
656
668
  relativeUri: ensurePathPrefix(
657
669
  toRelativeUrl(r),
658
- a(this, m)
670
+ o(this, m)
659
671
  ),
660
- protocol: a(this, x),
661
- method: t.method || c,
662
- body: u,
663
- fileInfos: f,
664
- scriptPath: _,
665
- headers: h
672
+ protocol: o(this, F),
673
+ method: t.method || a,
674
+ body: d,
675
+ scriptPath: p,
676
+ headers: c
666
677
  });
667
678
  } finally {
668
679
  s();
669
680
  }
670
- }, O = new WeakSet(), ee = function(t) {
671
- let r = removePathPrefix(t, a(this, m));
681
+ }, B = new WeakSet(), Q = function(t) {
682
+ let r = removePathPrefix(t, o(this, m));
672
683
  r.includes(".php") ? r = r.split(".php")[0] + ".php" : (r.endsWith("/") || (r += "/"), r.endsWith("index.php") || (r += "index.php"));
673
- const s = `${a(this, E)}${r}`;
684
+ const s = `${o(this, w)}${r}`;
674
685
  if (this.php.fileExists(s))
675
686
  return s;
676
687
  throw new Error(`File not found: ${s}`);
677
688
  };
678
- function parseMultipartFormDataString(e) {
679
- const t = {}, r = e.match(/--(.*)\r\n/);
680
- if (!r)
681
- return t;
682
- const s = r[1], i = e.split(`--${s}`);
683
- return i.shift(), i.pop(), i.forEach((n) => {
684
- const o = n.indexOf(`\r
685
- \r
686
- `), c = n.substring(0, o).trim(), h = n.substring(o + 4).trim(), f = c.match(/name="([^"]+)"/);
687
- if (f) {
688
- const u = f[1];
689
- t[u] = h;
690
- }
691
- }), t;
692
- }
693
689
  function inferMimeType(e) {
694
690
  switch (e.split(".").pop()) {
695
691
  case "css":
@@ -824,16 +820,16 @@ function getEmscriptenFsError(e) {
824
820
  return FileErrorCodes[t];
825
821
  }
826
822
  function rethrowFileSystemError(e = "") {
827
- return function(r, s, i) {
828
- const n = i.value;
829
- i.value = function(...o) {
823
+ return function(r, s, n) {
824
+ const i = n.value;
825
+ n.value = function(...a) {
830
826
  try {
831
- return n.apply(this, o);
827
+ return i.apply(this, a);
832
828
  } catch (c) {
833
- const h = typeof c == "object" ? c == null ? void 0 : c.errno : null;
834
- if (h in FileErrorCodes) {
835
- const f = FileErrorCodes[h], u = typeof o[0] == "string" ? o[0] : null, _ = u !== null ? e.replaceAll("{path}", u) : e;
836
- throw new Error(`${_}: ${f}`, {
829
+ const d = typeof c == "object" ? c == null ? void 0 : c.errno : null;
830
+ if (d in FileErrorCodes) {
831
+ const p = FileErrorCodes[d], u = typeof a[0] == "string" ? a[0] : null, _ = u !== null ? e.replaceAll("{path}", u) : e;
832
+ throw new Error(`${_}: ${p}`, {
837
833
  cause: c
838
834
  });
839
835
  }
@@ -851,12 +847,12 @@ function getLoadedRuntime(e) {
851
847
  return typeof process < "u" && ((e = process.release) == null ? void 0 : e.name) === "node" ? "NODE" : typeof window < "u" ? "WEB" : typeof WorkerGlobalScope < "u" && self instanceof WorkerGlobalScope ? "WORKER" : "NODE";
852
848
  })();
853
849
  var __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __decorateClass = (e, t, r, s) => {
854
- for (var i = s > 1 ? void 0 : s ? __getOwnPropDesc(t, r) : t, n = e.length - 1, o; n >= 0; n--)
855
- (o = e[n]) && (i = (s ? o(t, r, i) : o(i)) || i);
856
- return s && i && __defProp(t, r, i), i;
850
+ for (var n = s > 1 ? void 0 : s ? __getOwnPropDesc(t, r) : t, i = e.length - 1, a; i >= 0; i--)
851
+ (a = e[i]) && (n = (s ? a(t, r, n) : a(n)) || n);
852
+ return s && n && __defProp(t, r, n), n;
857
853
  };
858
854
  const STRING = "string", NUMBER = "number", __private__dont__use = Symbol("__private__dont__use");
859
- var T, H, A, w, P, v, g, I, U, te, D, re, $, se, q, ne, W, ie, j, oe, z, ae, G, le, J, ce, Y, ue, V, de, K, he;
855
+ var S, k, A, y, E, P, g, H, L, X, U, ee, O, te, q, re, $, se, D, ne, W, ie, j, oe, z, ae, G, le, J, ce;
860
856
  class BasePHP {
861
857
  /**
862
858
  * Initializes a PHP runtime.
@@ -866,55 +862,45 @@ class BasePHP {
866
862
  * @param serverOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
867
863
  */
868
864
  constructor(e, t) {
865
+ l(this, L);
869
866
  l(this, U);
870
- l(this, D);
871
- l(this, $);
867
+ l(this, O);
872
868
  l(this, q);
869
+ l(this, $);
870
+ l(this, D);
873
871
  l(this, W);
874
872
  l(this, j);
875
873
  l(this, z);
876
874
  l(this, G);
877
875
  l(this, J);
878
- /**
879
- * Adds file information to $_FILES superglobal in PHP.
880
- *
881
- * In particular:
882
- * * Creates the file data in the filesystem
883
- * * Registers the file details in PHP
884
- *
885
- * @param fileInfo - File details
886
- */
887
- l(this, Y);
888
- l(this, V);
889
- l(this, K);
890
- l(this, T, void 0);
891
- l(this, H, void 0);
876
+ l(this, S, void 0);
877
+ l(this, k, void 0);
892
878
  l(this, A, void 0);
893
- l(this, w, void 0);
879
+ l(this, y, void 0);
880
+ l(this, E, void 0);
894
881
  l(this, P, void 0);
895
- l(this, v, void 0);
896
882
  l(this, g, void 0);
897
- l(this, I, void 0);
898
- d(this, T, []), d(this, w, !1), d(this, P, null), d(this, v, {}), d(this, g, /* @__PURE__ */ new Map()), d(this, I, []), this.semaphore = new Semaphore({ concurrency: 1 }), e !== void 0 && this.initializeRuntime(e), t && (this.requestHandler = new PHPBrowser(
883
+ l(this, H, void 0);
884
+ h(this, S, []), h(this, y, !1), h(this, E, null), h(this, P, {}), h(this, g, /* @__PURE__ */ new Map()), h(this, H, []), this.semaphore = new Semaphore({ concurrency: 1 }), e !== void 0 && this.initializeRuntime(e), t && (this.requestHandler = new PHPBrowser(
899
885
  new PHPRequestHandler(this, t)
900
886
  ));
901
887
  }
902
888
  addEventListener(e, t) {
903
- a(this, g).has(e) || a(this, g).set(e, /* @__PURE__ */ new Set()), a(this, g).get(e).add(t);
889
+ o(this, g).has(e) || o(this, g).set(e, /* @__PURE__ */ new Set()), o(this, g).get(e).add(t);
904
890
  }
905
891
  removeEventListener(e, t) {
906
892
  var r;
907
- (r = a(this, g).get(e)) == null || r.delete(t);
893
+ (r = o(this, g).get(e)) == null || r.delete(t);
908
894
  }
909
895
  dispatchEvent(e) {
910
- const t = a(this, g).get(e.type);
896
+ const t = o(this, g).get(e.type);
911
897
  if (t)
912
898
  for (const r of t)
913
899
  r(e);
914
900
  }
915
901
  /** @inheritDoc */
916
902
  async onMessage(e) {
917
- a(this, I).push(e);
903
+ o(this, H).push(e);
918
904
  }
919
905
  /** @inheritDoc */
920
906
  async setSpawnHandler(handler) {
@@ -945,13 +931,13 @@ class BasePHP {
945
931
  if (!t)
946
932
  throw new Error("Invalid PHP runtime id.");
947
933
  this[__private__dont__use] = t, t.onMessage = async (r) => {
948
- for (const s of a(this, I)) {
949
- const i = await s(r);
950
- if (i)
951
- return i;
934
+ for (const s of o(this, H)) {
935
+ const n = await s(r);
936
+ if (n)
937
+ return n;
952
938
  }
953
939
  return "";
954
- }, d(this, P, improveWASMErrorReporting(t)), this.dispatchEvent({
940
+ }, h(this, E, improveWASMErrorReporting(t)), this.dispatchEvent({
955
941
  type: "runtime.initialized"
956
942
  });
957
943
  }
@@ -966,13 +952,13 @@ class BasePHP {
966
952
  throw new Error(
967
953
  "Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?"
968
954
  );
969
- d(this, A, e);
955
+ h(this, A, e);
970
956
  }
971
957
  /** @inheritDoc */
972
958
  setPhpIniPath(e) {
973
- if (a(this, w))
959
+ if (o(this, y))
974
960
  throw new Error("Cannot set PHP ini path after calling run().");
975
- d(this, H, e), this[__private__dont__use].ccall(
961
+ h(this, k, e), this[__private__dont__use].ccall(
976
962
  "wasm_set_phpini_path",
977
963
  null,
978
964
  ["string"],
@@ -981,9 +967,9 @@ class BasePHP {
981
967
  }
982
968
  /** @inheritDoc */
983
969
  setPhpIniEntry(e, t) {
984
- if (a(this, w))
970
+ if (o(this, y))
985
971
  throw new Error("Cannot set PHP ini entries after calling run().");
986
- a(this, T).push([e, t]);
972
+ o(this, S).push([e, t]);
987
973
  }
988
974
  /** @inheritDoc */
989
975
  chdir(e) {
@@ -1000,25 +986,22 @@ class BasePHP {
1000
986
  const t = await this.semaphore.acquire();
1001
987
  let r;
1002
988
  try {
1003
- a(this, w) || (p(this, U, te).call(this), d(this, w, !0)), p(this, G, le).call(this, e.scriptPath || ""), p(this, $, se).call(this, e.relativeUri || ""), p(this, W, ie).call(this, e.method || "GET");
1004
- const s = normalizeHeaders(e.headers || {}), i = s.host || "example.com:443";
1005
- if (p(this, q, ne).call(this, i, e.protocol || "http"), p(this, j, oe).call(this, s), e.body && (r = p(this, z, ae).call(this, e.body)), e.fileInfos)
1006
- for (const o of e.fileInfos)
1007
- p(this, Y, ue).call(this, o);
1008
- typeof e.code == "string" && p(this, V, de).call(this, " ?>" + e.code), p(this, J, ce).call(this);
1009
- const n = await p(this, K, he).call(this);
1010
- if (e.throwOnError && n.exitCode !== 0) {
1011
- const o = {
1012
- stdout: n.text,
1013
- stderr: n.errors
989
+ o(this, y) || (f(this, L, X).call(this), h(this, y, !0)), f(this, j, oe).call(this, e.scriptPath || ""), f(this, O, te).call(this, e.relativeUri || ""), f(this, $, se).call(this, e.method || "GET");
990
+ const s = normalizeHeaders(e.headers || {}), n = s.host || "example.com:443";
991
+ f(this, q, re).call(this, n, e.protocol || "http"), f(this, D, ne).call(this, s), e.body && (r = f(this, W, ie).call(this, e.body)), typeof e.code == "string" && f(this, G, le).call(this, " ?>" + e.code), f(this, z, ae).call(this);
992
+ const i = await f(this, J, ce).call(this);
993
+ if (e.throwOnError && i.exitCode !== 0) {
994
+ const a = {
995
+ stdout: i.text,
996
+ stderr: i.errors
1014
997
  };
1015
- console.warn("PHP.run() output was:", o);
998
+ console.warn("PHP.run() output was:", a);
1016
999
  const c = new Error(
1017
- `PHP.run() failed with exit code ${n.exitCode} and the following output`
1000
+ `PHP.run() failed with exit code ${i.exitCode} and the following output`
1018
1001
  );
1019
- throw c.output = o, c;
1002
+ throw c.output = a, c;
1020
1003
  }
1021
- return n;
1004
+ return i;
1022
1005
  } finally {
1023
1006
  try {
1024
1007
  r && this[__private__dont__use].free(r);
@@ -1030,7 +1013,7 @@ class BasePHP {
1030
1013
  }
1031
1014
  }
1032
1015
  addServerGlobalEntry(e, t) {
1033
- a(this, v)[e] = t;
1016
+ o(this, P)[e] = t;
1034
1017
  }
1035
1018
  defineConstant(e, t) {
1036
1019
  let r = {};
@@ -1095,7 +1078,7 @@ class BasePHP {
1095
1078
  );
1096
1079
  if (t.prependPath) {
1097
1080
  const s = e.replace(/\/$/, "");
1098
- return r.map((i) => `${s}/${i}`);
1081
+ return r.map((n) => `${s}/${n}`);
1099
1082
  }
1100
1083
  return r;
1101
1084
  } catch (r) {
@@ -1126,7 +1109,7 @@ class BasePHP {
1126
1109
  this.exit();
1127
1110
  } catch {
1128
1111
  }
1129
- if (this.initializeRuntime(e), a(this, H) && this.setPhpIniPath(a(this, H)), a(this, A) && this.setSapiName(a(this, A)), this.requestHandler) {
1112
+ if (this.initializeRuntime(e), o(this, k) && this.setPhpIniPath(o(this, k)), o(this, A) && this.setSapiName(o(this, A)), this.requestHandler) {
1130
1113
  const r = this.documentRoot;
1131
1114
  recreateMemFS(this[__private__dont__use].FS, t, r);
1132
1115
  }
@@ -1139,10 +1122,10 @@ class BasePHP {
1139
1122
  this[__private__dont__use]._exit(e);
1140
1123
  } catch {
1141
1124
  }
1142
- d(this, w, !1), d(this, P, null), delete this[__private__dont__use].onMessage, delete this[__private__dont__use];
1125
+ h(this, y, !1), h(this, E, null), delete this[__private__dont__use].onMessage, delete this[__private__dont__use];
1143
1126
  }
1144
1127
  }
1145
- T = new WeakMap(), H = new WeakMap(), A = new WeakMap(), w = new WeakMap(), P = new WeakMap(), v = new WeakMap(), g = new WeakMap(), I = new WeakMap(), U = new WeakSet(), te = function() {
1128
+ S = new WeakMap(), k = new WeakMap(), A = new WeakMap(), y = new WeakMap(), E = new WeakMap(), P = new WeakMap(), g = new WeakMap(), H = new WeakMap(), L = new WeakSet(), X = function() {
1146
1129
  if (this.setPhpIniEntry("auto_prepend_file", "/tmp/consts.php"), this.fileExists("/tmp/consts.php") || this.writeFile(
1147
1130
  "/tmp/consts.php",
1148
1131
  `<?php
@@ -1154,8 +1137,8 @@ T = new WeakMap(), H = new WeakMap(), A = new WeakMap(), w = new WeakMap(), P =
1154
1137
  }
1155
1138
  }
1156
1139
  }`
1157
- ), a(this, T).length > 0) {
1158
- const e = a(this, T).map(([t, r]) => `${t}=${r}`).join(`
1140
+ ), o(this, S).length > 0) {
1141
+ const e = o(this, S).map(([t, r]) => `${t}=${r}`).join(`
1159
1142
  `) + `
1160
1143
 
1161
1144
  `;
@@ -1167,7 +1150,7 @@ T = new WeakMap(), H = new WeakMap(), A = new WeakMap(), w = new WeakMap(), P =
1167
1150
  );
1168
1151
  }
1169
1152
  this[__private__dont__use].ccall("php_wasm_init", null, [], []);
1170
- }, D = new WeakSet(), re = function() {
1153
+ }, U = new WeakSet(), ee = function() {
1171
1154
  const e = "/tmp/headers.json";
1172
1155
  if (!this.fileExists(e))
1173
1156
  throw new Error(
@@ -1177,14 +1160,14 @@ T = new WeakMap(), H = new WeakMap(), A = new WeakMap(), w = new WeakMap(), P =
1177
1160
  for (const s of t.headers) {
1178
1161
  if (!s.includes(": "))
1179
1162
  continue;
1180
- const i = s.indexOf(": "), n = s.substring(0, i).toLowerCase(), o = s.substring(i + 2);
1181
- n in r || (r[n] = []), r[n].push(o);
1163
+ const n = s.indexOf(": "), i = s.substring(0, n).toLowerCase(), a = s.substring(n + 2);
1164
+ i in r || (r[i] = []), r[i].push(a);
1182
1165
  }
1183
1166
  return {
1184
1167
  headers: r,
1185
1168
  httpStatusCode: t.status
1186
1169
  };
1187
- }, $ = new WeakSet(), se = function(e) {
1170
+ }, O = new WeakSet(), te = function(e) {
1188
1171
  if (this[__private__dont__use].ccall(
1189
1172
  "wasm_set_request_uri",
1190
1173
  null,
@@ -1199,7 +1182,7 @@ T = new WeakMap(), H = new WeakMap(), A = new WeakMap(), w = new WeakMap(), P =
1199
1182
  [t]
1200
1183
  );
1201
1184
  }
1202
- }, q = new WeakSet(), ne = function(e, t) {
1185
+ }, q = new WeakSet(), re = function(e, t) {
1203
1186
  this[__private__dont__use].ccall(
1204
1187
  "wasm_set_request_host",
1205
1188
  null,
@@ -1217,14 +1200,14 @@ T = new WeakMap(), H = new WeakMap(), A = new WeakMap(), w = new WeakMap(), P =
1217
1200
  [NUMBER],
1218
1201
  [r]
1219
1202
  ), (t === "https" || !t && r === 443) && this.addServerGlobalEntry("HTTPS", "on");
1220
- }, W = new WeakSet(), ie = function(e) {
1203
+ }, $ = new WeakSet(), se = function(e) {
1221
1204
  this[__private__dont__use].ccall(
1222
1205
  "wasm_set_request_method",
1223
1206
  null,
1224
1207
  [STRING],
1225
1208
  [e]
1226
1209
  );
1227
- }, j = new WeakSet(), oe = function(e) {
1210
+ }, D = new WeakSet(), ne = function(e) {
1228
1211
  e.cookie && this[__private__dont__use].ccall(
1229
1212
  "wasm_set_cookies",
1230
1213
  null,
@@ -1248,67 +1231,61 @@ T = new WeakMap(), H = new WeakMap(), A = new WeakMap(), w = new WeakMap(), P =
1248
1231
  e[t]
1249
1232
  );
1250
1233
  }
1251
- }, z = new WeakSet(), ae = function(e) {
1252
- const t = this[__private__dont__use].lengthBytesUTF8(e), r = this[__private__dont__use].malloc(t + 1);
1253
- if (!r)
1234
+ }, W = new WeakSet(), ie = function(e) {
1235
+ let t, r;
1236
+ typeof e == "string" ? (console.warn(
1237
+ "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"
1238
+ ), r = this[__private__dont__use].lengthBytesUTF8(e), t = r + 1) : (r = e.byteLength, t = e.byteLength);
1239
+ const s = this[__private__dont__use].malloc(t);
1240
+ if (!s)
1254
1241
  throw new Error("Could not allocate memory for the request body.");
1255
- return this[__private__dont__use].stringToUTF8(
1242
+ return typeof e == "string" ? this[__private__dont__use].stringToUTF8(
1256
1243
  e,
1257
- r,
1244
+ s,
1258
1245
  t + 1
1259
- ), this[__private__dont__use].ccall(
1246
+ ) : this[__private__dont__use].HEAPU8.set(e, s), this[__private__dont__use].ccall(
1260
1247
  "wasm_set_request_body",
1261
1248
  null,
1262
1249
  [NUMBER],
1263
- [r]
1250
+ [s]
1264
1251
  ), this[__private__dont__use].ccall(
1265
1252
  "wasm_set_content_length",
1266
1253
  null,
1267
1254
  [NUMBER],
1268
- [new TextEncoder().encode(e).length]
1269
- ), r;
1270
- }, G = new WeakSet(), le = function(e) {
1255
+ [r]
1256
+ ), s;
1257
+ }, j = new WeakSet(), oe = function(e) {
1271
1258
  this[__private__dont__use].ccall(
1272
1259
  "wasm_set_path_translated",
1273
1260
  null,
1274
1261
  [STRING],
1275
1262
  [e]
1276
1263
  );
1277
- }, J = new WeakSet(), ce = function() {
1278
- for (const e in a(this, v))
1264
+ }, z = new WeakSet(), ae = function() {
1265
+ for (const e in o(this, P))
1279
1266
  this[__private__dont__use].ccall(
1280
1267
  "wasm_add_SERVER_entry",
1281
1268
  null,
1282
1269
  [STRING, STRING],
1283
- [e, a(this, v)[e]]
1270
+ [e, o(this, P)[e]]
1284
1271
  );
1285
- }, Y = new WeakSet(), ue = function(e) {
1286
- const { key: t, name: r, type: s, data: i } = e, n = `/tmp/${Math.random().toFixed(20)}`;
1287
- this.writeFile(n, i);
1288
- const o = 0;
1289
- this[__private__dont__use].ccall(
1290
- "wasm_add_uploaded_file",
1291
- null,
1292
- [STRING, STRING, STRING, STRING, NUMBER, NUMBER],
1293
- [t, r, s, n, o, i.byteLength]
1294
- );
1295
- }, V = new WeakSet(), de = function(e) {
1272
+ }, G = new WeakSet(), le = function(e) {
1296
1273
  this[__private__dont__use].ccall(
1297
1274
  "wasm_set_php_code",
1298
1275
  null,
1299
1276
  [STRING],
1300
1277
  [e]
1301
1278
  );
1302
- }, K = new WeakSet(), he = async function() {
1303
- var i;
1279
+ }, J = new WeakSet(), ce = async function() {
1280
+ var n;
1304
1281
  let e, t;
1305
1282
  try {
1306
- e = await new Promise((n, o) => {
1307
- var h;
1308
- t = (f) => {
1283
+ e = await new Promise((i, a) => {
1284
+ var d;
1285
+ t = (p) => {
1309
1286
  const u = new Error("Rethrown");
1310
- u.cause = f.error, u.betterMessage = f.message, o(u);
1311
- }, (h = a(this, P)) == null || h.addEventListener(
1287
+ u.cause = p.error, u.betterMessage = p.message, a(u);
1288
+ }, (d = o(this, E)) == null || d.addEventListener(
1312
1289
  "error",
1313
1290
  t
1314
1291
  );
@@ -1319,22 +1296,22 @@ T = new WeakMap(), H = new WeakMap(), A = new WeakMap(), w = new WeakMap(), P =
1319
1296
  [],
1320
1297
  { async: !0 }
1321
1298
  );
1322
- return c instanceof Promise ? c.then(n, o) : n(c);
1299
+ return c instanceof Promise ? c.then(i, a) : i(c);
1323
1300
  });
1324
- } catch (n) {
1325
- for (const f in this)
1326
- typeof this[f] == "function" && (this[f] = () => {
1301
+ } catch (i) {
1302
+ for (const p in this)
1303
+ typeof this[p] == "function" && (this[p] = () => {
1327
1304
  throw new Error(
1328
1305
  "PHP runtime has crashed – see the earlier error for details."
1329
1306
  );
1330
1307
  });
1331
1308
  this.functionsMaybeMissingFromAsyncify = getFunctionsMaybeMissingFromAsyncify();
1332
- const o = n, c = "betterMessage" in o ? o.betterMessage : o.message, h = new Error(c);
1333
- throw h.cause = o, h;
1309
+ const a = i, c = "betterMessage" in a ? a.betterMessage : a.message, d = new Error(c);
1310
+ throw d.cause = a, d;
1334
1311
  } finally {
1335
- (i = a(this, P)) == null || i.removeEventListener("error", t), d(this, v, {});
1312
+ (n = o(this, E)) == null || n.removeEventListener("error", t), h(this, P, {});
1336
1313
  }
1337
- const { headers: r, httpStatusCode: s } = p(this, D, re).call(this);
1314
+ const { headers: r, httpStatusCode: s } = f(this, U, ee).call(this);
1338
1315
  return new PHPResponse(
1339
1316
  s,
1340
1317
  r,
@@ -1398,15 +1375,15 @@ function recreateMemFS(e, t, r) {
1398
1375
  return;
1399
1376
  }
1400
1377
  e.mkdirTree(r);
1401
- const i = t.readdir(r).filter((n) => n !== "." && n !== "..");
1402
- for (const n of i)
1403
- recreateMemFS(e, t, joinPaths(r, n));
1378
+ const n = t.readdir(r).filter((i) => i !== "." && i !== "..");
1379
+ for (const i of n)
1380
+ recreateMemFS(e, t, joinPaths(r, i));
1404
1381
  }
1405
1382
  function journalFSEvents(e, t, r = () => {
1406
1383
  }) {
1407
1384
  function s() {
1408
1385
  t = normalizePath(t);
1409
- const n = e[__private__dont__use].FS, o = createFSHooks(n, (u) => {
1386
+ const i = e[__private__dont__use].FS, a = createFSHooks(i, (u) => {
1410
1387
  if (u.path.startsWith(t))
1411
1388
  r(u);
1412
1389
  else if (u.operation === "RENAME" && u.toPath.startsWith(t))
@@ -1417,29 +1394,29 @@ function journalFSEvents(e, t, r = () => {
1417
1394
  ))
1418
1395
  r(_);
1419
1396
  }), c = {};
1420
- for (const [u] of Object.entries(o))
1421
- c[u] = n[u];
1422
- function h() {
1423
- for (const [u, _] of Object.entries(o))
1424
- n[u] = function(...y) {
1425
- return _(...y), c[u].apply(this, y);
1397
+ for (const [u] of Object.entries(a))
1398
+ c[u] = i[u];
1399
+ function d() {
1400
+ for (const [u, _] of Object.entries(a))
1401
+ i[u] = function(...V) {
1402
+ return _(...V), c[u].apply(this, V);
1426
1403
  };
1427
1404
  }
1428
- function f() {
1405
+ function p() {
1429
1406
  for (const [u, _] of Object.entries(c))
1430
1407
  e[__private__dont__use].FS[u] = _;
1431
1408
  }
1432
1409
  e[__private__dont__use].journal = {
1433
- bind: h,
1434
- unbind: f
1435
- }, h();
1410
+ bind: d,
1411
+ unbind: p
1412
+ }, d();
1436
1413
  }
1437
1414
  e.addEventListener("runtime.initialized", s), e[__private__dont__use] && s();
1438
- function i() {
1415
+ function n() {
1439
1416
  e[__private__dont__use].journal.unbind(), delete e[__private__dont__use].journal;
1440
1417
  }
1441
- return e.addEventListener("runtime.beforedestroy", i), function() {
1442
- return e.removeEventListener("runtime.initialized", s), e.removeEventListener("runtime.beforedestroy", i), e[__private__dont__use].journal.unbind();
1418
+ return e.addEventListener("runtime.beforedestroy", n), function() {
1419
+ return e.removeEventListener("runtime.initialized", s), e.removeEventListener("runtime.beforedestroy", n), e[__private__dont__use].journal.unbind();
1443
1420
  };
1444
1421
  }
1445
1422
  const createFSHooks = (e, t = () => {
@@ -1491,16 +1468,16 @@ const createFSHooks = (e, t = () => {
1491
1468
  },
1492
1469
  rename(r, s) {
1493
1470
  try {
1494
- const i = e.lookupPath(r, {
1471
+ const n = e.lookupPath(r, {
1495
1472
  follow: !0
1496
- }), n = e.lookupPath(s, {
1473
+ }), i = e.lookupPath(s, {
1497
1474
  parent: !0
1498
1475
  }).path;
1499
1476
  t({
1500
1477
  operation: "RENAME",
1501
- nodeType: e.isDir(i.node.mode) ? "directory" : "file",
1502
- path: i.path,
1503
- toPath: joinPaths(n, basename(s))
1478
+ nodeType: e.isDir(n.node.mode) ? "directory" : "file",
1479
+ path: n.path,
1480
+ toPath: joinPaths(i, basename(s))
1504
1481
  });
1505
1482
  } catch {
1506
1483
  }
@@ -1546,52 +1523,52 @@ function normalizeFilesystemOperations(e) {
1546
1523
  const t = {};
1547
1524
  for (let r = e.length - 1; r >= 0; r--) {
1548
1525
  for (let s = r - 1; s >= 0; s--) {
1549
- const i = checkRelationship(e[r], e[s]);
1550
- if (i === "none")
1526
+ const n = checkRelationship(e[r], e[s]);
1527
+ if (n === "none")
1551
1528
  continue;
1552
- const n = e[r], o = e[s];
1553
- if (n.operation === "RENAME" && o.operation === "RENAME") {
1529
+ const i = e[r], a = e[s];
1530
+ if (i.operation === "RENAME" && a.operation === "RENAME") {
1554
1531
  console.warn(
1555
1532
  "[FS Journal] Normalizing a double rename is not yet supported:",
1556
1533
  {
1557
- current: n,
1558
- last: o
1534
+ current: i,
1535
+ last: a
1559
1536
  }
1560
1537
  );
1561
1538
  continue;
1562
1539
  }
1563
- (o.operation === "CREATE" || o.operation === "WRITE") && (n.operation === "RENAME" ? i === "same_node" ? (t[s] = [], t[r] = [
1540
+ (a.operation === "CREATE" || a.operation === "WRITE") && (i.operation === "RENAME" ? n === "same_node" ? (t[s] = [], t[r] = [
1564
1541
  {
1565
- ...o,
1566
- path: n.toPath
1542
+ ...a,
1543
+ path: i.toPath
1567
1544
  },
1568
1545
  ...t[r] || []
1569
- ]) : i === "descendant" && (t[s] = [], t[r] = [
1546
+ ]) : n === "descendant" && (t[s] = [], t[r] = [
1570
1547
  {
1571
- ...o,
1548
+ ...a,
1572
1549
  path: joinPaths(
1573
- n.toPath,
1574
- o.path.substring(n.path.length)
1550
+ i.toPath,
1551
+ a.path.substring(i.path.length)
1575
1552
  )
1576
1553
  },
1577
1554
  ...t[r] || []
1578
- ]) : n.operation === "WRITE" && i === "same_node" ? t[s] = [] : n.operation === "DELETE" && i === "same_node" && (t[s] = [], t[r] = []));
1555
+ ]) : i.operation === "WRITE" && n === "same_node" ? t[s] = [] : i.operation === "DELETE" && n === "same_node" && (t[s] = [], t[r] = []));
1579
1556
  }
1580
1557
  if (Object.entries(t).length > 0) {
1581
- const s = e.flatMap((i, n) => n in t ? t[n] : [i]);
1558
+ const s = e.flatMap((n, i) => i in t ? t[i] : [n]);
1582
1559
  return normalizeFilesystemOperations(s);
1583
1560
  }
1584
1561
  }
1585
1562
  return e;
1586
1563
  }
1587
1564
  function checkRelationship(e, t) {
1588
- const r = e.path, s = e.operation !== "WRITE" && e.nodeType === "directory", i = t.operation !== "WRITE" && t.nodeType === "directory", n = t.operation === "RENAME" ? t.toPath : t.path;
1589
- return n === r ? "same_node" : i && r.startsWith(n + "/") ? "ancestor" : s && n.startsWith(r + "/") ? "descendant" : "none";
1565
+ const r = e.path, s = e.operation !== "WRITE" && e.nodeType === "directory", n = t.operation !== "WRITE" && t.nodeType === "directory", i = t.operation === "RENAME" ? t.toPath : t.path;
1566
+ return i === r ? "same_node" : n && r.startsWith(i + "/") ? "ancestor" : s && i.startsWith(r + "/") ? "descendant" : "none";
1590
1567
  }
1591
1568
  async function hydrateUpdateFileOps(e, t) {
1592
1569
  const s = t.filter(
1593
- (i) => i.operation === "WRITE"
1594
- ).map((i) => hydrateOp(e, i));
1570
+ (n) => n.operation === "WRITE"
1571
+ ).map((n) => hydrateOp(e, n));
1595
1572
  return await Promise.all(s), t;
1596
1573
  }
1597
1574
  const hydrateLock = new Semaphore({ concurrency: 15 });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@php-wasm/fs-journal",
3
- "version": "0.6.1",
3
+ "version": "0.6.3",
4
4
  "description": "Bindings to journal the PHP filesystem",
5
5
  "repository": {
6
6
  "type": "git",
@@ -36,7 +36,7 @@
36
36
  "main": "./index.cjs",
37
37
  "module": "./index.js",
38
38
  "license": "GPL-2.0-or-later",
39
- "gitHead": "171b22b853786b8912d9624ea064eaa1e985e96b",
39
+ "gitHead": "0a8916ec08aa5f02de5fea308b287171e7948e4b",
40
40
  "engines": {
41
41
  "node": ">=18.18.2",
42
42
  "npm": ">=8.11.0"
@@ -1,4 +0,0 @@
1
- const e = {};
2
- export {
3
- e as default
4
- };
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e={};exports.default=e;