@wp-playground/wordpress 0.7.19 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/sqlite-database-integration-fd6f4063.zip +0 -0
- package/assets/wp-6.2-d4512a23.zip +0 -0
- package/assets/wp-6.3-cad7e42e.zip +0 -0
- package/assets/wp-6.4-f4f06f3b.zip +0 -0
- package/assets/wp-6.5-264f1631.zip +0 -0
- package/assets/wp-beta-1c0776b7.zip +0 -0
- package/assets/wp-nightly-06341211.zip +0 -0
- package/boot.d.ts +80 -0
- package/index.d.ts +31 -1
- package/index.js +271 -1
- package/package.json +2 -5
- package/version-detect.d.ts +4 -0
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/boot.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { FileTree, PHP, PHPProcessManager, PHPRequestHandler, SpawnHandler } from '../../../php-wasm/universal/src/index.ts';
|
|
2
|
+
export type PhpIniOptions = Record<string, string>;
|
|
3
|
+
export type Hook = (php: PHP) => void | Promise<void>;
|
|
4
|
+
export interface Hooks {
|
|
5
|
+
beforeWordPressFiles?: Hook;
|
|
6
|
+
beforeDatabaseSetup?: Hook;
|
|
7
|
+
}
|
|
8
|
+
export type DatabaseType = 'sqlite' | 'mysql' | 'custom';
|
|
9
|
+
export interface BootOptions {
|
|
10
|
+
createPhpRuntime: () => Promise<number>;
|
|
11
|
+
/**
|
|
12
|
+
* Mounting and Copying is handled via hooks for starters.
|
|
13
|
+
*
|
|
14
|
+
* In the future we could standardize the
|
|
15
|
+
* browser-specific and node-specific mounts
|
|
16
|
+
* in the future.
|
|
17
|
+
*/
|
|
18
|
+
hooks?: Hooks;
|
|
19
|
+
/**
|
|
20
|
+
* PHP SAPI name to be returned by get_sapi_name(). Overriding
|
|
21
|
+
* it is useful for running programs that check for this value,
|
|
22
|
+
* e.g. WP-CLI
|
|
23
|
+
*/
|
|
24
|
+
sapiName?: string;
|
|
25
|
+
/**
|
|
26
|
+
* URL to use as the site URL. This is used to set the WP_HOME
|
|
27
|
+
* and WP_SITEURL constants in WordPress.
|
|
28
|
+
*/
|
|
29
|
+
siteUrl: string;
|
|
30
|
+
documentRoot?: string;
|
|
31
|
+
/** SQL file to load instead of installing WordPress. */
|
|
32
|
+
dataSqlPath?: string;
|
|
33
|
+
/** Zip with the WordPress installation to extract in /wordpress. */
|
|
34
|
+
wordPressZip?: File | Promise<File> | undefined;
|
|
35
|
+
/** Preloaded SQLite integration plugin. */
|
|
36
|
+
sqliteIntegrationPluginZip?: File | Promise<File>;
|
|
37
|
+
spawnHandler?: (processManager: PHPProcessManager) => SpawnHandler;
|
|
38
|
+
/**
|
|
39
|
+
* PHP.ini entries to define before running any code. They'll
|
|
40
|
+
* be used for all requests.
|
|
41
|
+
*/
|
|
42
|
+
phpIniEntries?: PhpIniOptions;
|
|
43
|
+
/**
|
|
44
|
+
* PHP constants to define for every request.
|
|
45
|
+
*/
|
|
46
|
+
constants?: Record<string, string | number | boolean | null>;
|
|
47
|
+
/**
|
|
48
|
+
* Files to create in the filesystem before any mounts are applied.
|
|
49
|
+
*
|
|
50
|
+
* Example:
|
|
51
|
+
*
|
|
52
|
+
* ```ts
|
|
53
|
+
* {
|
|
54
|
+
* createFiles: {
|
|
55
|
+
* '/tmp/hello.txt': 'Hello, World!',
|
|
56
|
+
* '/internal/preload': {
|
|
57
|
+
* '1-custom-mu-plugin.php': '<?php echo "Hello, World!";',
|
|
58
|
+
* }
|
|
59
|
+
* }
|
|
60
|
+
* }
|
|
61
|
+
* ```
|
|
62
|
+
*/
|
|
63
|
+
createFiles?: FileTree;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Boots a WordPress instance with the given options.
|
|
67
|
+
*
|
|
68
|
+
* High-level overview:
|
|
69
|
+
*
|
|
70
|
+
* * Boot PHP instances and PHPRequestHandler
|
|
71
|
+
* * Setup VFS, run beforeWordPressFiles hook
|
|
72
|
+
* * Setup WordPress files (if wordPressZip is provided)
|
|
73
|
+
* * Run beforeDatabaseSetup hook
|
|
74
|
+
* * Setup the database – SQLite, MySQL (@TODO), or rely on a mounted database
|
|
75
|
+
* * Run WordPress installer, if the site isn't installed yet
|
|
76
|
+
*
|
|
77
|
+
* @param options Boot configuration options
|
|
78
|
+
* @return PHPRequestHandler instance with WordPress installed.
|
|
79
|
+
*/
|
|
80
|
+
export declare function bootWordPress(options: BootOptions): Promise<PHPRequestHandler>;
|
package/index.d.ts
CHANGED
|
@@ -1,2 +1,32 @@
|
|
|
1
|
+
import { PHP, UniversalPHP } from '../../../php-wasm/universal/src/index.ts';
|
|
2
|
+
export { bootWordPress } from './boot';
|
|
3
|
+
export { getLoadedWordPressVersion, isSupportedWordPressVersion, } from './version-detect';
|
|
1
4
|
export * from './rewrite-rules';
|
|
2
|
-
|
|
5
|
+
/**
|
|
6
|
+
* Preloads the platform mu-plugins from /internal/shared/mu-plugins.
|
|
7
|
+
* This avoids polluting the WordPress installation with mu-plugins
|
|
8
|
+
* that are only needed in the Playground environment.
|
|
9
|
+
*
|
|
10
|
+
* @param php
|
|
11
|
+
*/
|
|
12
|
+
export declare function setupPlatformLevelMuPlugins(php: UniversalPHP): Promise<void>;
|
|
13
|
+
/**
|
|
14
|
+
* Runs phpinfo() when the requested path is /phpinfo.php.
|
|
15
|
+
*/
|
|
16
|
+
export declare function preloadPhpInfoRoute(php: UniversalPHP, requestPath?: string): Promise<void>;
|
|
17
|
+
export declare function preloadSqliteIntegration(php: UniversalPHP, sqliteZip: File): Promise<void>;
|
|
18
|
+
/**
|
|
19
|
+
* Prepare the WordPress document root given a WordPress zip file and
|
|
20
|
+
* the sqlite-database-integration zip file.
|
|
21
|
+
*
|
|
22
|
+
* This is a TypeScript function for now, just to get something off the
|
|
23
|
+
* ground, but it may be superseded by the PHP Blueprints library developed
|
|
24
|
+
* at https://github.com/WordPress/blueprints-library/
|
|
25
|
+
*
|
|
26
|
+
* That PHP library will come with a set of functions and a CLI tool to
|
|
27
|
+
* turn a Blueprint into a WordPress directory structure or a zip Snapshot.
|
|
28
|
+
* Let's **not** invest in the TypeScript implementation of this function,
|
|
29
|
+
* accept the limitation, and switch to the PHP implementation as soon
|
|
30
|
+
* as that's viable.
|
|
31
|
+
*/
|
|
32
|
+
export declare function unzipWordPress(php: PHP, wpZip: File): Promise<void>;
|
package/index.js
CHANGED
|
@@ -1 +1,271 @@
|
|
|
1
|
-
const e=[{
|
|
1
|
+
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
|
|
2
|
+
function unzip($zipPath, $extractTo, $overwrite = true)
|
|
3
|
+
{
|
|
4
|
+
if (!is_dir($extractTo)) {
|
|
5
|
+
mkdir($extractTo, 0777, true);
|
|
6
|
+
}
|
|
7
|
+
$zip = new ZipArchive;
|
|
8
|
+
$res = $zip->open($zipPath);
|
|
9
|
+
if ($res === TRUE) {
|
|
10
|
+
$zip->extractTo($extractTo);
|
|
11
|
+
$zip->close();
|
|
12
|
+
chmod($extractTo, 0777);
|
|
13
|
+
} else {
|
|
14
|
+
throw new Exception("Could not unzip file");
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
unzip(${r.zipPath}, ${r.extractToPath});
|
|
18
|
+
`}),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(`
|
|
19
|
+
`):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.
|
|
20
|
+
If you're using a custom logger instance, make sure to register logToMemory handler.
|
|
21
|
+
`),[])}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+=`
|
|
22
|
+
|
|
23
|
+
This stack trace is lacking. For a better one initialize
|
|
24
|
+
the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
|
|
25
|
+
|
|
26
|
+
`),functionsMaybeMissingFromAsyncify=extractPHPFunctionsFromStack(t||e.stack||"");for(const r of functionsMaybeMissingFromAsyncify)s+=` * ${r}
|
|
27
|
+
`;return s}return e.message}const UNREACHABLE_ERROR=`
|
|
28
|
+
"unreachable" WASM instruction executed.
|
|
29
|
+
|
|
30
|
+
The typical reason is a PHP function missing from the ASYNCIFY_ONLY
|
|
31
|
+
list when building PHP.wasm.
|
|
32
|
+
|
|
33
|
+
You will need to file a new issue in the WordPress Playground repository
|
|
34
|
+
and paste this error message there:
|
|
35
|
+
|
|
36
|
+
https://github.com/WordPress/wordpress-playground/issues/new
|
|
37
|
+
|
|
38
|
+
If you're a core developer, the typical fix is to:
|
|
39
|
+
|
|
40
|
+
* Isolate a minimal reproduction of the error
|
|
41
|
+
* Add a reproduction of the error to php-asyncify.spec.ts in the WordPress Playground repository
|
|
42
|
+
* Run 'npm run fix-asyncify'
|
|
43
|
+
* Commit the changes, push to the repo, release updated NPM packages
|
|
44
|
+
|
|
45
|
+
Below is a list of all the PHP functions found in the stack trace to
|
|
46
|
+
help with the minimal reproduction. If they're all already listed in
|
|
47
|
+
the Dockerfile, you'll need to trigger this error again with long stack
|
|
48
|
+
traces enabled. In node.js, you can do it using the --stack-trace-limit=100
|
|
49
|
+
CLI option:
|
|
50
|
+
|
|
51
|
+
`,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}
|
|
52
|
+
${eol}
|
|
53
|
+
${bold} WASM ERROR${reset}${redBg}`);for(const t of e.split(`
|
|
54
|
+
`))logger.log(`${eol} ${t} `);logger.log(`${reset}`)}}function extractPHPFunctionsFromStack(e){try{const t=e.split(`
|
|
55
|
+
`).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(`
|
|
56
|
+
`)),this.fileExists(AUTO_PREPEND_SCRIPT)||this.writeFile(AUTO_PREPEND_SCRIPT,`<?php
|
|
57
|
+
// Define constants set via defineConstant() calls
|
|
58
|
+
if(file_exists('/internal/shared/consts.json')) {
|
|
59
|
+
$consts = json_decode(file_get_contents('/internal/shared/consts.json'), true);
|
|
60
|
+
foreach ($consts as $const => $value) {
|
|
61
|
+
if (!defined($const) && is_scalar($value)) {
|
|
62
|
+
define($const, $value);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
// Preload all the files from /internal/shared/preload
|
|
67
|
+
foreach (glob('/internal/shared/preload/*.php') as $file) {
|
|
68
|
+
require_once $file;
|
|
69
|
+
}
|
|
70
|
+
`),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&©FS(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
|
|
71
|
+
`:`
|
|
72
|
+
`,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
|
|
73
|
+
`),n.push(`Content-Disposition: form-data; name="${c}"`),l instanceof File&&n.push(`; filename="${l.name}"`),n.push(`\r
|
|
74
|
+
`),l instanceof File&&(n.push("Content-Type: application/octet-stream"),n.push(`\r
|
|
75
|
+
`)),n.push(`\r
|
|
76
|
+
`),l instanceof File?n.push(await fileToUint8Array(l)):n.push(l),n.push(`\r
|
|
77
|
+
`);n.push(`--${t}--\r
|
|
78
|
+
`);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
|
|
79
|
+
require '${e.documentRoot}/wp-load.php';
|
|
80
|
+
echo is_blog_installed() ? '1' : '0';
|
|
81
|
+
`})).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
|
|
82
|
+
require '${e.documentRoot}/wp-includes/version.php';
|
|
83
|
+
echo $wp_version;
|
|
84
|
+
`})).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
|
|
85
|
+
|
|
86
|
+
// Allow adding filters/actions prior to loading WordPress.
|
|
87
|
+
// $function_to_add MUST be a string.
|
|
88
|
+
function playground_add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {
|
|
89
|
+
global $wp_filter;
|
|
90
|
+
$wp_filter[$tag][$priority][$function_to_add] = array('function' => $function_to_add, 'accepted_args' => $accepted_args);
|
|
91
|
+
}
|
|
92
|
+
function playground_add_action( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {
|
|
93
|
+
playground_add_filter( $tag, $function_to_add, $priority, $accepted_args );
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Load our mu-plugins after customer mu-plugins
|
|
97
|
+
// NOTE: this means our mu-plugins can't use the muplugins_loaded action!
|
|
98
|
+
playground_add_action( 'muplugins_loaded', 'playground_load_mu_plugins', 0 );
|
|
99
|
+
function playground_load_mu_plugins() {
|
|
100
|
+
// Load all PHP files from /internal/shared/mu-plugins, sorted by filename
|
|
101
|
+
$mu_plugins_dir = '/internal/shared/mu-plugins';
|
|
102
|
+
if(!is_dir($mu_plugins_dir)){
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
$mu_plugins = glob( $mu_plugins_dir . '/*.php' );
|
|
106
|
+
sort( $mu_plugins );
|
|
107
|
+
foreach ( $mu_plugins as $mu_plugin ) {
|
|
108
|
+
require_once $mu_plugin;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
`),await e.writeFile("/internal/shared/mu-plugins/0-playground.php",`<?php
|
|
112
|
+
// Redirect /wp-admin to /wp-admin/
|
|
113
|
+
add_filter( 'redirect_canonical', function( $redirect_url ) {
|
|
114
|
+
if ( '/wp-admin' === $redirect_url ) {
|
|
115
|
+
return $redirect_url . '/';
|
|
116
|
+
}
|
|
117
|
+
return $redirect_url;
|
|
118
|
+
} );
|
|
119
|
+
|
|
120
|
+
// Needed because gethostbyname( 'wordpress.org' ) returns
|
|
121
|
+
// a private network IP address for some reason.
|
|
122
|
+
add_filter( 'allowed_redirect_hosts', function( $deprecated = '' ) {
|
|
123
|
+
return array(
|
|
124
|
+
'wordpress.org',
|
|
125
|
+
'api.wordpress.org',
|
|
126
|
+
'downloads.wordpress.org',
|
|
127
|
+
);
|
|
128
|
+
} );
|
|
129
|
+
|
|
130
|
+
// Support pretty permalinks
|
|
131
|
+
add_filter( 'got_url_rewrite', '__return_true' );
|
|
132
|
+
|
|
133
|
+
// Create the fonts directory if missing
|
|
134
|
+
if(!file_exists(WP_CONTENT_DIR . '/fonts')) {
|
|
135
|
+
mkdir(WP_CONTENT_DIR . '/fonts');
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
$log_file = WP_CONTENT_DIR . '/debug.log';
|
|
139
|
+
define('ERROR_LOG_FILE', $log_file);
|
|
140
|
+
ini_set('error_log', $log_file);
|
|
141
|
+
?>`),await e.writeFile("/internal/shared/preload/error-handler.php",`<?php
|
|
142
|
+
(function() {
|
|
143
|
+
$playground_consts = [];
|
|
144
|
+
if(file_exists('/internal/shared/consts.json')) {
|
|
145
|
+
$playground_consts = @json_decode(file_get_contents('/internal/shared/consts.json'), true) ?: [];
|
|
146
|
+
$playground_consts = array_keys($playground_consts);
|
|
147
|
+
}
|
|
148
|
+
set_error_handler(function($severity, $message, $file, $line) use($playground_consts) {
|
|
149
|
+
/**
|
|
150
|
+
* This is a temporary workaround to hide the 32bit integer warnings that
|
|
151
|
+
* appear when using various time related function, such as strtotime and mktime.
|
|
152
|
+
* Examples of the warnings that are displayed:
|
|
153
|
+
*
|
|
154
|
+
* Warning: mktime(): Epoch doesn't fit in a PHP integer in <file>
|
|
155
|
+
* Warning: strtotime(): Epoch doesn't fit in a PHP integer in <file>
|
|
156
|
+
*/
|
|
157
|
+
if (strpos($message, "fit in a PHP integer") !== false) {
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Playground defines some constants upfront, and some of them may be redefined
|
|
162
|
+
* in wp-config.php. For example, SITE_URL or WP_DEBUG. This is expected and
|
|
163
|
+
* we want Playground constants to take priority without showing warnings like:
|
|
164
|
+
*
|
|
165
|
+
* Warning: Constant SITE_URL already defined in
|
|
166
|
+
*/
|
|
167
|
+
if (strpos($message, "already defined") !== false) {
|
|
168
|
+
foreach($playground_consts as $const) {
|
|
169
|
+
if(strpos($message, "Constant $const already defined") !== false) {
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Don't complain about network errors when not connected to the network.
|
|
176
|
+
*/
|
|
177
|
+
if (
|
|
178
|
+
(
|
|
179
|
+
! defined('USE_FETCH_FOR_REQUESTS') ||
|
|
180
|
+
! USE_FETCH_FOR_REQUESTS
|
|
181
|
+
) &&
|
|
182
|
+
strpos($message, "WordPress could not establish a secure connection to WordPress.org") !== false)
|
|
183
|
+
{
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
return false;
|
|
187
|
+
});
|
|
188
|
+
})();`)}async function preloadPhpInfoRoute(e,t="/phpinfo.php"){await e.writeFile("/internal/shared/preload/phpinfo.php",`<?php
|
|
189
|
+
// Render PHPInfo if the requested page is /phpinfo.php
|
|
190
|
+
if ( ${phpVar(t)} === $_SERVER['REQUEST_URI'] ) {
|
|
191
|
+
phpinfo();
|
|
192
|
+
exit;
|
|
193
|
+
}
|
|
194
|
+
`)}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
|
|
195
|
+
// Do not preload this if WordPress comes with a custom db.php file.
|
|
196
|
+
if(file_exists(${phpVar(i)})) {
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
?>`,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
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Loads the SQLite integration plugin before WordPress is loaded
|
|
203
|
+
* and without creating a drop-in "db.php" file.
|
|
204
|
+
*
|
|
205
|
+
* Technically, it creates a global $wpdb object whose only two
|
|
206
|
+
* purposes are to:
|
|
207
|
+
*
|
|
208
|
+
* * Exist – because the require_wp_db() WordPress function won't
|
|
209
|
+
* connect to MySQL if $wpdb is already set.
|
|
210
|
+
* * Load the SQLite integration plugin the first time it's used
|
|
211
|
+
* and replace the global $wpdb reference with the SQLite one.
|
|
212
|
+
*
|
|
213
|
+
* This lets Playground keep the WordPress installation clean and
|
|
214
|
+
* solves dillemas like:
|
|
215
|
+
*
|
|
216
|
+
* * Should we include db.php in Playground exports?
|
|
217
|
+
* * Should we remove db.php from Playground imports?
|
|
218
|
+
* * How should we treat stale db.php from long-lived OPFS sites?
|
|
219
|
+
*
|
|
220
|
+
* @see https://github.com/WordPress/wordpress-playground/discussions/1379 for
|
|
221
|
+
* more context.
|
|
222
|
+
*/
|
|
223
|
+
class Playground_SQLite_Integration_Loader {
|
|
224
|
+
public function __call($name, $arguments) {
|
|
225
|
+
$this->load_sqlite_integration();
|
|
226
|
+
if($GLOBALS['wpdb'] === $this) {
|
|
227
|
+
throw new Exception('Infinite loop detected in $wpdb – SQLite integration plugin could not be loaded');
|
|
228
|
+
}
|
|
229
|
+
return call_user_func_array(
|
|
230
|
+
array($GLOBALS['wpdb'], $name),
|
|
231
|
+
$arguments
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
public function __get($name) {
|
|
235
|
+
$this->load_sqlite_integration();
|
|
236
|
+
if($GLOBALS['wpdb'] === $this) {
|
|
237
|
+
throw new Exception('Infinite loop detected in $wpdb – SQLite integration plugin could not be loaded');
|
|
238
|
+
}
|
|
239
|
+
return $GLOBALS['wpdb']->$name;
|
|
240
|
+
}
|
|
241
|
+
public function __set($name, $value) {
|
|
242
|
+
$this->load_sqlite_integration();
|
|
243
|
+
if($GLOBALS['wpdb'] === $this) {
|
|
244
|
+
throw new Exception('Infinite loop detected in $wpdb – SQLite integration plugin could not be loaded');
|
|
245
|
+
}
|
|
246
|
+
$GLOBALS['wpdb']->$name = $value;
|
|
247
|
+
}
|
|
248
|
+
protected function load_sqlite_integration() {
|
|
249
|
+
require_once ${phpVar(a)};
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
$wpdb = $GLOBALS['wpdb'] = new Playground_SQLite_Integration_Loader();
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* WordPress is capable of using a preloaded global $wpdb. However, if
|
|
256
|
+
* it cannot find the drop-in db.php plugin it still checks whether
|
|
257
|
+
* the mysqli_connect() function exists even though it's not used.
|
|
258
|
+
*
|
|
259
|
+
* What WordPress demands, Playground shall provide.
|
|
260
|
+
*/
|
|
261
|
+
if(!function_exists('mysqli_connect')) {
|
|
262
|
+
function mysqli_connect() {}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
`),await e.writeFile("/internal/shared/mu-plugins/sqlite-test.php",`<?php
|
|
266
|
+
global $wpdb;
|
|
267
|
+
if(!($wpdb instanceof WP_SQLite_DB)) {
|
|
268
|
+
var_dump(isset($wpdb));
|
|
269
|
+
die("SQLite integration not loaded " . get_class($wpdb));
|
|
270
|
+
}
|
|
271
|
+
`)}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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wp-playground/wordpress",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.1",
|
|
4
4
|
"description": "WordPress-related plumbing for WordPress Playground",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -27,8 +27,5 @@
|
|
|
27
27
|
"access": "public",
|
|
28
28
|
"directory": "../../../dist/packages/playground/wordpress"
|
|
29
29
|
},
|
|
30
|
-
"
|
|
31
|
-
"@php-wasm/universal": "^0.6.6"
|
|
32
|
-
},
|
|
33
|
-
"gitHead": "687ec237085853ff5c808814c28be349146a5d1a"
|
|
30
|
+
"gitHead": "1097764159c71f5fd9f215f46385d1c83428fe01"
|
|
34
31
|
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { PHPRequestHandler } from '../../../php-wasm/universal/src/index.ts';
|
|
2
|
+
export declare function getLoadedWordPressVersion(requestHandler: PHPRequestHandler): Promise<string>;
|
|
3
|
+
export declare function versionStringToLoadedWordPressVersion(wpVersionString: string): string;
|
|
4
|
+
export declare function isSupportedWordPressVersion(wpVersion: string): boolean;
|