@php-wasm/fs-journal 0.5.2 → 0.5.4
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 +9 -9
- package/index.js +484 -398
- package/package.json +3 -3
package/index.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var ne=(r,e,t)=>{if(!e.has(r))throw TypeError("Cannot "+t)};var a=(r,e,t)=>(ne(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,n)=>(ne(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t);var m=(r,e,t)=>(ne(r,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});if(typeof File>"u"){class r extends Blob{constructor(t,n,s){super(t);let o;s!=null&&s.lastModified&&(o=new Date),(!o||isNaN(o.getFullYear()))&&(o=new Date),this.lastModifiedDate=o,this.lastModified=o.getMilliseconds(),this.name=n||""}}global.File=r}function me(r){return new Promise(function(e,t){r.onload=r.onerror=function(n){r.onload=r.onerror=null,n.type==="load"?e(r.result):t(new Error("Failed to read the blob/file"))}})}typeof Blob.prototype.arrayBuffer>"u"&&(Blob.prototype.arrayBuffer=function(){const e=new FileReader;return e.readAsArrayBuffer(this),me(e)});typeof Blob.prototype.text>"u"&&(Blob.prototype.text=function(){const e=new FileReader;return e.readAsText(this),me(e)});function Ie(){const r=new Uint8Array([1,2,3,4]),t=new File([r],"test").stream();try{return t.getReader({mode:"byob"}),t.getReader({mode:"byob"}),!0}catch{return!1}}(typeof Blob.prototype.stream>"u"||!Ie())&&(Blob.prototype.stream=function(){let r=0;const e=this;return new ReadableStream({type:"bytes",autoAllocateChunkSize:512*1024,async pull(t){const n=t.byobRequest.view,o=await e.slice(r,r+n.byteLength).arrayBuffer(),i=new Uint8Array(o);new Uint8Array(n.buffer).set(i);const u=i.byteLength;t.byobRequest.respond(u),r+=u,r>=e.size&&t.close()}})});if(typeof CustomEvent>"u"){class r extends Event{constructor(t,n={}){super(t,n),this.detail=n.detail}initCustomEvent(){}}globalThis.CustomEvent=r}const ae=Symbol("error"),le=Symbol("message");class oe extends Event{constructor(e,t={}){super(e),this[ae]=t.error===void 0?null:t.error,this[le]=t.message===void 0?"":t.message}get error(){return this[ae]}get message(){return this[le]}}Object.defineProperty(oe.prototype,"error",{enumerable:!0});Object.defineProperty(oe.prototype,"message",{enumerable:!0});const Ne=typeof globalThis.ErrorEvent=="function"?globalThis.ErrorEvent:oe;function Me(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 Le 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 Ue(r){r.asm={...r.asm};const e=new Le;for(const t in r.asm)if(typeof r.asm[t]=="function"){const n=r.asm[t];r.asm[t]=function(...s){var o;try{return n(...s)}catch(i){if(!(i instanceof Error))throw i;const u=De(i,(o=r.lastAsyncifyStackSource)==null?void 0:o.stack);if(r.lastAsyncifyStackSource&&(i.cause=r.lastAsyncifyStackSource),e.hasListeners()){e.dispatchEvent(new Ne("error",{error:i,message:u}));return}throw Me(i)||je(u),i}}}return e}let se=[];function Be(){return se}function De(r,e){if(r.message==="unreachable"){let t=We;e||(t+=`
|
|
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 }).
|
|
5
5
|
|
|
6
|
-
`),se=
|
|
6
|
+
`),se=ze(e||r.stack||"");for(const n of se)t+=` * ${n}
|
|
7
7
|
`;return t}return r.message}const We=`
|
|
8
8
|
"unreachable" WASM instruction executed.
|
|
9
9
|
|
|
@@ -28,13 +28,13 @@ the Dockerfile, you'll need to trigger this error again with long stack
|
|
|
28
28
|
traces enabled. In node.js, you can do it using the --stack-trace-limit=100
|
|
29
29
|
CLI option:
|
|
30
30
|
|
|
31
|
-
`,
|
|
31
|
+
`,ce="\x1B[41m",qe="\x1B[1m",ue="\x1B[0m",he="\x1B[K";let de=!1;function je(r){if(!de){de=!0,console.log(`${ce}
|
|
32
32
|
${he}
|
|
33
|
-
${
|
|
34
|
-
`))console.log(`${he} ${e} `);console.log(`${
|
|
35
|
-
`).slice(1).map(t=>{const
|
|
33
|
+
${qe} WASM ERROR${ue}${ce}`);for(const e of r.split(`
|
|
34
|
+
`))console.log(`${he} ${e} `);console.log(`${ue}`)}}function ze(r){try{const e=r.split(`
|
|
35
|
+
`).slice(1).map(t=>{const n=t.trim().substring(3).split(" ");return{fn:n.length>=2?n[0]:"<unknown>",isWasm:t.includes("wasm://")}}).filter(({fn:t,isWasm:n})=>n&&!t.startsWith("dynCall_")&&!t.startsWith("invoke_")).map(({fn:t})=>t);return Array.from(new Set(e))}catch{return[]}}class ie{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 B(...r){let e=r.join("/");const t=e[0]==="/",n=e.substring(e.length-1)==="/";return e=ye(e),!e&&!t&&(e="."),e&&n&&(e+="/"),e}function Ge(r){if(r==="/")return"/";r=ye(r);const e=r.lastIndexOf("/");return e===-1?r:r.substr(e+1)}function ye(r){const e=r[0]==="/";return r=Je(r.split("/").filter(t=>!!t),!e).join("/"),(e?"/":"")+r.replace(/\/$/,"")}function Je(r,e){let t=0;for(let n=r.length-1;n>=0;n--){const s=r[n];s==="."?r.splice(n,1):s===".."?(r.splice(n,1),t++):t&&(r.splice(n,1),t--)}if(e)for(;t;t--)r.unshift("..");return r}ReadableStream.prototype[Symbol.asyncIterator]||(ReadableStream.prototype[Symbol.asyncIterator]=async function*(){const r=this.getReader();try{for(;;){const{done:e,value:t}=await r.read();if(e)return;yield t}}finally{r.releaseLock()}},ReadableStream.prototype.iterate=ReadableStream.prototype[Symbol.asyncIterator]);class A{constructor(e,t,n,s="",o=0){this.httpStatusCode=e,this.headers=t,this.bytes=n,this.exitCode=o,this.errors=s}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 Ye{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 n=await this.requestHandler.request({...e,headers:{...e.headers,cookie:this.serializeCookies()}});if(n.headers["set-cookie"]&&this.setCookies(n.headers["set-cookie"]),a(this,O).handleRedirects&&n.headers.location&&t<a(this,O).maxRedirects){const s=new URL(n.headers.location[0],this.requestHandler.absoluteUrl);return this.request({url:s.toString(),method:"GET",headers:{}},t+1)}return n}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 n=t.indexOf("="),s=t.substring(0,n),o=t.substring(n+1).split(";")[0];a(this,S)[s]=o}catch(n){console.error(n)}}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;const Ve="http://example.com";function fe(r){return r.toString().substring(r.origin.length)}function pe(r,e){return!e||!r.startsWith(e)?r:r.substring(e.length)}function Ke(r,e){return!e||r.startsWith(e)?r:e+r}var g,H,L,x,$,w,I,N,W,ge,q,we,j,be;class Ze{constructor(e,t={}){c(this,W);c(this,q);c(this,j);c(this,g,void 0);c(this,H,void 0);c(this,L,void 0);c(this,x,void 0);c(this,$,void 0);c(this,w,void 0);c(this,I,void 0);c(this,N,void 0);d(this,N,new ie({concurrency:1}));const{documentRoot:n="/www/",absoluteUrl:s=typeof location=="object"?location==null?void 0:location.href:""}=t;this.php=e,d(this,g,n);const o=new URL(s);d(this,L,o.hostname),d(this,x,o.port?Number(o.port):o.protocol==="https:"?443:80),d(this,H,(o.protocol||"").replace(":",""));const i=a(this,x)!==443&&a(this,x)!==80;d(this,$,[a(this,L),i?`:${a(this,x)}`:""].join("")),d(this,w,o.pathname.replace(/\/+$/,"")),d(this,I,[`${a(this,H)}://`,a(this,$),a(this,w)].join(""))}pathToInternalUrl(e){return`${this.absoluteUrl}${e}`}internalUrlToPath(e){const t=new URL(e);return t.pathname.startsWith(a(this,w))&&(t.pathname=t.pathname.slice(a(this,w).length)),fe(t)}get isRequestRunning(){return a(this,N).running>0}get absoluteUrl(){return a(this,I)}get documentRoot(){return a(this,g)}async request(e){const t=e.url.startsWith("http://")||e.url.startsWith("https://"),n=new URL(e.url,t?void 0:Ve),s=pe(n.pathname,a(this,w)),o=`${a(this,g)}${s}`;return et(o)?await m(this,q,we).call(this,e,n):m(this,W,ge).call(this,o)}}g=new WeakMap,H=new WeakMap,L=new WeakMap,x=new WeakMap,$=new WeakMap,w=new WeakMap,I=new WeakMap,N=new WeakMap,W=new WeakSet,ge=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":[Xe(e)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},t)},q=new WeakSet,we=async function(e,t){var s;const n=await a(this,N).acquire();try{this.php.addServerGlobalEntry("DOCUMENT_ROOT",a(this,g)),this.php.addServerGlobalEntry("HTTPS",a(this,I).startsWith("https://")?"on":"");let o="GET";const i={host:a(this,$),...Oe(e.headers||{})},u=[];if(e.files&&Object.keys(e.files).length){o="POST";for(const p in e.files){const R=e.files[p];u.push({key:p,name:R.name,type:R.type,data:new Uint8Array(await R.arrayBuffer())})}(s=i["content-type"])!=null&&s.startsWith("multipart/form-data")&&(e.formData=Qe(e.body||""),i["content-type"]="application/x-www-form-urlencoded",delete e.body)}let h;e.formData!==void 0?(o="POST",i["content-type"]=i["content-type"]||"application/x-www-form-urlencoded",h=new URLSearchParams(e.formData).toString()):h=e.body;let f;try{f=m(this,j,be).call(this,t.pathname)}catch{return new A(404,{},new TextEncoder().encode("404 File not found"))}return await this.php.run({relativeUri:Ke(fe(t),a(this,w)),protocol:a(this,H),method:e.method||o,body:h,fileInfos:u,scriptPath:f,headers:i})}finally{n()}},j=new WeakSet,be=function(e){let t=pe(e,a(this,w));t.includes(".php")?t=t.split(".php")[0]+".php":(t.endsWith("/")||(t+="/"),t.endsWith("index.php")||(t+="index.php"));const n=`${a(this,g)}${t}`;if(this.php.fileExists(n))return n;if(!this.php.fileExists(`${a(this,g)}/index.php`))throw new Error(`File not found: ${n}`);return`${a(this,g)}/index.php`};function Qe(r){const e={},t=r.match(/--(.*)\r\n/);if(!t)return e;const n=t[1],s=r.split(`--${n}`);return s.shift(),s.pop(),s.forEach(o=>{const i=o.indexOf(`\r
|
|
36
36
|
\r
|
|
37
|
-
`),
|
|
37
|
+
`),u=o.substring(0,i).trim(),h=o.substring(i+4).trim(),f=u.match(/name="([^"]+)"/);if(f){const p=f[1];e[p]=h}}),e}function Xe(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 et(r){return tt(r)||rt(r)}function tt(r){return r.endsWith(".php")||r.includes(".php/")}function rt(r){return!r.split("/").pop().includes(".")}const D={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 nt(r){const e=typeof r=="object"?r==null?void 0:r.errno:null;if(e in D)return D[e]}function b(r=""){return function(t,n,s){const o=s.value;s.value=function(...i){try{return o.apply(this,i)}catch(u){const h=typeof u=="object"?u==null?void 0:u.errno:null;if(h in D){const f=D[h],p=typeof i[0]=="string"?i[0]:null,R=p!==null?r.replaceAll("{path}",p):r;throw new Error(`${R}: ${f}`,{cause:u})}throw u}}}}const st=new Map;function ot(r){return st.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 it=Object.defineProperty,at=Object.getOwnPropertyDescriptor,E=(r,e,t,n)=>{for(var s=n>1?void 0:n?at(e,t):e,o=r.length-1,i;o>=0;o--)(i=r[o])&&(s=(n?i(e,t,s):i(s))||s);return n&&s&&it(e,t,s),s};const y="string",C="number",l=Symbol("__private__dont__use");var k,T,F,_,v,M,U,z,Ee,G,Pe,J,Re,Y,ve,V,Te,K,_e,Z,Se,Q,xe,X,ke,ee,Fe,te,Ce,re,Ae;class P{constructor(e,t){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,re);c(this,k,void 0);c(this,T,void 0);c(this,F,void 0);c(this,_,void 0);c(this,v,void 0);c(this,M,void 0);c(this,U,void 0);d(this,k,[]),d(this,T,!1),d(this,F,null),d(this,_,{}),d(this,v,new Map),d(this,M,[]),d(this,U,new ie({concurrency:1})),e!==void 0&&this.initializeRuntime(e),t&&(this.requestHandler=new Ye(new Ze(this,t)))}addEventListener(e,t){a(this,v).has(e)||a(this,v).set(e,new Set),a(this,v).get(e).add(t)}removeEventListener(e,t){var n;(n=a(this,v).get(e))==null||n.delete(t)}dispatchEvent(e){const t=a(this,v).get(e.type);if(t)for(const n of t)n(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=ot(e);if(!t)throw new Error("Invalid PHP runtime id.");this[l]=t,t.onMessage=async n=>{for(const s of a(this,M)){const o=await s(n);if(o)return o}return""},d(this,F,Ue(t))}setPhpIniPath(e){if(a(this,T))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,T))throw new Error("Cannot set PHP ini entries after calling run().");a(this,k).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,T)||(m(this,z,Ee).call(this),d(this,T,!0)),m(this,Q,xe).call(this,e.scriptPath||""),m(this,J,Re).call(this,e.relativeUri||""),m(this,V,Te).call(this,e.method||"GET");const n=Oe(e.headers||{}),s=n.host||"example.com:443";if(m(this,Y,ve).call(this,s,e.protocol||"http"),m(this,K,_e).call(this,n),e.body&&m(this,Z,Se).call(this,e.body),e.fileInfos)for(const o of e.fileInfos)m(this,ee,Fe).call(this,o);return e.code&&m(this,te,Ce).call(this," ?>"+e.code),m(this,X,ke).call(this),await m(this,re,Ae).call(this)}finally{t(),this.dispatchEvent({type:"request.end"})}}addServerGlobalEntry(e,t){a(this,_)[e]=t}defineConstant(e,t){let n={};try{n=JSON.parse(this.fileExists("/tmp/consts.json")&&this.readFileAsText("/tmp/consts.json")||"{}")}catch{}this.writeFile("/tmp/consts.json",JSON.stringify({...n,[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){try{this[l].FS.rename(e,t)}catch(n){const s=nt(n);throw s?new Error(`Could not move ${e} to ${t}: ${s}`,{cause:n}):n}}rmdir(e,t={recursive:!0}){t!=null&&t.recursive&&this.listFiles(e).forEach(n=>{const s=`${e}/${n}`;this.isDir(s)?this.rmdir(s,t):this.unlink(s)}),this[l].FS.rmdir(e)}listFiles(e,t={prependPath:!1}){if(!this.fileExists(e))return[];try{const n=this[l].FS.readdir(e).filter(s=>s!=="."&&s!=="..");if(t.prependPath){const s=e.replace(/\/$/,"");return n.map(o=>`${s}/${o}`)}return n}catch(n){return console.error(n,{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)}}k=new WeakMap,T=new WeakMap,F=new WeakMap,_=new WeakMap,v=new WeakMap,M=new WeakMap,U=new WeakMap,z=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
38
|
if(file_exists('/tmp/consts.json')) {
|
|
39
39
|
$consts = json_decode(file_get_contents('/tmp/consts.json'), true);
|
|
40
40
|
foreach ($consts as $const => $value) {
|
|
@@ -42,7 +42,7 @@ ${je} WASM ERROR${ce}${le}`);for(const e of r.split(`
|
|
|
42
42
|
define($const, $value);
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
|
-
}`),a(this,
|
|
45
|
+
}`),a(this,k).length>0){const e=a(this,k).map(([t,n])=>`${t}=${n}`).join(`
|
|
46
46
|
`)+`
|
|
47
47
|
|
|
48
|
-
`;this[l].ccall("wasm_set_phpini_entries",null,[y],[e])}this[l].ccall("php_wasm_init",null,[],[])},
|
|
48
|
+
`;this[l].ccall("wasm_set_phpini_entries",null,[y],[e])}this[l].ccall("php_wasm_init",null,[],[])},G=new WeakSet,Pe=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)),n={};for(const s of t.headers){if(!s.includes(": "))continue;const o=s.indexOf(": "),i=s.substring(0,o).toLowerCase(),u=s.substring(o+2);i in n||(n[i]=[]),n[i].push(u)}return{headers:n,httpStatusCode:t.status}},J=new WeakSet,Re=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])}},Y=new WeakSet,ve=function(e,t){this[l].ccall("wasm_set_request_host",null,[y],[e]);let n;try{n=parseInt(new URL(e).port,10)}catch{}(!n||isNaN(n)||n===80)&&(n=t==="https"?443:80),this[l].ccall("wasm_set_request_port",null,[C],[n]),(t==="https"||!t&&n===443)&&this.addServerGlobalEntry("HTTPS","on")},V=new WeakSet,Te=function(e){this[l].ccall("wasm_set_request_method",null,[y],[e])},K=new WeakSet,_e=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 n="HTTP_";["content-type","content-length"].includes(t.toLowerCase())&&(n=""),this.addServerGlobalEntry(`${n}${t.toUpperCase().replace(/-/g,"_")}`,e[t])}},Z=new WeakSet,Se=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])},Q=new WeakSet,xe=function(e){this[l].ccall("wasm_set_path_translated",null,[y],[e])},X=new WeakSet,ke=function(){for(const e in a(this,_))this[l].ccall("wasm_add_SERVER_entry",null,[y,y],[e,a(this,_)[e]])},ee=new WeakSet,Fe=function(e){const{key:t,name:n,type:s,data:o}=e,i=`/tmp/${Math.random().toFixed(20)}`;this.writeFile(i,o);const u=0;this[l].ccall("wasm_add_uploaded_file",null,[y,y,y,y,C,C],[t,n,s,i,u,o.byteLength])},te=new WeakSet,Ce=function(e){this[l].ccall("wasm_set_php_code",null,[y],[e])},re=new WeakSet,Ae=async function(){var o;let e,t;try{e=await new Promise((i,u)=>{var f;t=p=>{const R=new Error("Rethrown");R.cause=p.error,R.betterMessage=p.message,u(R)},(f=a(this,F))==null||f.addEventListener("error",t);const h=this[l].ccall("wasm_sapi_handle_request",C,[],[],{async:!0});return h instanceof Promise?h.then(i,u):i(h)})}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=Be();const u=i,h="betterMessage"in u?u.betterMessage:u.message,f=new Error(h);throw f.cause=u,f}finally{(o=a(this,F))==null||o.removeEventListener("error",t),d(this,_,{})}const{headers:n,httpStatusCode:s}=m(this,G,Pe).call(this);return new A(s,n,this.readFileAsBuffer("/tmp/stdout"),this.readFileAsText("/tmp/stderr"),e)};E([b('Could not create directory "{path}"')],P.prototype,"mkdir",1);E([b('Could not create directory "{path}"')],P.prototype,"mkdirTree",1);E([b('Could not read "{path}"')],P.prototype,"readFileAsText",1);E([b('Could not read "{path}"')],P.prototype,"readFileAsBuffer",1);E([b('Could not write to "{path}"')],P.prototype,"writeFile",1);E([b('Could not unlink "{path}"')],P.prototype,"unlink",1);E([b('Could not remove directory "{path}"')],P.prototype,"rmdir",1);E([b('Could not list files in "{path}"')],P.prototype,"listFiles",1);E([b('Could not stat "{path}"')],P.prototype,"isDir",1);E([b('Could not stat "{path}"')],P.prototype,"fileExists",1);function Oe(r){const e={};for(const t in r)e[t.toLowerCase()]=r[t];return e}function lt(r,e,t=()=>{}){e=ht(e);const n=r[l].FS,s=ct(n,h=>{if(h.path.startsWith(e))t(h);else if(h.operation==="RENAME"&&h.toPath.startsWith(e))for(const f of He(r,h.path,h.toPath))t(f)}),o={};for(const[h]of Object.entries(s))o[h]=n[h];function i(){for(const[h,f]of Object.entries(s))n[h]=function(...p){return f(...p),o[h].apply(this,p)}}function u(){for(const[h,f]of Object.entries(o))r[l].FS[h]=f}return r[l].journal={bind:i,unbind:u},i(),u}const ct=(r,e=()=>{})=>({write(t){e({operation:"WRITE",path:t.path,nodeType:"file"})},truncate(t){let n;typeof t=="string"?n=r.lookupPath(t,{follow:!0}).node:n=t,e({operation:"WRITE",path:r.getPath(n),nodeType:"file"})},unlink(t){e({operation:"DELETE",path:t,nodeType:"file"})},mknod(t,n){r.isFile(n)&&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,n){try{const s=r.lookupPath(t,{follow:!0}),o=r.lookupPath(n,{parent:!0}).path;e({operation:"RENAME",nodeType:r.isDir(s.node.mode)?"directory":"file",path:s.path,toPath:B(o,Ge(n))})}catch{}}});function ut(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*He(r,e,t){if(r.isDir(e)){yield{operation:"CREATE",path:t,nodeType:"directory"};for(const n of r.listFiles(e))yield*He(r,B(e,n),B(t,n))}else yield{operation:"CREATE",path:t,nodeType:"file"},yield{operation:"WRITE",nodeType:"file",path:t}}function ht(r){return r.replace(/\/$/,"").replace(/\/\/+/g,"/")}function $e(r){const e={};for(let t=r.length-1;t>=0;t--){for(let n=t-1;n>=0;n--){const s=dt(r[t],r[n]);if(s==="none")continue;const o=r[t],i=r[n];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"?s==="same_node"?(e[n]=[],e[t]=[{...i,path:o.toPath},...e[t]||[]]):s==="descendant"&&(e[n]=[],e[t]=[{...i,path:B(o.toPath,i.path.substring(o.path.length))},...e[t]||[]]):o.operation==="WRITE"&&s==="same_node"?e[n]=[]:o.operation==="DELETE"&&s==="same_node"&&(e[n]=[],e[t]=[]))}if(Object.entries(e).length>0){const n=r.flatMap((s,o)=>o in e?e[o]:[s]);return $e(n)}}return r}function dt(r,e){const t=r.path,n=r.operation!=="WRITE"&&r.nodeType==="directory",s=e.operation!=="WRITE"&&e.nodeType==="directory",o=e.operation==="RENAME"?e.toPath:e.path;return o===t?"same_node":s&&t.startsWith(o+"/")?"ancestor":n&&o.startsWith(t+"/")?"descendant":"none"}async function ft(r,e){const n=e.filter(s=>s.operation==="WRITE").map(s=>mt(r,s));return await Promise.all(n),e}const pt=new ie({concurrency:15});async function mt(r,e){const t=await pt.acquire();try{e.data=await r.readFileAsBuffer(e.path)}catch(n){console.warn(`Journal failed to hydrate a file on flush: the path ${e.path} no longer exists`),console.error(n)}t()}exports.hydrateUpdateFileOps=ft;exports.journalFSEvents=lt;exports.normalizeFilesystemOperations=$e;exports.replayFSJournal=ut;
|