Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@wp-playground/wordpress

Package Overview
Dependencies
Maintainers
0
Versions
72
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@wp-playground/wordpress - npm Package Compare versions

Comparing version 0.7.20 to 0.9.1

assets/sqlite-database-integration-fd6f4063.zip

9

index.d.ts

@@ -1,2 +0,4 @@

import { BasePHP, UniversalPHP } from '../../../php-wasm/universal/src/index.ts';
import { PHP, UniversalPHP } from '../../../php-wasm/universal/src/index.ts';
export { bootWordPress } from './boot';
export { getLoadedWordPressVersion, isSupportedWordPressVersion, } from './version-detect';
export * from './rewrite-rules';

@@ -10,4 +12,3 @@ /**

*/
export declare function enablePlatformMuPlugins(php: UniversalPHP): Promise<void>;
export declare function preloadRequiredMuPlugin(php: UniversalPHP): Promise<void>;
export declare function setupPlatformLevelMuPlugins(php: UniversalPHP): Promise<void>;
/**

@@ -32,2 +33,2 @@ * Runs phpinfo() when the requested path is /phpinfo.php.

*/
export declare function unzipWordPress(php: BasePHP, wpZip: File): Promise<void>;
export declare function unzipWordPress(php: PHP, wpZip: File): Promise<void>;

@@ -1,2 +0,2 @@

