@php-wasm/fs-journal 0.7.20 → 0.9.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 CHANGED
@@ -1,53 +1,4 @@
1
- "use strict";var O=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var f=(e,t,r)=>(O(e,t,"read from private field"),r?r.call(e):t.get(e)),d=(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)},p=(e,t,r,s)=>(O(e,t,"write to private field"),s?s.call(e,r):t.set(e,r),r);var h=(e,t,r)=>(O(e,t,"access private method"),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const currentJsRuntime=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"}();if(currentJsRuntime==="NODE"){let e=function(r){return new Promise(function(s,n){r.onload=r.onerror=function(i){r.onload=r.onerror=null,i.type==="load"?s(r.result):n(new Error("Failed to read the blob/file"))}})},t=function(){const r=new Uint8Array([1,2,3,4]),n=new File([r],"test").stream();try{return n.getReader({mode:"byob"}),!0}catch{return!1}};if(typeof File>"u"){class r extends Blob{constructor(n,i,o){super(n);let a;o!=null&&o.lastModified&&(a=new Date),(!a||isNaN(a.getFullYear()))&&(a=new Date),this.lastModifiedDate=a,this.lastModified=a.getMilliseconds(),this.name=i||""}}global.File=r}typeof Blob.prototype.arrayBuffer>"u"&&(Blob.prototype.arrayBuffer=function(){const s=new FileReader;return s.readAsArrayBuffer(this),e(s)}),typeof Blob.prototype.text>"u"&&(Blob.prototype.text=function(){const s=new FileReader;return s.readAsText(this),e(s)}),(typeof Blob.prototype.stream>"u"||!t())&&(Blob.prototype.stream=function(){let r=0;const s=this;return new ReadableStream({type:"bytes",autoAllocateChunkSize:512*1024,async pull(n){const i=n.byobRequest.view,a=await s.slice(r,r+i.byteLength).arrayBuffer(),l=new Uint8Array(a);new Uint8Array(i.buffer).set(l);const c=l.byteLength;n.byobRequest.respond(c),r+=c,r>=s.size&&n.close()}})})}if(currentJsRuntime==="NODE"&&typeof CustomEvent>"u"){class e extends Event{constructor(r,s={}){super(r,s),this.detail=s.detail}initCustomEvent(){}}globalThis.CustomEvent=e}const responseTexts={500:"Internal Server Error",502:"Bad Gateway",404:"Not Found",403:"Forbidden",401:"Unauthorized",400:"Bad Request",301:"Moved Permanently",302:"Found",307:"Temporary Redirect",308:"Permanent Redirect",204:"No Content",201:"Created",200:"OK"};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 forHttpCode(t,r=""){return new PHPResponse(t,{},new TextEncoder().encode(r||responseTexts[t]||""))}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)}}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(...o){try{return i.apply(this,o)}catch(a){const l=typeof a=="object"?a==null?void 0:a.errno:null;if(l in FileErrorCodes){const c=FileErrorCodes[l],u=typeof o[0]=="string"?o[0]:null,g=u!==null?e.replaceAll("{path}",u):e;throw new Error(`${g}: ${c}`,{cause:a})}throw a}}}}const logToConsole=(e,...t)=>{switch(typeof e.message=="string"?e.message=prepareLogMessage(e.message):e.message.message&&typeof e.message.message=="string"&&(e.message.message=prepareLogMessage(e.message.message)),e.severity){case"Debug":console.debug(e.message,...t);break;case"Info":console.info(e.message,...t);break;case"Warn":console.warn(e.message,...t);break;case"Error":console.error(e.message,...t);break;case"Fatal":console.error(e.message,...t);break;default:console.log(e.message,...t)}},prepareLogMessage$1=e=>e instanceof Error?[e.message,e.stack].join(`
2
- `):JSON.stringify(e,null,2),logs=[],addToLogArray=e=>{logs.push(e)},logToMemory=e=>{if(e.raw===!0)addToLogArray(e.message);else{const t=formatLogEntry(typeof e.message=="object"?prepareLogMessage$1(e.message):e.message,e.severity??"Info",e.prefix??"JavaScript");addToLogArray(t)}};class Logger extends EventTarget{constructor(t=[]){super(),this.handlers=t,this.fatalErrorEvent="playground-fatal-error"}getLogs(){return this.handlers.includes(logToMemory)?[...logs]:(this.error(`Logs aren't stored because the logToMemory handler isn't registered.
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=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"}();if(A==="NODE"){let r=function(t){return new Promise(function(o,n){t.onload=t.onerror=function(i){t.onload=t.onerror=null,i.type==="load"?o(t.result):n(new Error("Failed to read the blob/file"))}})},e=function(){const t=new Uint8Array([1,2,3,4]),n=new File([t],"test").stream();try{return n.getReader({mode:"byob"}),!0}catch{return!1}};if(typeof File>"u"){class t extends Blob{constructor(n,i,s){super(n);let a;s!=null&&s.lastModified&&(a=new Date),(!a||isNaN(a.getFullYear()))&&(a=new Date),this.lastModifiedDate=a,this.lastModified=a.getMilliseconds(),this.name=i||""}}global.File=t}typeof Blob.prototype.arrayBuffer>"u"&&(Blob.prototype.arrayBuffer=function(){const o=new FileReader;return o.readAsArrayBuffer(this),r(o)}),typeof Blob.prototype.text>"u"&&(Blob.prototype.text=function(){const o=new FileReader;return o.readAsText(this),r(o)}),(typeof Blob.prototype.stream>"u"||!e())&&(Blob.prototype.stream=function(){let t=0;const o=this;return new ReadableStream({type:"bytes",autoAllocateChunkSize:512*1024,async pull(n){const i=n.byobRequest.view,a=await o.slice(t,t+i.byteLength).arrayBuffer(),m=new Uint8Array(a);new Uint8Array(i.buffer).set(m);const h=m.byteLength;n.byobRequest.respond(h),t+=h,t>=o.size&&n.close()}})})}if(A==="NODE"&&typeof CustomEvent>"u"){class r extends Event{constructor(t,o={}){super(t,o),this.detail=o.detail}initCustomEvent(){}}globalThis.CustomEvent=r}const E={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 x(r){const e=typeof r=="object"?r==null?void 0:r.errno:null;if(e in E)return E[e]}function u(r=""){return function(t,o,n){const i=n.value;n.value=function(...s){try{return i.apply(this,s)}catch(a){const m=typeof a=="object"?a==null?void 0:a.errno:null;if(m in E){const h=E[m],l=typeof s[1]=="string"?s[1]:null,y=l!==null?r.replaceAll("{path}",l):r;throw new Error(`${y}: ${h}`,{cause:a})}throw a}}}}const I="playground-log",R=(r,...e)=>{b.dispatchEvent(new CustomEvent(I,{detail:{log:r,args:e}}))},B=(r,...e)=>{switch(typeof r.message=="string"?r.message=w(r.message):r.message.message&&typeof r.message.message=="string"&&(r.message.message=w(r.message.message)),r.severity){case"Debug":console.debug(r.message,...e);break;case"Info":console.info(r.message,...e);break;case"Warn":console.warn(r.message,...e);break;case"Error":console.error(r.message,...e);break;case"Fatal":console.error(r.message,...e);break;default:console.log(r.message,...e)}},P=r=>r instanceof Error?[r.message,r.stack].join(`
2
+ `):JSON.stringify(r,null,2),C=[],F=r=>{C.push(r)},v=r=>{if(r.raw===!0)F(r.message);else{const e=W(typeof r.message=="object"?P(r.message):r.message,r.severity??"Info",r.prefix??"JavaScript");F(e)}};class M extends EventTarget{constructor(e=[]){super(),this.handlers=e,this.fatalErrorEvent="playground-fatal-error"}getLogs(){return this.handlers.includes(v)?[...C]:(this.error(`Logs aren't stored because the logToMemory handler isn't registered.
3
3
  If you're using a custom logger instance, make sure to register logToMemory handler.
4
- `),[])}logMessage(t,...r){for(const s of this.handlers)s(t,...r)}log(t,...r){this.logMessage({message:t,severity:void 0,prefix:"JavaScript",raw:!1},...r)}debug(t,...r){this.logMessage({message:t,severity:"Debug",prefix:"JavaScript",raw:!1},...r)}info(t,...r){this.logMessage({message:t,severity:"Info",prefix:"JavaScript",raw:!1},...r)}warn(t,...r){this.logMessage({message:t,severity:"Warn",prefix:"JavaScript",raw:!1},...r)}error(t,...r){this.logMessage({message:t,severity:"Error",prefix:"JavaScript",raw:!1},...r)}}const getDefaultHandlers=()=>{try{if(process.env.NODE_ENV==="test")return[logToMemory]}catch{}return[logToMemory,logToConsole]},logger=new Logger(getDefaultHandlers()),prepareLogMessage=e=>e.replace(/\t/g,""),formatLogEntry=(e,t,r)=>{const s=new Date,n=new Intl.DateTimeFormat("en-GB",{year:"numeric",month:"short",day:"2-digit",timeZone:"UTC"}).format(s).replace(/ /g,"-"),i=new Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZone:"UTC",timeZoneName:"short"}).format(s),o=n+" "+i;return e=prepareLogMessage(e),`[${o}] ${r} ${t}: ${e}`},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"})();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(o){if(!(o instanceof Error))throw o;const a=clarifyErrorMessage(o,(i=e.lastAsyncifyStackSource)==null?void 0:i.stack);if(e.lastAsyncifyStackSource&&(o.cause=e.lastAsyncifyStackSource),t.hasListeners()){t.dispatchEvent(new ErrorEvent("error",{error:o,message:a}));return}throw isExitCodeZero(o)||showCriticalErrorBox(a),o}}}return t}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(e,t){if(e.message==="unreachable"){let r=UNREACHABLE_ERROR;t||(r+=`
5
-
6
- This stack trace is lacking. For a better one initialize
7
- the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
8
-
9
- `),functionsMaybeMissingFromAsyncify=extractPHPFunctionsFromStack(t||e.stack||"");for(const s of functionsMaybeMissingFromAsyncify)r+=` * ${s}
10
- `;return r}return e.message}const UNREACHABLE_ERROR=`
11
- "unreachable" WASM instruction executed.
12
-
13
- The typical reason is a PHP function missing from the ASYNCIFY_ONLY
14
- list when building PHP.wasm.
15
-
16
- You will need to file a new issue in the WordPress Playground repository
17
- and paste this error message there:
18
-
19
- https://github.com/WordPress/wordpress-playground/issues/new
20
-
21
- If you're a core developer, the typical fix is to:
22
-
23
- * Isolate a minimal reproduction of the error
24
- * Add a reproduction of the error to php-asyncify.spec.ts in the WordPress Playground repository
25
- * Run 'npm run fix-asyncify'
26
- * Commit the changes, push to the repo, release updated NPM packages
27
-
28
- Below is a list of all the PHP functions found in the stack trace to
29
- help with the minimal reproduction. If they're all already listed in
30
- the Dockerfile, you'll need to trigger this error again with long stack
31
- traces enabled. In node.js, you can do it using the --stack-trace-limit=100
32
- CLI option:
33
-
34
- `,redBg="\x1B[41m",bold="\x1B[1m",reset="\x1B[0m",eol="\x1B[K";let logged=!1;function showCriticalErrorBox(e){if(!logged&&(logged=!0,!(e!=null&&e.trim().startsWith("Program terminated with exit")))){logger.log(`${redBg}
35
- ${eol}
36
- ${bold} WASM ERROR${reset}${redBg}`);for(const t of e.split(`
37
- `))logger.log(`${eol} ${t} `);logger.log(`${reset}`)}}function extractPHPFunctionsFromStack(e){try{const t=e.split(`
38
- `).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[]}}const SleepFinished=Symbol("SleepFinished");function sleep(e){return new Promise(t=>{setTimeout(()=>t(SleepFinished),e)})}class AcquireTimeoutError extends Error{constructor(){super("Acquiring lock timed out")}}class Semaphore{constructor({concurrency:t,timeout:r}){this._running=0,this.concurrency=t,this.timeout=r,this.queue=[]}get remaining(){return this.concurrency-this.running}get running(){return this._running}async acquire(){for(;;)if(this._running>=this.concurrency){const t=new Promise(r=>{this.queue.push(r)});this.timeout!==void 0?await Promise.race([t,sleep(this.timeout)]).then(r=>{if(r===SleepFinished)throw new AcquireTimeoutError}):await 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 dirname(e){if(e==="/")return"/";e=normalizePath$1(e);const t=e.lastIndexOf("/");return t===-1?"":t===0?"/":e.substr(0,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 splitShellCommand(e){let s=0,n="";const i=[];let o="";for(let a=0;a<e.length;a++){const l=e[a];l==="\\"?((e[a+1]==='"'||e[a+1]==="'")&&a++,o+=e[a]):s===0?l==='"'||l==="'"?(s=1,n=l):l.match(/\s/)?(o.trim().length&&i.push(o.trim()),o=l):i.length&&!o?o=i.pop()+l:o+=l:s===1&&(l===n?(s=0,n=""):o+=l)}return o&&i.push(o.trim()),i}function createSpawnHandler(e){return function(t,r=[],s={}){const n=new ChildProcess,i=new ProcessApi(n);return setTimeout(async()=>{let o=[];if(r.length)o=[t,...r];else if(typeof t=="string")o=splitShellCommand(t);else if(Array.isArray(t))o=t;else throw new Error("Invalid command ",t);try{await e(o,i,s)}catch(a){n.emit("error",a),typeof a=="object"&&a!==null&&"message"in a&&typeof a.message=="string"&&i.stderr(a.message),i.exit(1)}n.emit("spawn",!0)}),n}}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)}stdoutEnd(){this.childProcess.stdout.emit("end",{})}stderr(t){typeof t=="string"&&(t=new TextEncoder().encode(t)),this.childProcess.stderr.emit("data",t)}stderrEnd(){this.childProcess.stderr.emit("end",{})}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)}}}}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,o;i>=0;i--)(o=e[i])&&(n=(s?o(t,r,n):o(n))||n);return s&&n&&__defProp(t,r,n),n};const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(t,r,s){super(t),this.response=r,this.source=s}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php";var E,m,y,_,w,P,B,b,L,S,U,R,$,T,q,F,W,x,z,C,j,k,G,N,J,v,H,A,V,M,Q,I,Y;class BasePHP{constructor(e){d(this,P);d(this,b);d(this,S);d(this,R);d(this,T);d(this,F);d(this,x);d(this,C);d(this,k);d(this,N);d(this,v);d(this,A);d(this,M);d(this,I);d(this,E,void 0);d(this,m,void 0);d(this,y,void 0);d(this,_,void 0);d(this,w,void 0);p(this,m,!1),p(this,y,null),p(this,_,new Map),p(this,w,[]),this.semaphore=new Semaphore({concurrency:1}),e!==void 0&&this.initializeRuntime(e)}addEventListener(e,t){f(this,_).has(e)||f(this,_).set(e,new Set),f(this,_).get(e).add(t)}removeEventListener(e,t){var r;(r=f(this,_).get(e))==null||r.delete(t)}dispatchEvent(e){const t=f(this,_).get(e.type);if(t)for(const r of t)r(e)}async onMessage(e){f(this,w).push(e)}async setSpawnHandler(handler){typeof handler=="string"&&(handler=createSpawnHandler(eval(handler))),this[__private__dont__use].spawnProcess=handler}get absoluteUrl(){return this.requestHandler.absoluteUrl}get documentRoot(){return this.requestHandler.documentRoot}pathToInternalUrl(e){return this.requestHandler.pathToInternalUrl(e)}internalUrlToPath(e){return this.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,this[__private__dont__use].ccall("wasm_set_phpini_path",null,["string"],[PHP_INI_PATH]),this.fileExists(PHP_INI_PATH)||this.writeFile(PHP_INI_PATH,["auto_prepend_file="+AUTO_PREPEND_SCRIPT,"memory_limit=256M","ignore_repeated_errors = 1","error_reporting = E_ALL","display_errors = 1","html_errors = 1","display_startup_errors = On","log_errors = 1","always_populate_raw_post_data = -1","upload_max_filesize = 2000M","post_max_size = 2000M","disable_functions = curl_exec,curl_multi_exec","allow_url_fopen = Off","allow_url_include = Off","session.save_path = /home/web_user","implicit_flush = 1","output_buffering = 0","max_execution_time = 0","max_input_time = -1"].join(`
39
- `)),this.fileExists(AUTO_PREPEND_SCRIPT)||this.writeFile(AUTO_PREPEND_SCRIPT,`<?php
40
- // Define constants set via defineConstant() calls
41
- if(file_exists('/internal/shared/consts.json')) {
42
- $consts = json_decode(file_get_contents('/internal/shared/consts.json'), true);
43
- foreach ($consts as $const => $value) {
44
- if (!defined($const) && is_scalar($value)) {
45
- define($const, $value);
46
- }
47
- }
48
- }
49
- // Preload all the files from /internal/shared/preload
50
- foreach (glob('/internal/shared/preload/*.php') as $file) {
51
- require_once $file;
52
- }
53
- `),t.onMessage=async r=>{for(const s of f(this,w)){const n=await s(r);if(n)return n}return""},p(this,y,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?");p(this,E,e)}chdir(e){this[__private__dont__use].FS.chdir(e)}async request(e){if(logger.warn("PHP.request() is deprecated. Please use new PHPRequestHandler() instead."),!this.requestHandler)throw new Error("No request handler available.");return this.requestHandler.request(e)}async run(e){const t=await this.semaphore.acquire();let r;try{if(f(this,m)||(h(this,b,L).call(this),p(this,m,!0)),e.scriptPath&&!this.fileExists(e.scriptPath))throw new Error(`The script path "${e.scriptPath}" does not exist.`);h(this,R,$).call(this,e.relativeUri||""),h(this,C,j).call(this,e.method||"GET");const s=normalizeHeaders(e.headers||{}),n=s.host||"example.com:443",i=h(this,x,z).call(this,n,e.protocol||"http");h(this,T,q).call(this,n),h(this,F,W).call(this,i),h(this,k,G).call(this,s),e.body&&(r=h(this,N,J).call(this,e.body)),typeof e.code=="string"?(this.writeFile("/internal/eval.php",e.code),h(this,v,H).call(this,"/internal/eval.php")):h(this,v,H).call(this,e.scriptPath||"");const o=h(this,P,B).call(this,e.$_SERVER,s,i);for(const c in o)h(this,A,V).call(this,c,o[c]);const a=e.env||{};for(const c in a)h(this,M,Q).call(this,c,a[c]);const l=await h(this,I,Y).call(this);if(l.exitCode!==0){logger.warn("PHP.run() output was:",l.text);const c=new PHPExecutionFailureError(`PHP.run() failed with exit code ${l.exitCode} and the following output: `+l.errors,l,"request");throw logger.error(c),c}return l}catch(s){throw this.dispatchEvent({type:"request.error",error:s,source:s.source??"php-wasm"}),s}finally{try{r&&this[__private__dont__use].free(r)}finally{t(),this.dispatchEvent({type:"request.end"})}}}defineConstant(e,t){let r={};try{r=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...r,[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){const r=this[__private__dont__use].FS;try{const s=r.lookupPath(e).node.mount,n=this.fileExists(t)?r.lookupPath(t).node.mount:r.lookupPath(dirname(t)).node.mount;s.mountpoint!==n.mountpoint?(copyRecursive(r,e,t),this.rmdir(e,{recursive:!0})):r.rename(e,t)}catch(s){const n=getEmscriptenFsError(s);throw n?new Error(`Could not move ${e} to ${t}: ${n}`,{cause:s}):s}}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 logger.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,t){const r=this[__private__dont__use].FS;try{this.exit()}catch{}this.initializeRuntime(e),f(this,E)&&this.setSapiName(f(this,E)),t&&copyFS(r,this[__private__dont__use].FS,t)}exit(e=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(e)}catch{}p(this,m,!1),p(this,y,null),delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}[Symbol.dispose](){f(this,m)&&this.exit(0)}}E=new WeakMap,m=new WeakMap,y=new WeakMap,_=new WeakMap,w=new WeakMap,P=new WeakSet,B=function(e,t,r){const s={...e||{}};s.HTTPS=s.HTTPS||r===443?"on":"off";for(const n in t){let i="HTTP_";["content-type","content-length"].includes(n.toLowerCase())&&(i=""),s[`${i}${n.toUpperCase().replace(/-/g,"_")}`]=t[n]}return s},b=new WeakSet,L=function(){this[__private__dont__use].ccall("php_wasm_init",null,[],[])},S=new WeakSet,U=function(){const e="/internal/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(),o=s.substring(n+2);i in r||(r[i]=[]),r[i].push(o)}return{headers:r,httpStatusCode:t.status}},R=new WeakSet,$=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])}},T=new WeakSet,q=function(e){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[e])},F=new WeakSet,W=function(e){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[e])},x=new WeakSet,z=function(e,t){let r;try{r=parseInt(new URL(e).port,10)}catch{}return(!r||isNaN(r)||r===80)&&(r=t==="https"?443:80),r},C=new WeakSet,j=function(e){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[e])},k=new WeakSet,G=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)])},N=new WeakSet,J=function(e){let t,r;typeof e=="string"?(logger.warn("Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"),r=this[__private__dont__use].lengthBytesUTF8(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},v=new WeakSet,H=function(e){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[e])},A=new WeakSet,V=function(e,t){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[e,t])},M=new WeakSet,Q=function(e,t){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[e,t])},I=new WeakSet,Y=async function(){var n;let e,t;try{e=await new Promise((i,o)=>{var l;t=c=>{logger.error(c),logger.error(c.error);const u=new Error("Rethrown");u.cause=c.error,u.betterMessage=c.message,o(u)},(l=f(this,y))==null||l.addEventListener("error",t);const a=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return a instanceof Promise?a.then(i,o):i(a)})}catch(i){for(const c in this)typeof this[c]=="function"&&(this[c]=()=>{throw new Error("PHP runtime has crashed – see the earlier error for details.")});this.functionsMaybeMissingFromAsyncify=getFunctionsMaybeMissingFromAsyncify();const o=i,a="betterMessage"in o?o.betterMessage:o.message,l=new Error(a);throw l.cause=o,logger.error(l),l}finally{(n=f(this,y))==null||n.removeEventListener("error",t)}const{headers:r,httpStatusCode:s}=h(this,S,U).call(this);return new PHPResponse(e===0?s:500,r,this.readFileAsBuffer("/internal/stdout"),this.readFileAsText("/internal/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 copyFS(e,t,r){let s;try{s=e.lookupPath(r)}catch{return}if(!("contents"in s.node))return;if(!e.isDir(s.node.mode)){t.writeFile(r,e.readFile(r));return}t.mkdirTree(r);const n=e.readdir(r).filter(i=>i!=="."&&i!=="..");for(const i of n)copyFS(e,t,joinPaths(r,i))}function copyRecursive(e,t,r){const s=e.lookupPath(t).node;if(e.isDir(s.mode)){e.mkdirTree(r);const n=e.readdir(t).filter(i=>i!=="."&&i!=="..");for(const i of n)copyRecursive(e,joinPaths(t,i),joinPaths(r,i))}else e.writeFile(r,e.readFile(t))}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]);function journalFSEvents(e,t,r=()=>{}){function s(){t=normalizePath(t);const i=e[__private__dont__use].FS,o=createFSHooks(i,u=>{if(u.path.startsWith(t))r(u);else if(u.operation==="RENAME"&&u.toPath.startsWith(t))for(const g of recordExistingPath(e,u.path,u.toPath))r(g)}),a={};for(const[u]of Object.entries(o))a[u]=i[u];function l(){for(const[u,g]of Object.entries(o))i[u]=function(...D){return g(...D),a[u].apply(this,D)}}function c(){for(const[u,g]of Object.entries(a))e[__private__dont__use].FS[u]=g}e[__private__dont__use].journal={bind:l,unbind:c},l()}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],o=e[s];if(i.operation==="RENAME"&&o.operation==="RENAME"){logger.warn("[FS Journal] Normalizing a double rename is not yet supported:",{current:i,last:o});continue}(o.operation==="CREATE"||o.operation==="WRITE")&&(i.operation==="RENAME"?n==="same_node"?(t[s]=[],t[r]=[{...o,path:i.toPath},...t[r]||[]]):n==="descendant"&&(t[s]=[],t[r]=[{...o,path:joinPaths(i.toPath,o.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){logger.warn(`Journal failed to hydrate a file on flush: the path ${t.path} no longer exists`),logger.error(s)}r()}exports.hydrateUpdateFileOps=hydrateUpdateFileOps;exports.journalFSEvents=journalFSEvents;exports.normalizeFilesystemOperations=normalizeFilesystemOperations;exports.replayFSJournal=replayFSJournal;
4
+ `),[])}logMessage(e,...t){for(const o of this.handlers)o(e,...t)}log(e,...t){this.logMessage({message:e,severity:void 0,prefix:"JavaScript",raw:!1},...t)}debug(e,...t){this.logMessage({message:e,severity:"Debug",prefix:"JavaScript",raw:!1},...t)}info(e,...t){this.logMessage({message:e,severity:"Info",prefix:"JavaScript",raw:!1},...t)}warn(e,...t){this.logMessage({message:e,severity:"Warn",prefix:"JavaScript",raw:!1},...t)}error(e,...t){this.logMessage({message:e,severity:"Error",prefix:"JavaScript",raw:!1},...t)}}const S=()=>{try{if(process.env.NODE_ENV==="test")return[v,R]}catch{}return[v,B,R]},b=new M(S()),w=r=>r.replace(/\t/g,""),W=(r,e,t)=>{const o=new Date,n=new Intl.DateTimeFormat("en-GB",{year:"numeric",month:"short",day:"2-digit",timeZone:"UTC"}).format(o).replace(/ /g,"-"),i=new Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZone:"UTC",timeZoneName:"short"}).format(o),s=n+" "+i;return r=w(r),`[${s}] ${t} ${e}: ${r}`},N=Symbol("SleepFinished");function L(r){return new Promise(e=>{setTimeout(()=>e(N),r)})}class $ extends Error{constructor(){super("Acquiring lock timed out")}}class _{constructor({concurrency:e,timeout:t}){this._running=0,this.concurrency=e,this.timeout=t,this.queue=[]}get remaining(){return this.concurrency-this.running}get running(){return this._running}async acquire(){for(;;)if(this._running>=this.concurrency){const e=new Promise(t=>{this.queue.push(t)});this.timeout!==void 0?await Promise.race([e,L(this.timeout)]).then(t=>{if(t===N)throw new $}):await 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 g(...r){let e=r.join("/");const t=e[0]==="/",o=e.substring(e.length-1)==="/";return e=T(e),!e&&!t&&(e="."),e&&o&&(e+="/"),e}function q(r){if(r==="/")return"/";r=T(r);const e=r.lastIndexOf("/");return e===-1?"":e===0?"/":r.substr(0,e)}function j(r){if(r==="/")return"/";r=T(r);const e=r.lastIndexOf("/");return e===-1?r:r.substr(e+1)}function T(r){const e=r[0]==="/";return r=J(r.split("/").filter(t=>!!t),!e).join("/"),(e?"/":"")+r.replace(/\/$/,"")}function J(r,e){let t=0;for(let o=r.length-1;o>=0;o--){const n=r[o];n==="."?r.splice(o,1):n===".."?(r.splice(o,1),t++):t&&(r.splice(o,1),t--)}if(e)for(;t;t--)r.unshift("..");return r}var z=Object.defineProperty,U=Object.getOwnPropertyDescriptor,d=(r,e,t,o)=>{for(var n=o>1?void 0:o?U(e,t):e,i=r.length-1,s;i>=0;i--)(s=r[i])&&(n=(o?s(e,t,n):s(n))||n);return o&&n&&z(e,t,n),n};const f=class c{static readFileAsText(e,t){return new TextDecoder().decode(c.readFileAsBuffer(e,t))}static readFileAsBuffer(e,t){return e.readFile(t)}static writeFile(e,t,o){e.writeFile(t,o)}static unlink(e,t){e.unlink(t)}static mv(e,t,o){try{const n=e.lookupPath(t).node.mount,i=c.fileExists(e,o)?e.lookupPath(o).node.mount:e.lookupPath(q(o)).node.mount;n.mountpoint!==i.mountpoint?(c.copyRecursive(e,t,o),c.rmdir(e,t,{recursive:!0})):e.rename(t,o)}catch(n){const i=x(n);throw i?new Error(`Could not move ${t} to ${o}: ${i}`,{cause:n}):n}}static rmdir(e,t,o={recursive:!0}){o!=null&&o.recursive&&c.listFiles(e,t).forEach(n=>{const i=`${t}/${n}`;c.isDir(e,i)?c.rmdir(e,i,o):c.unlink(e,i)}),e.rmdir(t)}static listFiles(e,t,o={prependPath:!1}){if(!c.fileExists(e,t))return[];try{const n=e.readdir(t).filter(i=>i!=="."&&i!=="..");if(o.prependPath){const i=t.replace(/\/$/,"");return n.map(s=>`${i}/${s}`)}return n}catch(n){return b.error(n,{path:t}),[]}}static isDir(e,t){return c.fileExists(e,t)?e.isDir(e.lookupPath(t).node.mode):!1}static fileExists(e,t){try{return e.lookupPath(t),!0}catch{return!1}}static mkdir(e,t){e.mkdirTree(t)}static copyRecursive(e,t,o){const n=e.lookupPath(t).node;if(e.isDir(n.mode)){e.mkdirTree(o);const i=e.readdir(t).filter(s=>s!=="."&&s!=="..");for(const s of i)c.copyRecursive(e,g(t,s),g(o,s))}else e.writeFile(o,e.readFile(t))}};d([u('Could not read "{path}"')],f,"readFileAsText",1);d([u('Could not read "{path}"')],f,"readFileAsBuffer",1);d([u('Could not write to "{path}"')],f,"writeFile",1);d([u('Could not unlink "{path}"')],f,"unlink",1);d([u('Could not remove directory "{path}"')],f,"rmdir",1);d([u('Could not list files in "{path}"')],f,"listFiles",1);d([u('Could not stat "{path}"')],f,"isDir",1);d([u('Could not stat "{path}"')],f,"fileExists",1);d([u('Could not create directory "{path}"')],f,"mkdir",1);d([u('Could not copy files from "{path}"')],f,"copyRecursive",1);(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"})();const p=Symbol("__private__dont__use");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]);function G(r,e,t=()=>{}){function o(){e=K(e);const i=r[p].FS,s=H(i,l=>{if(l.path.startsWith(e))t(l);else if(l.operation==="RENAME"&&l.toPath.startsWith(e))for(const y of D(r,l.path,l.toPath))t(y)}),a={};for(const[l]of Object.entries(s))a[l]=i[l];function m(){for(const[l,y]of Object.entries(s))i[l]=function(...k){return y(...k),a[l].apply(this,k)}}function h(){for(const[l,y]of Object.entries(a))r[p].FS[l]=y}r[p].journal={bind:m,unbind:h},m()}r.addEventListener("runtime.initialized",o),r[p]&&o();function n(){r[p].journal.unbind(),delete r[p].journal}return r.addEventListener("runtime.beforedestroy",n),function(){return r.removeEventListener("runtime.initialized",o),r.removeEventListener("runtime.beforedestroy",n),r[p].journal.unbind()}}const H=(r,e=()=>{})=>({write(t){e({operation:"WRITE",path:t.path,nodeType:"file"})},truncate(t){let o;typeof t=="string"?o=r.lookupPath(t,{follow:!0}).node:o=t,e({operation:"WRITE",path:r.getPath(o),nodeType:"file"})},unlink(t){e({operation:"DELETE",path:t,nodeType:"file"})},mknod(t,o){r.isFile(o)&&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,o){try{const n=r.lookupPath(t,{follow:!0}),i=r.lookupPath(o,{parent:!0}).path;e({operation:"RENAME",nodeType:r.isDir(n.node.mode)?"directory":"file",path:n.path,toPath:g(i,j(o))})}catch{}}});function Z(r,e){r[p].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[p].journal.bind()}}function*D(r,e,t){if(r.isDir(e)){yield{operation:"CREATE",path:t,nodeType:"directory"};for(const o of r.listFiles(e))yield*D(r,g(e,o),g(t,o))}else yield{operation:"CREATE",path:t,nodeType:"file"},yield{operation:"WRITE",nodeType:"file",path:t}}function K(r){return r.replace(/\/$/,"").replace(/\/\/+/g,"/")}function O(r){const e={};for(let t=r.length-1;t>=0;t--){for(let o=t-1;o>=0;o--){const n=V(r[t],r[o]);if(n==="none")continue;const i=r[t],s=r[o];if(i.operation==="RENAME"&&s.operation==="RENAME"){b.warn("[FS Journal] Normalizing a double rename is not yet supported:",{current:i,last:s});continue}(s.operation==="CREATE"||s.operation==="WRITE")&&(i.operation==="RENAME"?n==="same_node"?(e[o]=[],e[t]=[{...s,path:i.toPath},...e[t]||[]]):n==="descendant"&&(e[o]=[],e[t]=[{...s,path:g(i.toPath,s.path.substring(i.path.length))},...e[t]||[]]):i.operation==="WRITE"&&n==="same_node"?e[o]=[]:i.operation==="DELETE"&&n==="same_node"&&(e[o]=[],e[t]=[]))}if(Object.entries(e).length>0){const o=r.flatMap((n,i)=>i in e?e[i]:[n]);return O(o)}}return r}function V(r,e){const t=r.path,o=r.operation!=="WRITE"&&r.nodeType==="directory",n=e.operation!=="WRITE"&&e.nodeType==="directory",i=e.operation==="RENAME"?e.toPath:e.path;return i===t?"same_node":n&&t.startsWith(i+"/")?"ancestor":o&&i.startsWith(t+"/")?"descendant":"none"}async function Y(r,e){const o=e.filter(n=>n.operation==="WRITE").map(n=>X(r,n));return await Promise.all(o),e}const Q=new _({concurrency:15});async function X(r,e){const t=await Q.acquire();try{e.data=await r.readFileAsBuffer(e.path)}catch(o){b.warn(`Journal failed to hydrate a file on flush: the path ${e.path} no longer exists`),b.error(o)}t()}exports.hydrateUpdateFileOps=Y;exports.journalFSEvents=G;exports.normalizeFilesystemOperations=O;exports.replayFSJournal=Z;