@php-wasm/fs-journal 0.5.1

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 ADDED
@@ -0,0 +1,48 @@
1
+ "use strict";var re=(r,e,t)=>{if(!e.has(r))throw TypeError("Cannot "+t)};var a=(r,e,t)=>(re(r,e,"read from private field"),t?t.call(r):e.get(r)),c=(r,e,t)=>{if(e.has(r))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(r):e.set(r,t)},d=(r,e,t,s)=>(re(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t);var m=(r,e,t)=>(re(r,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ie=Symbol("error"),ae=Symbol("message");class ne extends Event{constructor(e,t={}){super(e),this[ie]=t.error===void 0?null:t.error,this[ae]=t.message===void 0?"":t.message}get error(){return this[ie]}get message(){return this[ae]}}Object.defineProperty(ne.prototype,"error",{enumerable:!0});Object.defineProperty(ne.prototype,"message",{enumerable:!0});const $e=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:ne;function Ie(r){return r instanceof Error?"exitCode"in r&&(r==null?void 0:r.exitCode)===0||(r==null?void 0:r.name)==="ExitStatus"&&"status"in r&&r.status===0:!1}class Ne extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(e,t){++this.listenersCount,super.addEventListener(e,t)}removeEventListener(e,t){--this.listenersCount,super.removeEventListener(e,t)}hasListeners(){return this.listenersCount>0}}function Me(r){r.asm={...r.asm};const e=new Ne;for(const t in r.asm)if(typeof r.asm[t]=="function"){const s=r.asm[t];r.asm[t]=function(...n){var o;try{return s(...n)}catch(i){if(!(i instanceof Error))throw i;const h=Ue(i,(o=r.lastAsyncifyStackSource)==null?void 0:o.stack);if(r.lastAsyncifyStackSource&&(i.cause=r.lastAsyncifyStackSource),e.hasListeners()){e.dispatchEvent(new $e("error",{error:i,message:h}));return}throw Ie(i)||De(h),i}}}return e}let se=[];function Le(){return se}function Ue(r,e){if(r.message==="unreachable"){let t=We;e||(t+=`
2
+
3
+ This stack trace is lacking. For a better one initialize
4
+ the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
5
+
6
+ `),se=qe(e||r.stack||"");for(const s of se)t+=` * ${s}
7
+ `;return t}return r.message}const We=`
8
+ "unreachable" WASM instruction executed.
9
+
10
+ The typical reason is a PHP function missing from the ASYNCIFY_ONLY
11
+ list when building PHP.wasm.
12
+
13
+ You will need to file a new issue in the WordPress Playground repository
14
+ and paste this error message there:
15
+
16
+ https://github.com/WordPress/wordpress-playground/issues/new
17
+
18
+ If you're a core developer, the typical fix is to:
19
+
20
+ * Isolate a minimal reproduction of the error
21
+ * Add a reproduction of the error to php-asyncify.spec.ts in the WordPress Playground repository
22
+ * Run 'npm run fix-asyncify'
23
+ * Commit the changes, push to the repo, release updated NPM packages
24
+
25
+ Below is a list of all the PHP functions found in the stack trace to
26
+ help with the minimal reproduction. If they're all already listed in
27
+ the Dockerfile, you'll need to trigger this error again with long stack
28
+ traces enabled. In node.js, you can do it using the --stack-trace-limit=100
29
+ CLI option:
30
+
31
+ `,le="\x1B[41m",je="\x1B[1m",ce="\x1B[0m",he="\x1B[K";let ue=!1;function De(r){if(!ue){ue=!0,console.log(`${le}
32
+ ${he}
33
+ ${je} WASM ERROR${ce}${le}`);for(const e of r.split(`
34
+ `))console.log(`${he} ${e} `);console.log(`${ce}`)}}function qe(r){try{const e=r.split(`
35
+ `).slice(1).map(t=>{const s=t.trim().substring(3).split(" ");return{fn:s.length>=2?s[0]:"<unknown>",isWasm:t.includes("wasm://")}}).filter(({fn:t,isWasm:s})=>s&&!t.startsWith("dynCall_")&&!t.startsWith("invoke_")).map(({fn:t})=>t);return Array.from(new Set(e))}catch{return[]}}class A{constructor(e,t,s,n="",o=0){this.httpStatusCode=e,this.headers=t,this.bytes=s,this.exitCode=o,this.errors=n}static fromRawData(e){return new A(e.httpStatusCode,e.headers,e.bytes,e.errors,e.exitCode)}toRawData(){return{headers:this.headers,bytes:this.bytes,errors:this.errors,exitCode:this.exitCode,httpStatusCode:this.httpStatusCode}}get json(){return JSON.parse(this.text)}get text(){return new TextDecoder().decode(this.bytes)}}var S,O;class Be{constructor(e,t={}){c(this,S,void 0);c(this,O,void 0);this.requestHandler=e,d(this,S,{}),d(this,O,{handleRedirects:!1,maxRedirects:4,...t})}async request(e,t=0){const s=await this.requestHandler.request({...e,headers:{...e.headers,cookie:this.serializeCookies()}});if(s.headers["set-cookie"]&&this.setCookies(s.headers["set-cookie"]),a(this,O).handleRedirects&&s.headers.location&&t<a(this,O).maxRedirects){const n=new URL(s.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:n.toString(),method:"GET",headers:{}},t+1)}return s}pathToInternalUrl(e){return this.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.internalUrlToPath(e)}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}setCookies(e){for(const t of e)try{if(!t.includes("="))continue;const s=t.indexOf("="),n=t.substring(0,s),o=t.substring(s+1).split(";")[0];a(this,S)[n]=o}catch(s){console.error(s)}}serializeCookies(){const e=[];for(const t in a(this,S))e.push(`${t}=${a(this,S)[t]}`);return e.join("; ")}}S=new WeakMap,O=new WeakMap;class oe{constructor({concurrency:e}){this._running=0,this.concurrency=e,this.queue=[]}get running(){return this._running}async acquire(){for(;;)if(this._running>=this.concurrency)await new Promise(e=>this.queue.push(e));else{this._running++;let e=!1;return()=>{e||(e=!0,this._running--,this.queue.length>0&&this.queue.shift()())}}}async run(e){const t=await this.acquire();try{return await e()}finally{t()}}}function W(...r){let e=r.join("/");const t=e[0]==="/",s=e.substring(e.length-1)==="/";return e=me(e),!e&&!t&&(e="."),e&&s&&(e+="/"),e}function ze(r){if(r==="/")return"/";r=me(r);const e=r.lastIndexOf("/");return e===-1?r:r.substr(e+1)}function me(r){const e=r[0]==="/";return r=Ge(r.split("/").filter(t=>!!t),!e).join("/"),(e?"/":"")+r.replace(/\/$/,"")}function Ge(r,e){let t=0;for(let s=r.length-1;s>=0;s--){const n=r[s];n==="."?r.splice(s,1):n===".."?(r.splice(s,1),t++):t&&(r.splice(s,1),t--)}if(e)for(;t;t--)r.unshift("..");return r}const Je="http://example.com";function de(r){return r.toString().substring(r.origin.length)}function pe(r,e){return!e||!r.startsWith(e)?r:r.substring(e.length)}function Ye(r,e){return!e||r.startsWith(e)?r:e+r}var b,H,L,k,$,P,I,N,j,ye,D,ge,q,we;class Ve{constructor(e,t={}){c(this,j);c(this,D);c(this,q);c(this,b,void 0);c(this,H,void 0);c(this,L,void 0);c(this,k,void 0);c(this,$,void 0);c(this,P,void 0);c(this,I,void 0);c(this,N,void 0);d(this,N,new oe({concurrency:1}));const{documentRoot:s="/www/",absoluteUrl:n=typeof location=="object"?location==null?void 0:location.href:""}=t;this.php=e,d(this,b,s);const o=new URL(n);d(this,L,o.hostname),d(this,k,o.port?Number(o.port):o.protocol==="https:"?443:80),d(this,H,(o.protocol||"").replace(":",""));const i=a(this,k)!==443&&a(this,k)!==80;d(this,$,[a(this,L),i?`:${a(this,k)}`:""].join("")),d(this,P,o.pathname.replace(/\/+$/,"")),d(this,I,[`${a(this,H)}://`,a(this,$),a(this,P)].join(""))}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const t=new URL(e);return t.pathname.startsWith(a(this,P))&&(t.pathname=t.pathname.slice(a(this,P).length)),de(t)}get isRequestRunning(){return a(this,N).running>0}get absoluteUrl(){return a(this,I)}get documentRoot(){return a(this,b)}async request(e){const t=e.url.startsWith("http://")||e.url.startsWith("https://"),s=new URL(e.url,t?void 0:Je),n=pe(s.pathname,a(this,P)),o=`${a(this,b)}${n}`;return Qe(o)?await m(this,D,ge).call(this,e,s):m(this,j,ye).call(this,o)}}b=new WeakMap,H=new WeakMap,L=new WeakMap,k=new WeakMap,$=new WeakMap,P=new WeakMap,I=new WeakMap,N=new WeakMap,j=new WeakSet,ye=function(e){if(!this.php.fileExists(e))return new A(404,{"x-file-type":["static"]},new TextEncoder().encode("404 File not found"));const t=this.php.readFileAsBuffer(e);return new A(200,{"content-length":[`${t.byteLength}`],"content-type":[Ze(e)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},t)},D=new WeakSet,ge=async function(e,t){var n;const s=await a(this,N).acquire();try{this.php.addServerGlobalEntry("DOCUMENT_ROOT",a(this,b)),this.php.addServerGlobalEntry("HTTPS",a(this,I).startsWith("https://")?"on":"");let o="GET";const i={host:a(this,$),...Ae(e.headers||{})},h=[];if(e.files&&Object.keys(e.files).length){o="POST";for(const f in e.files){const T=e.files[f];h.push({key:f,name:T.name,type:T.type,data:new Uint8Array(await T.arrayBuffer())})}(n=i["content-type"])!=null&&n.startsWith("multipart/form-data")&&(e.formData=Ke(e.body||""),i["content-type"]="application/x-www-form-urlencoded",delete e.body)}let u;e.formData!==void 0?(o="POST",i["content-type"]=i["content-type"]||"application/x-www-form-urlencoded",u=new URLSearchParams(e.formData).toString()):u=e.body;let p;try{p=m(this,q,we).call(this,t.pathname)}catch{return new A(404,{},new TextEncoder().encode("404 File not found"))}return await this.php.run({relativeUri:Ye(de(t),a(this,P)),protocol:a(this,H),method:e.method||o,body:u,fileInfos:h,scriptPath:p,headers:i})}finally{s()}},q=new WeakSet,we=function(e){let t=pe(e,a(this,P));t.includes(".php")?t=t.split(".php")[0]+".php":(t.endsWith("/")||(t+="/"),t.endsWith("index.php")||(t+="index.php"));const s=`${a(this,b)}${t}`;if(this.php.fileExists(s))return s;if(!this.php.fileExists(`${a(this,b)}/index.php`))throw new Error(`File not found: ${s}`);return`${a(this,b)}/index.php`};function Ke(r){const e={},t=r.match(/--(.*)\r\n/);if(!t)return e;const s=t[1],n=r.split(`--${s}`);return n.shift(),n.pop(),n.forEach(o=>{const i=o.indexOf(`\r
36
+ \r
37
+ `),h=o.substring(0,i).trim(),u=o.substring(i+4).trim(),p=h.match(/name="([^"]+)"/);if(p){const f=p[1];e[f]=u}}),e}function Ze(r){switch(r.split(".").pop()){case"css":return"text/css";case"js":return"application/javascript";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"svg":return"image/svg+xml";case"woff":return"font/woff";case"woff2":return"font/woff2";case"ttf":return"font/ttf";case"otf":return"font/otf";case"eot":return"font/eot";case"ico":return"image/x-icon";case"html":return"text/html";case"json":return"application/json";case"xml":return"application/xml";case"txt":case"md":return"text/plain";default:return"application-octet-stream"}}function Qe(r){return Xe(r)||et(r)}function Xe(r){return r.endsWith(".php")||r.includes(".php/")}function et(r){return!r.split("/").pop().includes(".")}const fe={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 g(r=""){return function(t,s,n){const o=n.value;n.value=function(...i){try{return o.apply(this,i)}catch(h){const u=typeof h=="object"?h==null?void 0:h.errno:null;if(u in fe){const p=fe[u],f=typeof i[0]=="string"?i[0]:null,T=f!==null?r.replaceAll("{path}",f):r;throw new Error(`${T}: ${p}`,{cause:h})}throw h}}}}const tt=new Map;function rt(r){return tt.get(r)}(function(){var r;return typeof process<"u"&&((r=process.release)==null?void 0:r.name)==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"})();var st=Object.defineProperty,nt=Object.getOwnPropertyDescriptor,w=(r,e,t,s)=>{for(var n=s>1?void 0:s?nt(e,t):e,o=r.length-1,i;o>=0;o--)(i=r[o])&&(n=(s?i(e,t,n):i(n))||n);return s&&n&&st(e,t,n),n};const y="string",C="number",l=Symbol("__private__dont__use");var x,v,F,R,_,M,U,B,Ee,z,be,G,Pe,J,Te,Y,_e,V,ve,K,Re,Z,Se,Q,ke,X,xe,ee,Fe,te,Ce;class E{constructor(e,t){c(this,B);c(this,z);c(this,G);c(this,J);c(this,Y);c(this,V);c(this,K);c(this,Z);c(this,Q);c(this,X);c(this,ee);c(this,te);c(this,x,void 0);c(this,v,void 0);c(this,F,void 0);c(this,R,void 0);c(this,_,void 0);c(this,M,void 0);c(this,U,void 0);d(this,x,[]),d(this,v,!1),d(this,F,null),d(this,R,{}),d(this,_,new Map),d(this,M,[]),d(this,U,new oe({concurrency:1})),e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new Be(new Ve(this,t)))}addEventListener(e,t){a(this,_).has(e)||a(this,_).set(e,new Set),a(this,_).get(e).add(t)}removeEventListener(e,t){var s;(s=a(this,_).get(e))==null||s.delete(t)}dispatchEvent(e){const t=a(this,_).get(e.type);if(t)for(const s of t)s(e)}async onMessage(e){a(this,M).push(e)}async setSpawnHandler(e){this[l].spawnProcess=e}get absoluteUrl(){return this.requestHandler.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.requestHandler.documentRoot}pathToInternalUrl(e){return this.requestHandler.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.requestHandler.requestHandler.internalUrlToPath(e)}initializeRuntime(e){if(this[l])throw new Error("PHP runtime already initialized.");const t=rt(e);if(!t)throw new Error("Invalid PHP runtime id.");this[l]=t,t.onMessage=async s=>{for(const n of a(this,M)){const o=await n(s);if(o)return o}return""},d(this,F,Me(t))}setPhpIniPath(e){if(a(this,v))throw new Error("Cannot set PHP ini path after calling run().");this[l].ccall("wasm_set_phpini_path",null,["string"],[e])}setPhpIniEntry(e,t){if(a(this,v))throw new Error("Cannot set PHP ini entries after calling run().");a(this,x).push([e,t])}chdir(e){this[l].FS.chdir(e)}async request(e,t){if(!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(e,t)}async run(e){const t=await a(this,U).acquire();try{a(this,v)||(m(this,B,Ee).call(this),d(this,v,!0)),m(this,Z,Se).call(this,e.scriptPath||""),m(this,G,Pe).call(this,e.relativeUri||""),m(this,Y,_e).call(this,e.method||"GET");const s=Ae(e.headers||{}),n=s.host||"example.com:443";if(m(this,J,Te).call(this,n,e.protocol||"http"),m(this,V,ve).call(this,s),e.body&&m(this,K,Re).call(this,e.body),e.fileInfos)for(const o of e.fileInfos)m(this,X,xe).call(this,o);return e.code&&m(this,ee,Fe).call(this," ?>"+e.code),m(this,Q,ke).call(this),await m(this,te,Ce).call(this)}finally{t(),this.dispatchEvent({type:"request.end"})}}addServerGlobalEntry(e,t){a(this,R)[e]=t}defineConstant(e,t){let s={};try{s=JSON.parse(this.fileExists("/tmp/consts.json")&&this.readFileAsText("/tmp/consts.json")||"{}")}catch{}this.writeFile("/tmp/consts.json",JSON.stringify({...s,[e]:t}))}mkdir(e){this[l].FS.mkdirTree(e)}mkdirTree(e){this.mkdir(e)}readFileAsText(e){return new TextDecoder().decode(this.readFileAsBuffer(e))}readFileAsBuffer(e){return this[l].FS.readFile(e)}writeFile(e,t){this[l].FS.writeFile(e,t)}unlink(e){this[l].FS.unlink(e)}mv(e,t){this[l].FS.rename(e,t)}rmdir(e,t={recursive:!0}){t!=null&&t.recursive&&this.listFiles(e).forEach(s=>{const n=`${e}/${s}`;this.isDir(n)?this.rmdir(n,t):this.unlink(n)}),this[l].FS.rmdir(e)}listFiles(e,t={prependPath:!1}){if(!this.fileExists(e))return[];try{const s=this[l].FS.readdir(e).filter(n=>n!=="."&&n!=="..");if(t.prependPath){const n=e.replace(/\/$/,"");return s.map(o=>`${n}/${o}`)}return s}catch(s){return console.error(s,{path:e}),[]}}isDir(e){return this.fileExists(e)?this[l].FS.isDir(this[l].FS.lookupPath(e).node.mode):!1}fileExists(e){try{return this[l].FS.lookupPath(e),!0}catch{return!1}}exit(e=0){return this[l]._exit(e)}}x=new WeakMap,v=new WeakMap,F=new WeakMap,R=new WeakMap,_=new WeakMap,M=new WeakMap,U=new WeakMap,B=new WeakSet,Ee=function(){if(this.setPhpIniEntry("auto_prepend_file","/tmp/consts.php"),this.fileExists("/tmp/consts.php")||this.writeFile("/tmp/consts.php",`<?php
38
+ if(file_exists('/tmp/consts.json')) {
39
+ $consts = json_decode(file_get_contents('/tmp/consts.json'), true);
40
+ foreach ($consts as $const => $value) {
41
+ if (!defined($const) && is_scalar($value)) {
42
+ define($const, $value);
43
+ }
44
+ }
45
+ }`),a(this,x).length>0){const e=a(this,x).map(([t,s])=>`${t}=${s}`).join(`
46
+ `)+`
47
+
48
+ `;this[l].ccall("wasm_set_phpini_entries",null,[y],[e])}this[l].ccall("php_wasm_init",null,[],[])},z=new WeakSet,be=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)),s={};for(const n of t.headers){if(!n.includes(": "))continue;const o=n.indexOf(": "),i=n.substring(0,o).toLowerCase(),h=n.substring(o+2);i in s||(s[i]=[]),s[i].push(h)}return{headers:s,httpStatusCode:t.status}},G=new WeakSet,Pe=function(e){if(this[l].ccall("wasm_set_request_uri",null,[y],[e]),e.includes("?")){const t=e.substring(e.indexOf("?")+1);this[l].ccall("wasm_set_query_string",null,[y],[t])}},J=new WeakSet,Te=function(e,t){this[l].ccall("wasm_set_request_host",null,[y],[e]);let s;try{s=parseInt(new URL(e).port,10)}catch{}(!s||isNaN(s)||s===80)&&(s=t==="https"?443:80),this[l].ccall("wasm_set_request_port",null,[C],[s]),(t==="https"||!t&&s===443)&&this.addServerGlobalEntry("HTTPS","on")},Y=new WeakSet,_e=function(e){this[l].ccall("wasm_set_request_method",null,[y],[e])},V=new WeakSet,ve=function(e){e.cookie&&this[l].ccall("wasm_set_cookies",null,[y],[e.cookie]),e["content-type"]&&this[l].ccall("wasm_set_content_type",null,[y],[e["content-type"]]),e["content-length"]&&this[l].ccall("wasm_set_content_length",null,[C],[parseInt(e["content-length"],10)]);for(const t in e){let s="HTTP_";["content-type","content-length"].includes(t.toLowerCase())&&(s=""),this.addServerGlobalEntry(`${s}${t.toUpperCase().replace(/-/g,"_")}`,e[t])}},K=new WeakSet,Re=function(e){this[l].ccall("wasm_set_request_body",null,[y],[e]),this[l].ccall("wasm_set_content_length",null,[C],[new TextEncoder().encode(e).length])},Z=new WeakSet,Se=function(e){this[l].ccall("wasm_set_path_translated",null,[y],[e])},Q=new WeakSet,ke=function(){for(const e in a(this,R))this[l].ccall("wasm_add_SERVER_entry",null,[y,y],[e,a(this,R)[e]])},X=new WeakSet,xe=function(e){const{key:t,name:s,type:n,data:o}=e,i=`/tmp/${Math.random().toFixed(20)}`;this.writeFile(i,o);const h=0;this[l].ccall("wasm_add_uploaded_file",null,[y,y,y,y,C,C],[t,s,n,i,h,o.byteLength])},ee=new WeakSet,Fe=function(e){this[l].ccall("wasm_set_php_code",null,[y],[e])},te=new WeakSet,Ce=async function(){var o;let e,t;try{e=await new Promise((i,h)=>{var p;t=f=>{const T=new Error("Rethrown");T.cause=f.error,T.betterMessage=f.message,h(T)},(p=a(this,F))==null||p.addEventListener("error",t);const u=this[l].ccall("wasm_sapi_handle_request",C,[],[],{async:!0});return u instanceof Promise?u.then(i,h):i(u)})}catch(i){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=Le();const h=i,u="betterMessage"in h?h.betterMessage:h.message,p=new Error(u);throw p.cause=h,p}finally{(o=a(this,F))==null||o.removeEventListener("error",t),d(this,R,{})}const{headers:s,httpStatusCode:n}=m(this,z,be).call(this);return new A(n,s,this.readFileAsBuffer("/tmp/stdout"),this.readFileAsText("/tmp/stderr"),e)};w([g('Could not create directory "{path}"')],E.prototype,"mkdir",1);w([g('Could not create directory "{path}"')],E.prototype,"mkdirTree",1);w([g('Could not read "{path}"')],E.prototype,"readFileAsText",1);w([g('Could not read "{path}"')],E.prototype,"readFileAsBuffer",1);w([g('Could not write to "{path}"')],E.prototype,"writeFile",1);w([g('Could not unlink "{path}"')],E.prototype,"unlink",1);w([g('Could not move "{path}"')],E.prototype,"mv",1);w([g('Could not remove directory "{path}"')],E.prototype,"rmdir",1);w([g('Could not list files in "{path}"')],E.prototype,"listFiles",1);w([g('Could not stat "{path}"')],E.prototype,"isDir",1);w([g('Could not stat "{path}"')],E.prototype,"fileExists",1);function Ae(r){const e={};for(const t in r)e[t.toLowerCase()]=r[t];return e}function ot(r,e,t=()=>{}){e=lt(e);const s=r[l].FS,n=it(s,u=>{if(u.path.startsWith(e))t(u);else if(u.operation==="RENAME"&&u.toPath.startsWith(e))for(const p of Oe(r,u.path,u.toPath))t(p)}),o={};for(const[u]of Object.entries(n))o[u]=s[u];function i(){for(const[u,p]of Object.entries(n))s[u]=function(...f){return p(...f),o[u].apply(this,f)}}function h(){for(const[u,p]of Object.entries(o))r[l].FS[u]=p}return r[l].journal={bind:i,unbind:h},i(),h}const it=(r,e=()=>{})=>({write(t){e({operation:"WRITE",path:t.path,nodeType:"file"})},truncate(t){let s;typeof t=="string"?s=r.lookupPath(t,{follow:!0}).node:s=t,e({operation:"WRITE",path:r.getPath(s),nodeType:"file"})},unlink(t){e({operation:"DELETE",path:t,nodeType:"file"})},mknod(t,s){r.isFile(s)&&e({operation:"CREATE",path:t,nodeType:"file"})},mkdir(t){e({operation:"CREATE",path:t,nodeType:"directory"})},rmdir(t){e({operation:"DELETE",path:t,nodeType:"directory"})},rename(t,s){try{const n=r.lookupPath(t,{follow:!0}),o=r.lookupPath(s,{parent:!0}).path;e({operation:"RENAME",nodeType:r.isDir(n.node.mode)?"directory":"file",path:n.path,toPath:W(o,ze(s))})}catch{}}});function at(r,e){r[l].journal.unbind();try{for(const t of e)t.operation==="CREATE"?t.nodeType==="file"?r.writeFile(t.path," "):r.mkdir(t.path):t.operation==="DELETE"?t.nodeType==="file"?r.unlink(t.path):r.rmdir(t.path):t.operation==="WRITE"?r.writeFile(t.path,t.data):t.operation==="RENAME"&&r.mv(t.path,t.toPath)}finally{r[l].journal.bind()}}function*Oe(r,e,t){if(r.isDir(e)){yield{operation:"CREATE",path:t,nodeType:"directory"};for(const s of r.listFiles(e))yield*Oe(r,W(e,s),W(t,s))}else yield{operation:"CREATE",path:t,nodeType:"file"},yield{operation:"WRITE",nodeType:"file",path:t}}function lt(r){return r.replace(/\/$/,"").replace(/\/\/+/g,"/")}function He(r){const e={};for(let t=r.length-1;t>=0;t--){for(let s=t-1;s>=0;s--){const n=ct(r[t],r[s]);if(n==="none")continue;const o=r[t],i=r[s];if(o.operation==="RENAME"&&i.operation==="RENAME"){console.warn("[FS Journal] Normalizing a double rename is not yet supported:",{current:o,last:i});continue}(i.operation==="CREATE"||i.operation==="WRITE")&&(o.operation==="RENAME"?n==="same_node"?(e[s]=[],e[t]=[{...i,path:o.toPath},...e[t]||[]]):n==="descendant"&&(e[s]=[],e[t]=[{...i,path:W(o.toPath,i.path.substring(o.path.length))},...e[t]||[]]):o.operation==="WRITE"&&n==="same_node"?e[s]=[]:o.operation==="DELETE"&&n==="same_node"&&(e[s]=[],e[t]=[]))}if(Object.entries(e).length>0){const s=r.flatMap((n,o)=>o in e?e[o]:[n]);return He(s)}}return r}function ct(r,e){const t=r.path,s=r.operation!=="WRITE"&&r.nodeType==="directory",n=e.operation!=="WRITE"&&e.nodeType==="directory",o=e.operation==="RENAME"?e.toPath:e.path;return o===t?"same_node":n&&t.startsWith(o+"/")?"ancestor":s&&o.startsWith(t+"/")?"descendant":"none"}async function ht(r,e){const s=e.filter(n=>n.operation==="WRITE").map(n=>dt(r,n));return await Promise.all(s),e}const ut=new oe({concurrency:15});async function dt(r,e){const t=await ut.acquire();try{e.data=await r.readFileAsBuffer(e.path)}catch(s){console.warn(`Journal failed to hydrate a file on flush: the path ${e.path} no longer exists`),console.error(s)}t()}exports.hydrateUpdateFileOps=ht;exports.journalFSEvents=ot;exports.normalizeFilesystemOperations=He;exports.replayFSJournal=at;
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './lib';