function o(...e){let t=e.join("/");const i=t[0]==="/",n=t.substring(t.length-1)==="/";return t=c(t),!t&&!i&&(t="."),t&&n&&(t+="/"),t}function c(e){const t=e[0]==="/";return e=f(e.split("/").filter(i=>!!i),!t).join("/"),(t?"/":"")+e.replace(/\/$/,"")}function f(e,t){let i=0;for(let n=e.length-1;n>=0;n--){const r=e[n];r==="."?e.splice(n,1):r===".."?(e.splice(n,1),i++):i&&(e.splice(n,1),i--)}if(t)for(;i;i--)e.unshift("..");return e}function s(e){return`json_decode(base64_decode('${_(JSON.stringify(e))}'), true)`}function g(e){const t={};for(const i in e)t[i]=s(e[i]);return t}function _(e){return w(new TextEncoder().encode(e))}function w(e){const t=String.fromCodePoint(...e);return btoa(t)}const a="/tmp/file.zip",d=async(e,t,i)=>{if(t instanceof File){const r=t;t=a,await e.writeFile(t,new Uint8Array(await r.arrayBuffer()))}const n=g({zipPath:t,extractToPath:i});await e.run({code:`<?php
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:s}){this._running=0,this.concurrency=t,this.timeout=s,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(s=>{this.queue.push(s)});this.timeout!==void 0?await Promise.race([t,sleep(this.timeout)]).then(s=>{if(s===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 s=await this.acquire();try{return await t()}finally{s()}}}function joinPaths(...e){let t=e.join("/");const s=t[0]==="/",r=t.substring(t.length-1)==="/";return t=normalizePath(t),!t&&!s&&(t="."),t&&r&&(t+="/"),t}function dirname(e){if(e==="/")return"/";e=normalizePath(e);const t=e.lastIndexOf("/");return t===-1?"":t===0?"/":e.substr(0,t)}function normalizePath(e){const t=e[0]==="/";return e=normalizePathsArray(e.split("/").filter(s=>!!s),!t).join("/"),(t?"/":"")+e.replace(/\/$/,"")}function normalizePathsArray(e,t){let s=0;for(let r=e.length-1;r>=0;r--){const n=e[r];n==="."?e.splice(r,1):n===".."?(e.splice(r,1),s++):s&&(e.splice(r,1),s--)}if(t)for(;s;s--)e.unshift("..");return e}function splitShellCommand(e){let r=0,n="";const i=[];let o="";for(let a=0;a<e.length;a++){const c=e[a];c==="\\"?((e[a+1]==='"'||e[a+1]==="'")&&a++,o+=e[a]):r===0?c==='"'||c==="'"?(r=1,n=c):c.match(/\s/)?(o.trim().length&&i.push(o.trim()),o=c):i.length&&!o?o=i.pop()+c:o+=c:r===1&&(c===n?(r=0,n=""):o+=c)}return o&&i.push(o.trim()),i}function createSpawnHandler(e){return function(t,s=[],r={}){const n=new ChildProcess,i=new ProcessApi(n);return setTimeout(async()=>{let o=[];if(s.length)o=[t,...s];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,r)}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,s){this.listeners[t]&&this.listeners[t].forEach(function(r){r(s)})}on(t,s){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(s)}}class ProcessApi extends EventEmitter{constructor(t){super(),this.childProcess=t,this.exited=!1,this.stdinData=[],t.on("stdin",s=>{this.stdinData?this.stdinData.push(s.slice()):this.emit("stdin",s)})}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 s=this;this.stdin={write:r=>{s.emit("stdin",r)}}}}function phpVar(e){return`json_decode(base64_decode('${stringToBase64(JSON.stringify(e))}'), true)`}function phpVars(e){const t={};for(const s in e)t[s]=phpVar(e[s]);return t}function stringToBase64(e){return bytesToBase64(new TextEncoder().encode(e))}function bytesToBase64(e){const t=String.fromCodePoint(...e);return btoa(t)}const tmpPath="/tmp/file.zip",unzipFile=async(e,t,s)=>{if(t instanceof File){const n=t;t=tmpPath,await e.writeFile(t,new Uint8Array(await n.arrayBuffer()))}const r=phpVars({zipPath:t,extractToPath:s});await e.run({code:`<?php
function unzip($zipPath, $extractTo, $overwrite = true)

@@ -17,4 +17,70 @@ {

}
unzip(${n.zipPath}, ${n.extractToPath});
`}),await e.fileExists(a)&&await e.unlink(a)},m=[{match:/^\/(.*?)(\/wp-(content|admin|includes)\/.*)/g,replacement:"$2"}];async function $(e){await e.mkdir("/internal/shared/mu-plugins"),await e.writeFile("/internal/shared/preload/env.php",`<?php
unzip(${r.zipPath}, ${r.extractToPath});
`}),await e.fileExists(tmpPath)&&await e.unlink(tmpPath)},currentJsRuntime=function(){return typeof process<"u"&&process.release?.name==="node"?"NODE":typeof window<"u"?"WEB":typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?"WORKER":"NODE"}();if(currentJsRuntime==="NODE"){let e=function(s){return new Promise(function(r,n){s.onload=s.onerror=function(i){s.onload=s.onerror=null,i.type==="load"?r(s.result):n(new Error("Failed to read the blob/file"))}})},t=function(){const s=new Uint8Array([1,2,3,4]),n=new File([s],"test").stream();try{return n.getReader({mode:"byob"}),!0}catch{return!1}};if(typeof File>"u"){class s extends Blob{constructor(n,i,o){super(n);let a;o?.lastModified&&(a=new Date),(!a||isNaN(a.getFullYear()))&&(a=new Date),this.lastModifiedDate=a,this.lastModified=a.getMilliseconds(),this.name=i||""}}global.File=s}typeof Blob.prototype.arrayBuffer>"u"&&(Blob.prototype.arrayBuffer=function(){const r=new FileReader;return r.readAsArrayBuffer(this),e(r)}),typeof Blob.prototype.text>"u"&&(Blob.prototype.text=function(){const r=new FileReader;return r.readAsText(this),e(r)}),(typeof Blob.prototype.stream>"u"||!t())&&(Blob.prototype.stream=function(){let s=0;const r=this;return new ReadableStream({type:"bytes",autoAllocateChunkSize:512*1024,async pull(n){const i=n.byobRequest.view,a=await r.slice(s,s+i.byteLength).arrayBuffer(),c=new Uint8Array(a);new Uint8Array(i.buffer).set(c);const l=c.byteLength;n.byobRequest.respond(l),s+=l,s>=r.size&&n.close()}})})}if(currentJsRuntime==="NODE"&&typeof CustomEvent>"u"){class e extends Event{constructor(s,r={}){super(s,r),this.detail=r.detail}initCustomEvent(){}}globalThis.CustomEvent=e}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?.errno:null;if(t in FileErrorCodes)return FileErrorCodes[t]}function rethrowFileSystemError(e=""){return function(s,r,n){const i=n.value;n.value=function(...o){try{return i.apply(this,o)}catch(a){const c=typeof a=="object"?a?.errno:null;if(c in FileErrorCodes){const l=FileErrorCodes[c],d=typeof o[1]=="string"?o[1]:null,p=d!==null?e.replaceAll("{path}",d):e;throw new Error(`${p}: ${l}`,{cause:a})}throw a}}}}const logEventType="playground-log",logEvent=(e,...t)=>{logger.dispatchEvent(new CustomEvent(logEventType,{detail:{log:e,args:t}}))},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(`
`):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.
If you're using a custom logger instance, make sure to register logToMemory handler.
`),[])}logMessage(t,...s){for(const r of this.handlers)r(t,...s)}log(t,...s){this.logMessage({message:t,severity:void 0,prefix:"JavaScript",raw:!1},...s)}debug(t,...s){this.logMessage({message:t,severity:"Debug",prefix:"JavaScript",raw:!1},...s)}info(t,...s){this.logMessage({message:t,severity:"Info",prefix:"JavaScript",raw:!1},...s)}warn(t,...s){this.logMessage({message:t,severity:"Warn",prefix:"JavaScript",raw:!1},...s)}error(t,...s){this.logMessage({message:t,severity:"Error",prefix:"JavaScript",raw:!1},...s)}}const getDefaultHandlers=()=>{try{if(process.env.NODE_ENV==="test")return[logToMemory,logEvent]}catch{}return[logToMemory,logToConsole,logEvent]},logger=new Logger(getDefaultHandlers()),prepareLogMessage=e=>e.replace(/\t/g,""),formatLogEntry=(e,t,s)=>{const r=new Date,n=new Intl.DateTimeFormat("en-GB",{year:"numeric",month:"short",day:"2-digit",timeZone:"UTC"}).format(r).replace(/ /g,"-"),i=new Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZone:"UTC",timeZoneName:"short"}).format(r),o=n+" "+i;return e=prepareLogMessage(e),`[${o}] ${s} ${t}: ${e}`};var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(e,t,s,r)=>{for(var n=r>1?void 0:r?__getOwnPropDesc(t,s):t,i=e.length-1,o;i>=0;i--)(o=e[i])&&(n=(r?o(t,s,n):o(n))||n);return r&&n&&__defProp(t,s,n),n};const _FSHelpers=class h{static readFileAsText(t,s){return new TextDecoder().decode(h.readFileAsBuffer(t,s))}static readFileAsBuffer(t,s){return t.readFile(s)}static writeFile(t,s,r){t.writeFile(s,r)}static unlink(t,s){t.unlink(s)}static mv(t,s,r){try{const n=t.lookupPath(s).node.mount,i=h.fileExists(t,r)?t.lookupPath(r).node.mount:t.lookupPath(dirname(r)).node.mount;n.mountpoint!==i.mountpoint?(h.copyRecursive(t,s,r),h.rmdir(t,s,{recursive:!0})):t.rename(s,r)}catch(n){const i=getEmscriptenFsError(n);throw i?new Error(`Could not move ${s} to ${r}: ${i}`,{cause:n}):n}}static rmdir(t,s,r={recursive:!0}){r?.recursive&&h.listFiles(t,s).forEach(n=>{const i=`${s}/${n}`;h.isDir(t,i)?h.rmdir(t,i,r):h.unlink(t,i)}),t.rmdir(s)}static listFiles(t,s,r={prependPath:!1}){if(!h.fileExists(t,s))return[];try{const n=t.readdir(s).filter(i=>i!=="."&&i!=="..");if(r.prependPath){const i=s.replace(/\/$/,"");return n.map(o=>`${i}/${o}`)}return n}catch(n){return logger.error(n,{path:s}),[]}}static isDir(t,s){return h.fileExists(t,s)?t.isDir(t.lookupPath(s).node.mode):!1}static fileExists(t,s){try{return t.lookupPath(s),!0}catch{return!1}}static mkdir(t,s){t.mkdirTree(s)}static copyRecursive(t,s,r){const n=t.lookupPath(s).node;if(t.isDir(n.mode)){t.mkdirTree(r);const i=t.readdir(s).filter(o=>o!=="."&&o!=="..");for(const o of i)h.copyRecursive(t,joinPaths(s,o),joinPaths(r,o))}else t.writeFile(r,t.readFile(s))}};__decorateClass([rethrowFileSystemError('Could not read "{path}"')],_FSHelpers,"readFileAsText",1);__decorateClass([rethrowFileSystemError('Could not read "{path}"')],_FSHelpers,"readFileAsBuffer",1);__decorateClass([rethrowFileSystemError('Could not write to "{path}"')],_FSHelpers,"writeFile",1);__decorateClass([rethrowFileSystemError('Could not unlink "{path}"')],_FSHelpers,"unlink",1);__decorateClass([rethrowFileSystemError('Could not remove directory "{path}"')],_FSHelpers,"rmdir",1);__decorateClass([rethrowFileSystemError('Could not list files in "{path}"')],_FSHelpers,"listFiles",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],_FSHelpers,"isDir",1);__decorateClass([rethrowFileSystemError('Could not stat "{path}"')],_FSHelpers,"fileExists",1);__decorateClass([rethrowFileSystemError('Could not create directory "{path}"')],_FSHelpers,"mkdir",1);__decorateClass([rethrowFileSystemError('Could not copy files from "{path}"')],_FSHelpers,"copyRecursive",1);let FSHelpers=_FSHelpers;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,s,r,n="",i=0){this.httpStatusCode=t,this.headers=s,this.bytes=r,this.exitCode=i,this.errors=n}static forHttpCode(t,s=""){return new PHPResponse(t,{},new TextEncoder().encode(s||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 loadedRuntimes=new Map;function getLoadedRuntime(e){return loadedRuntimes.get(e)}(function(){return typeof process<"u"&&process.release?.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,s={}){super(t),this[kError]=s.error===void 0?null:s.error,this[kMessage]=s.message===void 0?"":s.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?.exitCode===0||e?.name==="ExitStatus"&&"status"in e&&e.status===0:!1}class UnhandledRejectionsTarget extends EventTarget{constructor(){super(...arguments),this.listenersCount=0}addEventListener(t,s){++this.listenersCount,super.addEventListener(t,s)}removeEventListener(t,s){--this.listenersCount,super.removeEventListener(t,s)}hasListeners(){return this.listenersCount>0}}function improveWASMErrorReporting(e){const t=new UnhandledRejectionsTarget;for(const s in e.wasmExports)if(typeof e.wasmExports[s]=="function"){const r=e.wasmExports[s];e.wasmExports[s]=function(...n){try{return r(...n)}catch(i){if(!(i instanceof Error))throw i;const o=clarifyErrorMessage(i,e.lastAsyncifyStackSource?.stack);if(e.lastAsyncifyStackSource&&(i.cause=e.lastAsyncifyStackSource),t.hasListeners()){t.dispatchEvent(new ErrorEvent("error",{error:i,message:o}));return}throw isExitCodeZero(i)||showCriticalErrorBox(o),i}}}return t}let functionsMaybeMissingFromAsyncify=[];function getFunctionsMaybeMissingFromAsyncify(){return functionsMaybeMissingFromAsyncify}function clarifyErrorMessage(e,t){if(e.message==="unreachable"){let s=UNREACHABLE_ERROR;t||(s+=`
This stack trace is lacking. For a better one initialize
the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
`),functionsMaybeMissingFromAsyncify=extractPHPFunctionsFromStack(t||e.stack||"");for(const r of functionsMaybeMissingFromAsyncify)s+=` * ${r}
`;return s}return e.message}const UNREACHABLE_ERROR=`
"unreachable" WASM instruction executed.
The typical reason is a PHP function missing from the ASYNCIFY_ONLY
list when building PHP.wasm.
You will need to file a new issue in the WordPress Playground repository
and paste this error message there:
https://github.com/WordPress/wordpress-playground/issues/new
If you're a core developer, the typical fix is to:
* Isolate a minimal reproduction of the error
* Add a reproduction of the error to php-asyncify.spec.ts in the WordPress Playground repository
* Run 'npm run fix-asyncify'
* Commit the changes, push to the repo, release updated NPM packages
Below is a list of all the PHP functions found in the stack trace to
help with the minimal reproduction. If they're all already listed in
the Dockerfile, you'll need to trigger this error again with long stack
traces enabled. In node.js, you can do it using the --stack-trace-limit=100
CLI option:
`,redBg="\x1B[41m",bold="\x1B[1m",reset="\x1B[0m",eol="\x1B[K";let logged=!1;function showCriticalErrorBox(e){if(!logged&&(logged=!0,!e?.trim().startsWith("Program terminated with exit"))){logger.log(`${redBg}
${eol}
${bold} WASM ERROR${reset}${redBg}`);for(const t of e.split(`
`))logger.log(`${eol} ${t} `);logger.log(`${reset}`)}}function extractPHPFunctionsFromStack(e){try{const t=e.split(`
`).slice(1).map(s=>{const r=s.trim().substring(3).split(" ");return{fn:r.length>=2?r[0]:"<unknown>",isWasm:s.includes("wasm://")}}).filter(({fn:s,isWasm:r})=>r&&!s.startsWith("dynCall_")&&!s.startsWith("invoke_")).map(({fn:s})=>s);return Array.from(new Set(t))}catch{return[]}}const STRING="string",NUMBER="number",__private__dont__use=Symbol("__private__dont__use");class PHPExecutionFailureError extends Error{constructor(t,s,r){super(t),this.response=s,this.source=r}}const PHP_INI_PATH="/internal/shared/php.ini",AUTO_PREPEND_SCRIPT="/internal/shared/auto_prepend_file.php";class PHP{constructor(e){this.#webSapiInitialized=!1,this.#wasmErrorsTarget=null,this.#eventListeners=new Map,this.#messageListeners=[],this.semaphore=new Semaphore({concurrency:1}),e!==void 0&&this.initializeRuntime(e)}#sapiName;#webSapiInitialized;#wasmErrorsTarget;#eventListeners;#messageListeners;addEventListener(e,t){this.#eventListeners.has(e)||this.#eventListeners.set(e,new Set),this.#eventListeners.get(e).add(t)}removeEventListener(e,t){this.#eventListeners.get(e)?.delete(t)}dispatchEvent(e){const t=this.#eventListeners.get(e.type);if(t)for(const s of t)s(e)}onMessage(e){this.#messageListeners.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(`
`)),this.fileExists(AUTO_PREPEND_SCRIPT)||this.writeFile(AUTO_PREPEND_SCRIPT,`<?php
// Define constants set via defineConstant() calls
if(file_exists('/internal/shared/consts.json')) {
$consts = json_decode(file_get_contents('/internal/shared/consts.json'), true);
foreach ($consts as $const => $value) {
if (!defined($const) && is_scalar($value)) {
define($const, $value);
}
}
}
// Preload all the files from /internal/shared/preload
foreach (glob('/internal/shared/preload/*.php') as $file) {
require_once $file;
}
`),t.onMessage=async s=>{for(const r of this.#messageListeners){const n=await r(s);if(n)return n}return""},this.#wasmErrorsTarget=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?");this.#sapiName=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 s;try{if(this.#webSapiInitialized||(this.#initWebRuntime(),this.#webSapiInitialized=!0),e.scriptPath&&!this.fileExists(e.scriptPath))throw new Error(`The script path "${e.scriptPath}" does not exist.`);this.#setRelativeRequestUri(e.relativeUri||""),this.#setRequestMethod(e.method||"GET");const r=normalizeHeaders(e.headers||{}),n=r.host||"example.com:443",i=this.#inferPortFromHostAndProtocol(n,e.protocol||"http");this.#setRequestHost(n),this.#setRequestPort(i),this.#setRequestHeaders(r),e.body&&(s=this.#setRequestBody(e.body)),typeof e.code=="string"?(this.writeFile("/internal/eval.php",e.code),this.#setScriptPath("/internal/eval.php")):this.#setScriptPath(e.scriptPath||"");const o=this.#prepareServerEntries(e.$_SERVER,r,i);for(const l in o)this.#setServerGlobalEntry(l,o[l]);const a=e.env||{};for(const l in a)this.#setEnv(l,a[l]);const c=await this.#handleRequest();if(c.exitCode!==0){logger.warn("PHP.run() output was:",c.text);const l=new PHPExecutionFailureError(`PHP.run() failed with exit code ${c.exitCode} and the following output: `+c.errors,c,"request");throw logger.error(l),l}return c}catch(r){throw this.dispatchEvent({type:"request.error",error:r,source:r.source??"php-wasm"}),r}finally{try{s&&this[__private__dont__use].free(s)}finally{t(),this.dispatchEvent({type:"request.end"})}}}#prepareServerEntries(e,t,s){const r={...e||{}};r.HTTPS=r.HTTPS||s===443?"on":"off";for(const n in t){let i="HTTP_";["content-type","content-length"].includes(n.toLowerCase())&&(i=""),r[`${i}${n.toUpperCase().replace(/-/g,"_")}`]=t[n]}return r}#initWebRuntime(){this[__private__dont__use].ccall("php_wasm_init",null,[],[])}#getResponseHeaders(){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)),s={};for(const r of t.headers){if(!r.includes(": "))continue;const n=r.indexOf(": "),i=r.substring(0,n).toLowerCase(),o=r.substring(n+2);i in s||(s[i]=[]),s[i].push(o)}return{headers:s,httpStatusCode:t.status}}#setRelativeRequestUri(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])}}#setRequestHost(e){this[__private__dont__use].ccall("wasm_set_request_host",null,[STRING],[e])}#setRequestPort(e){this[__private__dont__use].ccall("wasm_set_request_port",null,[NUMBER],[e])}#inferPortFromHostAndProtocol(e,t){let s;try{s=parseInt(new URL(e).port,10)}catch{}return(!s||isNaN(s)||s===80)&&(s=t==="https"?443:80),s}#setRequestMethod(e){this[__private__dont__use].ccall("wasm_set_request_method",null,[STRING],[e])}#setRequestHeaders(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)])}#setRequestBody(e){let t,s;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"),s=this[__private__dont__use].lengthBytesUTF8(e),t=s+1):(s=e.byteLength,t=e.byteLength);const r=this[__private__dont__use].malloc(t);if(!r)throw new Error("Could not allocate memory for the request body.");return typeof e=="string"?this[__private__dont__use].stringToUTF8(e,r,t+1):this[__private__dont__use].HEAPU8.set(e,r),this[__private__dont__use].ccall("wasm_set_request_body",null,[NUMBER],[r]),this[__private__dont__use].ccall("wasm_set_content_length",null,[NUMBER],[s]),r}#setScriptPath(e){this[__private__dont__use].ccall("wasm_set_path_translated",null,[STRING],[e])}#setServerGlobalEntry(e,t){this[__private__dont__use].ccall("wasm_add_SERVER_entry",null,[STRING,STRING],[e,t])}#setEnv(e,t){this[__private__dont__use].ccall("wasm_add_ENV_entry",null,[STRING,STRING],[e,t])}defineConstant(e,t){let s={};try{s=JSON.parse(this.fileExists("/internal/shared/consts.json")&&this.readFileAsText("/internal/shared/consts.json")||"{}")}catch{}this.writeFile("/internal/shared/consts.json",JSON.stringify({...s,[e]:t}))}async#handleRequest(){let e,t;try{e=await new Promise((n,i)=>{t=a=>{logger.error(a),logger.error(a.error);const c=new Error("Rethrown");c.cause=a.error,c.betterMessage=a.message,i(c)},this.#wasmErrorsTarget?.addEventListener("error",t);const o=this[__private__dont__use].ccall("wasm_sapi_handle_request",NUMBER,[],[],{async:!0});return o instanceof Promise?o.then(n,i):n(o)})}catch(n){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 i=n,o="betterMessage"in i?i.betterMessage:i.message,a=new Error(o);throw a.cause=i,logger.error(a),a}finally{this.#wasmErrorsTarget?.removeEventListener("error",t)}const{headers:s,httpStatusCode:r}=this.#getResponseHeaders();return new PHPResponse(e===0?r:500,s,this.readFileAsBuffer("/internal/stdout"),this.readFileAsText("/internal/stderr"),e)}mkdir(e){return FSHelpers.mkdir(this[__private__dont__use].FS,e)}mkdirTree(e){return FSHelpers.mkdir(this[__private__dont__use].FS,e)}readFileAsText(e){return FSHelpers.readFileAsText(this[__private__dont__use].FS,e)}readFileAsBuffer(e){return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS,e)}writeFile(e,t){return FSHelpers.writeFile(this[__private__dont__use].FS,e,t)}unlink(e){return FSHelpers.unlink(this[__private__dont__use].FS,e)}mv(e,t){return FSHelpers.mv(this[__private__dont__use].FS,e,t)}rmdir(e,t={recursive:!0}){return FSHelpers.rmdir(this[__private__dont__use].FS,e,t)}listFiles(e,t={prependPath:!1}){return FSHelpers.listFiles(this[__private__dont__use].FS,e,t)}isDir(e){return FSHelpers.isDir(this[__private__dont__use].FS,e)}fileExists(e){return FSHelpers.fileExists(this[__private__dont__use].FS,e)}hotSwapPHPRuntime(e,t){const s=this[__private__dont__use].FS;try{this.exit()}catch{}this.initializeRuntime(e),this.#sapiName&&this.setSapiName(this.#sapiName),t&&copyFS(s,this[__private__dont__use].FS,t)}async mount(e,t){return await t(this,this[__private__dont__use].FS,e)}async cli(e){for(const t of e)this[__private__dont__use].ccall("wasm_add_cli_arg",null,[STRING],[t]);try{return await this[__private__dont__use].ccall("run_cli",null,[],[],{async:!0})}catch(t){if(isExitCodeZero(t))return 0;throw t}}setSkipShebang(e){this[__private__dont__use].ccall("wasm_set_skip_shebang",null,[NUMBER],[e?1:0])}exit(e=0){this.dispatchEvent({type:"runtime.beforedestroy"});try{this[__private__dont__use]._exit(e)}catch{}this.#webSapiInitialized=!1,this.#wasmErrorsTarget=null,delete this[__private__dont__use].onMessage,delete this[__private__dont__use]}[Symbol.dispose](){this.#webSapiInitialized&&this.exit(0)}}function normalizeHeaders(e){const t={};for(const s in e)t[s.toLowerCase()]=e[s];return t}function copyFS(e,t,s){let r;try{r=e.lookupPath(s)}catch{return}if(!("contents"in r.node))return;if(!e.isDir(r.node.mode)){t.writeFile(s,e.readFile(s));return}t.mkdirTree(s);const n=e.readdir(s).filter(i=>i!=="."&&i!=="..");for(const i of n)copyFS(e,t,joinPaths(s,i))}const{hasOwnProperty}=Object.prototype,encode=(e,t={})=>{typeof t=="string"&&(t={section:t}),t.align=t.align===!0,t.newline=t.newline===!0,t.sort=t.sort===!0,t.whitespace=t.whitespace===!0||t.align===!0,t.platform=t.platform||typeof process<"u"&&process.platform,t.bracketedArray=t.bracketedArray!==!1;const s=t.platform==="win32"?`\r
`:`
`,r=t.whitespace?" = ":"=",n=[],i=t.sort?Object.keys(e).sort():Object.keys(e);let o=0;t.align&&(o=safe(i.filter(l=>e[l]===null||Array.isArray(e[l])||typeof e[l]!="object").map(l=>Array.isArray(e[l])?`${l}[]`:l).concat([""]).reduce((l,d)=>safe(l).length>=safe(d).length?l:d)).length);let a="";const c=t.bracketedArray?"[]":"";for(const l of i){const d=e[l];if(d&&Array.isArray(d))for(const p of d)a+=safe(`${l}${c}`).padEnd(o," ")+r+safe(p)+s;else d&&typeof d=="object"?n.push(l):a+=safe(l).padEnd(o," ")+r+safe(d)+s}t.section&&a.length&&(a="["+safe(t.section)+"]"+(t.newline?s+s:s)+a);for(const l of n){const d=splitSections(l,".").join("\\."),p=(t.section?t.section+".":"")+d,f=encode(e[l],{...t,section:p});a.length&&f.length&&(a+=s),a+=f}return a};function splitSections(e,t){var s=0,r=0,n=0,i=[];do if(n=e.indexOf(t,s),n!==-1){if(s=n+t.length,n>0&&e[n-1]==="\\")continue;i.push(e.slice(r,n)),r=n+t.length}while(n!==-1);return i.push(e.slice(r)),i}const decode=(e,t={})=>{t.bracketedArray=t.bracketedArray!==!1;const s=Object.create(null);let r=s,n=null;const i=/^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i,o=e.split(/[\r\n]+/g),a={};for(const l of o){if(!l||l.match(/^\s*[;#]/)||l.match(/^\s*$/))continue;const d=l.match(i);if(!d)continue;if(d[1]!==void 0){if(n=unsafe(d[1]),n==="__proto__"){r=Object.create(null);continue}r=s[n]=s[n]||Object.create(null);continue}const p=unsafe(d[2]);let f;t.bracketedArray?f=p.length>2&&p.slice(-2)==="[]":(a[p]=(a?.[p]||0)+1,f=a[p]>1);const u=f?p.slice(0,-2):p;if(u==="__proto__")continue;const m=d[3]?unsafe(d[4]):!0,_=m==="true"||m==="false"||m==="null"?JSON.parse(m):m;f&&(hasOwnProperty.call(r,u)?Array.isArray(r[u])||(r[u]=[r[u]]):r[u]=[]),Array.isArray(r[u])?r[u].push(_):r[u]=_}const c=[];for(const l of Object.keys(s)){if(!hasOwnProperty.call(s,l)||typeof s[l]!="object"||Array.isArray(s[l]))continue;const d=splitSections(l,".");r=s;const p=d.pop(),f=p.replace(/\\\./g,".");for(const u of d)u!=="__proto__"&&((!hasOwnProperty.call(r,u)||typeof r[u]!="object")&&(r[u]=Object.create(null)),r=r[u]);r===s&&f===p||(r[f]=s[l],c.push(l))}for(const l of c)delete s[l];return s},isQuoted=e=>e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"),safe=e=>typeof e!="string"||e.match(/[=\r\n]/)||e.match(/^\[/)||e.length>1&&isQuoted(e)||e!==e.trim()?JSON.stringify(e):e.split(";").join("\\;").split("#").join("\\#"),unsafe=e=>{if(e=(e||"").trim(),isQuoted(e)){e.charAt(0)==="'"&&(e=e.slice(1,-1));try{e=JSON.parse(e)}catch{}}else{let t=!1,s="";for(let r=0,n=e.length;r<n;r++){const i=e.charAt(r);if(t)"\\;#".indexOf(i)!==-1?s+=i:s+="\\"+i,t=!1;else{if(";#".indexOf(i)!==-1)break;i==="\\"?t=!0:s+=i}}return t&&(s+="\\"),s.trim()}return e};var ini={parse:decode,decode,stringify:encode,encode,safe,unsafe};async function setPhpIniEntries(e,t){const s=ini.parse(await e.readFileAsText(PHP_INI_PATH));for(const[r,n]of Object.entries(t))n==null?delete s[r]:s[r]=n;await e.writeFile(PHP_INI_PATH,ini.stringify(s))}async function withPHPIniValues(e,t,s){const r=await e.readFileAsText(PHP_INI_PATH);try{return await setPhpIniEntries(e,t),await s()}finally{await e.writeFile(PHP_INI_PATH,r)}}class HttpCookieStore{constructor(){this.cookies={}}rememberCookiesFromResponseHeaders(t){if(t?.["set-cookie"])for(const s of t["set-cookie"])try{if(!s.includes("="))continue;const r=s.indexOf("="),n=s.substring(0,r),i=s.substring(r+1).split(";")[0];this.cookies[n]=i}catch(r){logger.error(r)}}getCookieRequestHeader(){const t=[];for(const s in this.cookies)t.push(`${s}=${this.cookies[s]}`);return t.join("; ")}}ReadableStream.prototype[Symbol.asyncIterator]||(ReadableStream.prototype[Symbol.asyncIterator]=async function*(){const e=this.getReader();try{for(;;){const{done:t,value:s}=await e.read();if(t)return;yield s}}finally{e.releaseLock()}},ReadableStream.prototype.iterate=ReadableStream.prototype[Symbol.asyncIterator]);class MaxPhpInstancesError extends Error{constructor(t){super(`Requested more concurrent PHP instances than the limit (${t}).`),this.name=this.constructor.name}}class PHPProcessManager{constructor(t){this.primaryIdle=!0,this.nextInstance=null,this.allInstances=[],this.maxPhpInstances=t?.maxPhpInstances??5,this.phpFactory=t?.phpFactory,this.primaryPhp=t?.primaryPhp,this.semaphore=new Semaphore({concurrency:this.maxPhpInstances,timeout:t?.timeout||5e3})}async getPrimaryPhp(){if(!this.phpFactory&&!this.primaryPhp)throw new Error("phpFactory or primaryPhp must be set before calling getPrimaryPhp().");if(!this.primaryPhp){const t=await this.spawn({isPrimary:!0});this.primaryPhp=t.php}return this.primaryPhp}async acquirePHPInstance(){if(this.primaryIdle)return this.primaryIdle=!1,{php:await this.getPrimaryPhp(),reap:()=>this.primaryIdle=!0};const t=this.nextInstance||this.spawn({isPrimary:!1});return this.semaphore.remaining>0?this.nextInstance=this.spawn({isPrimary:!1}):this.nextInstance=null,await t}spawn(t){if(t.isPrimary&&this.allInstances.length>0)throw new Error("Requested spawning a primary PHP instance when another primary instance already started spawning.");const s=this.doSpawn(t);this.allInstances.push(s);const r=()=>{this.allInstances=this.allInstances.filter(n=>n!==s)};return s.catch(n=>{throw r(),n}).then(n=>({...n,reap:()=>{r(),n.reap()}}))}async doSpawn(t){let s;try{s=await this.semaphore.acquire()}catch(r){throw r instanceof AcquireTimeoutError?new MaxPhpInstancesError(this.maxPhpInstances):r}try{const r=await this.phpFactory(t);return{php:r,reap(){r.exit(),s()}}}catch(r){throw s(),r}}async[Symbol.asyncDispose](){this.primaryPhp&&this.primaryPhp.exit(),await Promise.all(this.allInstances.map(t=>t.then(({reap:s})=>s())))}}const DEFAULT_BASE_URL="http://example.com";function toRelativeUrl(e){return e.toString().substring(e.origin.length)}function removePathPrefix(e,t){return!t||!e.startsWith(t)?e:e.substring(t.length)}function ensurePathPrefix(e,t){return!t||e.startsWith(t)?e:t+e}async function encodeAsMultipart(e){const t=`----${Math.random().toString(36).slice(2)}`,s=`multipart/form-data; boundary=${t}`,r=new TextEncoder,n=[];for(const[c,l]of Object.entries(e))n.push(`--${t}\r
`),n.push(`Content-Disposition: form-data; name="${c}"`),l instanceof File&&n.push(`; filename="${l.name}"`),n.push(`\r
`),l instanceof File&&(n.push("Content-Type: application/octet-stream"),n.push(`\r
`)),n.push(`\r
`),l instanceof File?n.push(await fileToUint8Array(l)):n.push(l),n.push(`\r
`);n.push(`--${t}--\r
`);const i=n.reduce((c,l)=>c+l.length,0),o=new Uint8Array(i);let a=0;for(const c of n)o.set(typeof c=="string"?r.encode(c):c,a),a+=c.length;return{bytes:o,contentType:s}}function fileToUint8Array(e){return new Promise(t=>{const s=new FileReader;s.onload=()=>{t(new Uint8Array(s.result))},s.readAsArrayBuffer(e)})}const _default="application/octet-stream",asx="video/x-ms-asf",atom="application/atom+xml",avi="video/x-msvideo",avif="image/avif",bin="application/octet-stream",bmp="image/x-ms-bmp",cco="application/x-cocoa",css="text/css",data="application/octet-stream",deb="application/octet-stream",der="application/x-x509-ca-cert",dmg="application/octet-stream",doc="application/msword",docx="application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot="application/vnd.ms-fontobject",flv="video/x-flv",gif="image/gif",gz="application/gzip",hqx="application/mac-binhex40",htc="text/x-component",html="text/html",ico="image/x-icon",iso="application/octet-stream",jad="text/vnd.sun.j2me.app-descriptor",jar="application/java-archive",jardiff="application/x-java-archive-diff",jng="image/x-jng",jnlp="application/x-java-jnlp-file",jpg="image/jpeg",jpeg="image/jpeg",js="application/javascript",json="application/json",kml="application/vnd.google-earth.kml+xml",kmz="application/vnd.google-earth.kmz",m3u8="application/vnd.apple.mpegurl",m4a="audio/x-m4a",m4v="video/x-m4v",md="text/plain",mid="audio/midi",mml="text/mathml",mng="video/x-mng",mov="video/quicktime",mp3="audio/mpeg",mp4="video/mp4",mpeg="video/mpeg",msi="application/octet-stream",odg="application/vnd.oasis.opendocument.graphics",odp="application/vnd.oasis.opendocument.presentation",ods="application/vnd.oasis.opendocument.spreadsheet",odt="application/vnd.oasis.opendocument.text",ogg="audio/ogg",otf="font/otf",pdf="application/pdf",pl="application/x-perl",png="image/png",ppt="application/vnd.ms-powerpoint",pptx="application/vnd.openxmlformats-officedocument.presentationml.presentation",prc="application/x-pilot",ps="application/postscript",ra="audio/x-realaudio",rar="application/x-rar-compressed",rpm="application/x-redhat-package-manager",rss="application/rss+xml",rtf="application/rtf",run="application/x-makeself",sea="application/x-sea",sit="application/x-stuffit",svg="image/svg+xml",swf="application/x-shockwave-flash",tcl="application/x-tcl",tar="application/x-tar",tif="image/tiff",ts="video/mp2t",ttf="font/ttf",txt="text/plain",wasm="application/wasm",wbmp="image/vnd.wap.wbmp",webm="video/webm",webp="image/webp",wml="text/vnd.wap.wml",wmlc="application/vnd.wap.wmlc",wmv="video/x-ms-wmv",woff="font/woff",woff2="font/woff2",xhtml="application/xhtml+xml",xls="application/vnd.ms-excel",xlsx="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml="text/xml",xpi="application/x-xpinstall",xspf="application/xspf+xml",zip="application/zip",mimeTypes={_default,"3gpp":"video/3gpp","7z":"application/x-7z-compressed",asx,atom,avi,avif,bin,bmp,cco,css,data,deb,der,dmg,doc,docx,eot,flv,gif,gz,hqx,htc,html,ico,iso,jad,jar,jardiff,jng,jnlp,jpg,jpeg,js,json,kml,kmz,m3u8,m4a,m4v,md,mid,mml,mng,mov,mp3,mp4,mpeg,msi,odg,odp,ods,odt,ogg,otf,pdf,pl,png,ppt,pptx,prc,ps,ra,rar,rpm,rss,rtf,run,sea,sit,svg,swf,tcl,tar,tif,ts,ttf,txt,wasm,wbmp,webm,webp,wml,wmlc,wmv,woff,woff2,xhtml,xls,xlsx,xml,xpi,xspf,zip};class PHPRequestHandler{#e;#r;#a;#s;#n;#t;#i;#o;constructor(t){const{documentRoot:s="/www/",absoluteUrl:r=typeof location=="object"?location?.href:"",rewriteRules:n=[]}=t;"processManager"in t?this.processManager=t.processManager:this.processManager=new PHPProcessManager({phpFactory:async a=>{const c=await t.phpFactory({...a,requestHandler:this});return c.requestHandler=this,c},maxPhpInstances:t.maxPhpInstances}),this.#o=new HttpCookieStore,this.#e=s;const i=new URL(r);this.#a=i.hostname,this.#s=i.port?Number(i.port):i.protocol==="https:"?443:80,this.#r=(i.protocol||"").replace(":","");const o=this.#s!==443&&this.#s!==80;this.#n=[this.#a,o?`:${this.#s}`:""].join(""),this.#t=i.pathname.replace(/\/+$/,""),this.#i=[`${this.#r}://`,this.#n,this.#t].join(""),this.rewriteRules=n}async getPrimaryPhp(){return await this.processManager.getPrimaryPhp()}pathToInternalUrl(t){return`${this.absoluteUrl}${t}`}internalUrlToPath(t){const s=new URL(t);return s.pathname.startsWith(this.#t)&&(s.pathname=s.pathname.slice(this.#t.length)),toRelativeUrl(s)}get absoluteUrl(){return this.#i}get documentRoot(){return this.#e}async request(t){const s=t.url.startsWith("http://")||t.url.startsWith("https://"),r=new URL(t.url.split("#")[0],s?void 0:DEFAULT_BASE_URL),n=applyRewriteRules(removePathPrefix(decodeURIComponent(r.pathname),this.#t),this.rewriteRules),i=joinPaths(this.#e,n);return seemsLikeAPHPRequestHandlerPath(i)?this.#c(t,r):this.#l(await this.processManager.getPrimaryPhp(),i)}#l(t,s){if(!t.fileExists(s))return new PHPResponse(404,{"x-file-type":["static"]},new TextEncoder().encode("404 File not found"));const r=t.readFileAsBuffer(s);return new PHPResponse(200,{"content-length":[`${r.byteLength}`],"content-type":[inferMimeType(s)],"accept-ranges":["bytes"],"cache-control":["public, max-age=0"]},r)}async#c(t,s){let r;try{r=await this.processManager.acquirePHPInstance()}catch(n){return n instanceof MaxPhpInstancesError?PHPResponse.forHttpCode(502):PHPResponse.forHttpCode(500)}try{return await this.#d(r.php,t,s)}finally{r.reap()}}async#d(t,s,r){let n="GET";const i={host:this.#n,...normalizeHeaders(s.headers||{}),cookie:this.#o.getCookieRequestHeader()};let o=s.body;if(typeof o=="object"&&!(o instanceof Uint8Array)){n="POST";const{bytes:c,contentType:l}=await encodeAsMultipart(o);o=c,i["content-type"]=l}let a;try{a=this.#p(t,decodeURIComponent(r.pathname))}catch{return PHPResponse.forHttpCode(404)}try{const c=await t.run({relativeUri:ensurePathPrefix(toRelativeUrl(r),this.#t),protocol:this.#r,method:s.method||n,$_SERVER:{REMOTE_ADDR:"127.0.0.1",DOCUMENT_ROOT:this.#e,HTTPS:this.#i.startsWith("https://")?"on":""},body:o,scriptPath:a,headers:i});return this.#o.rememberCookiesFromResponseHeaders(c.headers),c}catch(c){const l=c;if(l?.response)return l.response;throw c}}#p(t,s){let r=removePathPrefix(s,this.#t);r=applyRewriteRules(r,this.rewriteRules),r.includes(".php")?r=r.split(".php")[0]+".php":t.isDir(`${this.#e}${r}`)?(r.endsWith("/")||(r=`${r}/`),r=`${r}index.php`):r="/index.php";let n=`${this.#e}${r}`;if(t.fileExists(n)||(n=`${this.#e}/index.php`),t.fileExists(n))return n;throw new Error(`File not found: ${n}`)}}function inferMimeType(e){const t=e.split(".").pop();return mimeTypes[t]||mimeTypes._default}function seemsLikeAPHPRequestHandlerPath(e){return seemsLikeAPHPFile(e)||seemsLikeADirectoryRoot(e)}function seemsLikeAPHPFile(e){return e.endsWith(".php")||e.includes(".php/")}function seemsLikeADirectoryRoot(e){return!e.split("/").pop().includes(".")}function applyRewriteRules(e,t){for(const s of t)if(new RegExp(s.match).test(e))return e.replace(s.match,s.replacement);return e}function rotatePHPRuntime({php:e,cwd:t,recreateRuntime:s,maxRequests:r=400}){let n=0;async function i(){if(++n<r)return;n=0;const o=await e.semaphore.acquire();try{e.hotSwapPHPRuntime(await s(),t)}finally{o()}}return e.addEventListener("request.end",i),function(){e.removeEventListener("request.end",i)}}async function writeFiles(e,t,s,{rmRoot:r=!1}={}){r&&await e.isDir(t)&&await e.rmdir(t,{recursive:!0});for(const[n,i]of Object.entries(s)){const o=joinPaths(t,n);await e.fileExists(dirname(o))||await e.mkdir(dirname(o)),i instanceof Uint8Array||typeof i=="string"?await e.writeFile(o,i):await writeFiles(e,o,i)}}function proxyFileSystem(e,t,s){const r=Object.getOwnPropertySymbols(e)[0];for(const n of s)t.fileExists(n)||t.mkdir(n),e.fileExists(n)||e.mkdir(n),t[r].FS.mount(t[r].PROXYFS,{root:n,fs:e[r].FS},n)}async function bootWordPress(e){async function t(n,i){const o=new PHP(await e.createPhpRuntime());return e.sapiName&&o.setSapiName(e.sapiName),n&&(o.requestHandler=n),e.phpIniEntries&&setPhpIniEntries(o,e.phpIniEntries),i?(await setupPlatformLevelMuPlugins(o),await writeFiles(o,"/",e.createFiles||{}),await preloadPhpInfoRoute(o,joinPaths(new URL(e.siteUrl).pathname,"phpinfo.php"))):proxyFileSystem(await n.getPrimaryPhp(),o,["/tmp",n.documentRoot,"/internal/shared"]),e.spawnHandler&&await o.setSpawnHandler(e.spawnHandler(n.processManager)),rotatePHPRuntime({php:o,cwd:n.documentRoot,recreateRuntime:e.createPhpRuntime,maxRequests:400}),o}const s=new PHPRequestHandler({phpFactory:async({isPrimary:n})=>t(s,n),documentRoot:e.documentRoot||"/wordpress",absoluteUrl:e.siteUrl,rewriteRules:wordPressRewriteRules}),r=await s.getPrimaryPhp();if(e.hooks?.beforeWordPressFiles&&await e.hooks.beforeWordPressFiles(r),e.wordPressZip&&await unzipWordPress(r,await e.wordPressZip),e.constants)for(const n in e.constants)r.defineConstant(n,e.constants[n]);if(r.defineConstant("WP_HOME",e.siteUrl),r.defineConstant("WP_SITEURL",e.siteUrl),e.hooks?.beforeDatabaseSetup&&await e.hooks.beforeDatabaseSetup(r),e.sqliteIntegrationPluginZip&&await preloadSqliteIntegration(r,await e.sqliteIntegrationPluginZip),await isWordPressInstalled(r)||await installWordPress(r),!await isWordPressInstalled(r))throw new Error("WordPress installation has failed.");return s}async function isWordPressInstalled(e){return(await e.run({code:`<?php
require '${e.documentRoot}/wp-load.php';
echo is_blog_installed() ? '1' : '0';
`})).text==="1"}async function installWordPress(e){await withPHPIniValues(e,{disable_functions:"fsockopen",allow_url_fopen:"0"},async()=>await e.request({url:"/wp-admin/install.php?step=2",method:"POST",body:{language:"en",prefix:"wp_",weblog_title:"My WordPress Website",user_name:"admin",admin_password:"password",admin_password2:"password",Submit:"Install WordPress",pw_weak:"1",admin_email:"admin@localhost.com"}}))}const nightly="nightly",beta="6.6-RC1",SupportedWordPressVersions={nightly,beta,"6.5":"6.5.5","6.4":"6.4.5","6.3":"6.3.5","6.2":"6.2.6"},SupportedWordPressVersionsList=Object.keys(SupportedWordPressVersions);SupportedWordPressVersionsList.filter(e=>e.match(/^\d/))[0];async function getLoadedWordPressVersion(e){const r=(await(await e.getPrimaryPhp()).run({code:`<?php
require '${e.documentRoot}/wp-includes/version.php';
echo $wp_version;
`})).text;if(!r)throw new Error("Unable to read loaded WordPress version.");return versionStringToLoadedWordPressVersion(r)}function versionStringToLoadedWordPressVersion(e){if(/-(alpha|beta|RC)\d*-\d+$/.test(e))return"nightly";if(/-(beta|RC)\d*$/.test(e))return"beta";const r=e.match(/^(\d+\.\d+)(?:\.\d+)?$/);return r!==null?r[1]:e}function isSupportedWordPressVersion(e){return Object.keys(SupportedWordPressVersions).includes(e)}const wordPressRewriteRules=[{match:/^\/(.*?)(\/wp-(content|admin|includes)\/.*)/g,replacement:"$2"}];async function setupPlatformLevelMuPlugins(e){await e.mkdir("/internal/shared/mu-plugins"),await e.writeFile("/internal/shared/preload/env.php",`<?php

@@ -46,3 +112,3 @@ // Allow adding filters/actions prior to loading WordPress.

}
`)}async function h(e){const i=Object.values({addTrailingSlashToWpAdmin:`<?php
`),await e.writeFile("/internal/shared/mu-plugins/0-playground.php",`<?php
// Redirect /wp-admin to /wp-admin/

@@ -55,3 +121,3 @@ add_filter( 'redirect_canonical', function( $redirect_url ) {

} );
?>`,allowRedirectHosts:`<?php
// Needed because gethostbyname( 'wordpress.org' ) returns

@@ -66,5 +132,6 @@ // a private network IP address for some reason.

} );
?>`,supportPermalinksWithoutIndexPhp:`<?php
// Support pretty permalinks
add_filter( 'got_url_rewrite', '__return_true' );
?>`,createFontsDirectory:`<?php
// Create the fonts directory if missing

@@ -74,8 +141,7 @@ if(!file_exists(WP_CONTENT_DIR . '/fonts')) {

}
?>`,configureErrorLogging:`<?php
$log_file = WP_CONTENT_DIR . '/debug.log';
define('ERROR_LOG_FILE', $log_file);
ini_set('error_log', $log_file);
?>`}).map(n=>n.trim()).join(`
`);await e.writeFile("/internal/shared/mu-plugins/0-playground.php",i),await e.writeFile("/internal/shared/preload/error-handler.php",`<?php
?>`),await e.writeFile("/internal/shared/preload/error-handler.php",`<?php
(function() {

@@ -127,14 +193,14 @@ $playground_consts = [];

});
})();`)}async function b(e,t="/phpinfo.php"){await e.writeFile("/internal/shared/preload/phpinfo.php",`<?php
})();`)}async function preloadPhpInfoRoute(e,t="/phpinfo.php"){await e.writeFile("/internal/shared/preload/phpinfo.php",`<?php
// Render PHPInfo if the requested page is /phpinfo.php
if ( ${s(t)} === $_SERVER['REQUEST_URI'] ) {
if ( ${phpVar(t)} === $_SERVER['REQUEST_URI'] ) {
phpinfo();
exit;
}
`)}async function y(e,t){await e.isDir("/tmp/sqlite-database-integration")&&await e.rmdir("/tmp/sqlite-database-integration",{recursive:!0}),await e.mkdir("/tmp/sqlite-database-integration"),await d(e,t,"/tmp/sqlite-database-integration");const i="/internal/shared/sqlite-database-integration";await e.mv("/tmp/sqlite-database-integration/sqlite-database-integration-main",i);const r=(await e.readFileAsText(o(i,"db.copy"))).replace("'{SQLITE_IMPLEMENTATION_FOLDER_PATH}'",s(i)).replace("'{SQLITE_PLUGIN}'",s(o(i,"load.php"))),u=o(await e.documentRoot,"wp-content/db.php"),l=`<?php
`)}async function preloadSqliteIntegration(e,t){await e.isDir("/tmp/sqlite-database-integration")&&await e.rmdir("/tmp/sqlite-database-integration",{recursive:!0}),await e.mkdir("/tmp/sqlite-database-integration"),await unzipFile(e,t,"/tmp/sqlite-database-integration");const s="/internal/shared/sqlite-database-integration";await e.mv("/tmp/sqlite-database-integration/sqlite-database-integration-main",s),await e.defineConstant("SQLITE_MAIN_FILE","1");const n=(await e.readFileAsText(joinPaths(s,"db.copy"))).replace("'{SQLITE_IMPLEMENTATION_FOLDER_PATH}'",phpVar(s)).replace("'{SQLITE_PLUGIN}'",phpVar(joinPaths(s,"load.php"))),i=joinPaths(await e.documentRoot,"wp-content/db.php"),o=`<?php
// Do not preload this if WordPress comes with a custom db.php file.
if(file_exists(${s(u)})) {
if(file_exists(${phpVar(i)})) {
return;
}
?>`,p="/internal/shared/mu-plugins/sqlite-database-integration.php";await e.writeFile(p,l+r),await e.writeFile("/internal/shared/preload/0-sqlite.php",l+`<?php
?>`,a="/internal/shared/mu-plugins/sqlite-database-integration.php";await e.writeFile(a,o+n),await e.writeFile("/internal/shared/preload/0-sqlite.php",o+`<?php

@@ -189,3 +255,3 @@ /**

protected function load_sqlite_integration() {
require_once ${s(p)};
require_once ${phpVar(a)};
}

@@ -212,2 +278,2 @@ }

}
`)}async function P(e,t){e.mkdir("/tmp/unzipped-wordpress"),await d(e,t,"/tmp/unzipped-wordpress"),e.fileExists("/tmp/unzipped-wordpress/wordpress.zip")&&await d(e,"/tmp/unzipped-wordpress/wordpress.zip","/tmp/unzipped-wordpress");const i=e.fileExists("/tmp/unzipped-wordpress/wordpress")?"/tmp/unzipped-wordpress/wordpress":e.fileExists("/tmp/unzipped-wordpress/build")?"/tmp/unzipped-wordpress/build":"/tmp/unzipped-wordpress";e.mv(i,e.documentRoot),!e.fileExists(o(e.documentRoot,"wp-config.php"))&&e.fileExists(o(e.documentRoot,"wp-config-sample.php"))&&e.writeFile(o(e.documentRoot,"wp-config.php"),e.readFileAsText(o(e.documentRoot,"/wp-config-sample.php")))}export{$ as enablePlatformMuPlugins,b as preloadPhpInfoRoute,h as preloadRequiredMuPlugin,y as preloadSqliteIntegration,P as unzipWordPress,m as wordPressRewriteRules};
`)}async function unzipWordPress(e,t){e.mkdir("/tmp/unzipped-wordpress"),await unzipFile(e,t,"/tmp/unzipped-wordpress"),e.fileExists("/tmp/unzipped-wordpress/wordpress.zip")&&await unzipFile(e,"/tmp/unzipped-wordpress/wordpress.zip","/tmp/unzipped-wordpress");const s=e.fileExists("/tmp/unzipped-wordpress/wordpress")?"/tmp/unzipped-wordpress/wordpress":e.fileExists("/tmp/unzipped-wordpress/build")?"/tmp/unzipped-wordpress/build":"/tmp/unzipped-wordpress";e.mv(s,e.documentRoot),!e.fileExists(joinPaths(e.documentRoot,"wp-config.php"))&&e.fileExists(joinPaths(e.documentRoot,"wp-config-sample.php"))&&e.writeFile(joinPaths(e.documentRoot,"wp-config.php"),e.readFileAsText(joinPaths(e.documentRoot,"/wp-config-sample.php")))}export{bootWordPress,getLoadedWordPressVersion,isSupportedWordPressVersion,preloadPhpInfoRoute,preloadSqliteIntegration,setupPlatformLevelMuPlugins,unzipWordPress,wordPressRewriteRules};
{
"name": "@wp-playground/wordpress",
"version": "0.7.20",
"version": "0.9.1",
"description": "WordPress-related plumbing for WordPress Playground",

@@ -30,3 +30,3 @@ "repository": {

},
"gitHead": "5915ef756c88da8dcb665f9f0e49ddc0c0b10d50"
"gitHead": "1097764159c71f5fd9f215f46385d1c83428fe01"
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc