@wp-playground/cli 3.1.0 → 3.1.2

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.
@@ -1,7 +1,7 @@
1
- "use strict";const f=require("@php-wasm/logger"),P=require("@php-wasm/universal"),$=require("@wp-playground/blueprints"),B=require("@wp-playground/common"),c=require("fs"),H=require("worker_threads"),fe=require("@php-wasm/node"),d=require("path"),we=require("express"),F=require("os"),ye=require("yargs"),U=require("@wp-playground/storage"),ee=require("@php-wasm/progress"),be=require("@wp-playground/wordpress"),E=require("fs-extra"),ge=require("module"),Pe=require("@php-wasm/xdebug-bridge"),ve=require("child_process"),te=require("tmp-promise"),Se=require("ps-man"),W=require("@php-wasm/cli-util"),xe=require("crypto"),_=require("@wp-playground/tools"),re=require("wasm-feature-detect");var T=typeof document<"u"?document.currentScript:null;const Ie=2**31-1;class Te{constructor(t=1,r=Ie){this.claimed=new Set,this.initialId=t,this.maxId=r,this.nextId=t}claim(){const t=this.maxId-this.initialId+1;for(let r=0;r<t;r++)if(this.claimed.has(this.nextId))this.nextId++,this.nextId>this.maxId&&(this.nextId=this.initialId);else return this.claimed.add(this.nextId),this.nextId;throw new Error(`Unable to find free process ID after ${t} tries.`)}release(t){return this.claimed.has(t)?(this.claimed.delete(t),!0):!1}}function q(e){const t=[];for(const r of e){const o=r.split(":");if(o.length!==2)throw new Error(`Invalid mount format: ${r}.
1
+ "use strict";const w=require("@php-wasm/logger"),P=require("@php-wasm/universal"),$=require("@wp-playground/blueprints"),B=require("@wp-playground/common"),c=require("fs"),_=require("worker_threads"),fe=require("@php-wasm/node"),d=require("path"),we=require("express"),ye=require("stream"),be=require("stream/promises"),H=require("os"),ge=require("yargs"),L=require("@wp-playground/storage"),ee=require("@php-wasm/progress"),Pe=require("@wp-playground/wordpress"),E=require("fs-extra"),ve=require("module"),Se=require("@php-wasm/xdebug-bridge"),xe=require("child_process"),te=require("tmp-promise"),Ie=require("ps-man"),U=require("@php-wasm/cli-util"),Te=require("crypto"),W=require("@wp-playground/tools"),re=require("wasm-feature-detect");var T=typeof document<"u"?document.currentScript:null;const $e=2**31-1;class Ee{constructor(t=1,r=$e){this.claimed=new Set,this.initialId=t,this.maxId=r,this.nextId=t}claim(){const t=this.maxId-this.initialId+1;for(let r=0;r<t;r++)if(this.claimed.has(this.nextId))this.nextId++,this.nextId>this.maxId&&(this.nextId=this.initialId);else return this.claimed.add(this.nextId),this.nextId;throw new Error(`Unable to find free process ID after ${t} tries.`)}release(t){return this.claimed.has(t)?(this.claimed.delete(t),!0):!1}}function O(e){const t=[];for(const r of e){const o=r.split(":");if(o.length!==2)throw new Error(`Invalid mount format: ${r}.
2
2
  Expected format: /host/path:/vfs/path.
3
3
  If your path contains a colon, e.g. C:\\myplugin, use the --mount-dir option instead.
4
- Example: --mount-dir C:\\my-plugin /wordpress/wp-content/plugins/my-plugin`);const[s,n]=o;if(!c.existsSync(s))throw new Error(`Host path does not exist: ${s}`);t.push({hostPath:s,vfsPath:n})}return t}function oe(e){if(e.length%2!==0)throw new Error("Invalid mount format. Expected: /host/path /vfs/path");const t=[];for(let r=0;r<e.length;r+=2){const o=e[r],s=e[r+1];if(!c.existsSync(o))throw new Error(`Host path does not exist: ${o}`);t.push({hostPath:d.resolve(process.cwd(),o),vfsPath:s})}return t}async function $e(e,t){for(const r of t)await e.mount(r.vfsPath,fe.createNodeFsMountHandler(r.hostPath))}const se={step:"runPHP",code:{filename:"activate-theme.php",content:`<?php
4
+ Example: --mount-dir C:\\my-plugin /wordpress/wp-content/plugins/my-plugin`);const[s,n]=o;if(!c.existsSync(s))throw new Error(`Host path does not exist: ${s}`);t.push({hostPath:s,vfsPath:n})}return t}function oe(e){if(e.length%2!==0)throw new Error("Invalid mount format. Expected: /host/path /vfs/path");const t=[];for(let r=0;r<e.length;r+=2){const o=e[r],s=e[r+1];if(!c.existsSync(o))throw new Error(`Host path does not exist: ${o}`);t.push({hostPath:d.resolve(process.cwd(),o),vfsPath:s})}return t}async function ke(e,t){for(const r of t)await e.mount(r.vfsPath,fe.createNodeFsMountHandler(r.hostPath))}const se={step:"runPHP",code:{filename:"activate-theme.php",content:`<?php
5
5
  $docroot = getenv('DOCROOT') ? getenv('DOCROOT') : '/wordpress';
6
6
  require_once "$docroot/wp-load.php";
7
7
  $theme = wp_get_theme();
@@ -12,9 +12,9 @@
12
12
  switch_theme($themeName);
13
13
  }
14
14
  }
15
- `}};function ae(e){const t=e.autoMount,r=[...e.mount||[]],o=[...e["mount-before-install"]||[]],s={...e,mount:r,"mount-before-install":o,"additional-blueprint-steps":[...e["additional-blueprint-steps"]||[]]};if(Re(t)){const a=`/wordpress/wp-content/plugins/${d.basename(t)}`;r.push({hostPath:t,vfsPath:a,autoMounted:!0}),s["additional-blueprint-steps"].push({step:"activatePlugin",pluginPath:`/wordpress/wp-content/plugins/${d.basename(t)}`})}else if(Me(t)){const n=d.basename(t),a=`/wordpress/wp-content/themes/${n}`;r.push({hostPath:t,vfsPath:a,autoMounted:!0}),s["additional-blueprint-steps"].push(e["experimental-blueprints-v2-runner"]?{step:"activateTheme",themeDirectoryName:n}:{step:"activateTheme",themeFolderName:n})}else if(ke(t)){const n=c.readdirSync(t);for(const a of n)a!=="index.php"&&r.push({hostPath:`${t}/${a}`,vfsPath:`/wordpress/wp-content/${a}`,autoMounted:!0});s["additional-blueprint-steps"].push(se)}else Ee(t)&&(o.push({hostPath:t,vfsPath:"/wordpress",autoMounted:!0}),s.mode="apply-to-existing-site",s["additional-blueprint-steps"].push(se),s.wordpressInstallMode||(s.wordpressInstallMode="install-from-existing-files-if-needed"));return s}function Ee(e){const t=c.readdirSync(e);return t.includes("wp-admin")&&t.includes("wp-includes")&&t.includes("wp-content")}function ke(e){const t=c.readdirSync(e);return t.includes("themes")||t.includes("plugins")||t.includes("mu-plugins")||t.includes("uploads")}function Me(e){if(!c.readdirSync(e).includes("style.css"))return!1;const r=c.readFileSync(d.join(e,"style.css"),"utf8");return!!/^(?:[ \t]*<\?php)?[ \t/*#@]*Theme Name:(.*)$/im.exec(r)}function Re(e){const t=c.readdirSync(e),r=/^(?:[ \t]*<\?php)?[ \t/*#@]*Plugin Name:(.*)$/im;return!!t.filter(s=>s.endsWith(".php")).find(s=>{const n=c.readFileSync(d.join(e,s),"utf8");return!!r.exec(n)})}function Ce(e){if(e.length%2!==0)throw new Error("Invalid constant definition format. Expected pairs of NAME value");const t={};for(let r=0;r<e.length;r+=2){const o=e[r],s=e[r+1];if(!o||!o.trim())throw new Error("Constant name cannot be empty");t[o.trim()]=s}return t}function Be(e){if(e.length%2!==0)throw new Error("Invalid boolean constant definition format. Expected pairs of NAME value");const t={};for(let r=0;r<e.length;r+=2){const o=e[r],s=e[r+1].trim().toLowerCase();if(!o||!o.trim())throw new Error("Constant name cannot be empty");if(s==="true"||s==="1")t[o.trim()]=!0;else if(s==="false"||s==="0")t[o.trim()]=!1;else throw new Error(`Invalid boolean value for constant "${o}": "${s}". Must be "true", "false", "1", or "0".`)}return t}function Ae(e){if(e.length%2!==0)throw new Error("Invalid number constant definition format. Expected pairs of NAME value");const t={};for(let r=0;r<e.length;r+=2){const o=e[r],s=e[r+1].trim();if(!o||!o.trim())throw new Error("Constant name cannot be empty");const n=Number(s);if(isNaN(n))throw new Error(`Invalid number value for constant "${o}": "${s}". Must be a valid number.`);t[o.trim()]=n}return t}function De(e={},t={},r={}){const o={},s=new Set,n=(a,l)=>{for(const u in a){if(s.has(u))throw new Error(`Constant "${u}" is defined multiple times across different --define-${l} flags`);s.add(u),o[u]=a[u]}};return n(e,"string"),n(t,"bool"),n(r,"number"),o}function z(e){return De(e.define,e["define-bool"],e["define-number"])}async function Le(e){const t=we(),r=await new Promise((n,a)=>{const l=t.listen(e.port,()=>{const u=l.address();u===null||typeof u=="string"?a(new Error("Server address is not available")):n(l)})});t.use("/",async(n,a)=>{let l;try{l=await e.handleRequest({url:n.url,headers:We(n),method:n.method,body:await Ue(n)})}catch(u){f.logger.error(u),l=P.PHPResponse.forHttpCode(500)}a.statusCode=l.httpStatusCode;for(const u in l.headers)a.setHeader(u,l.headers[u]);a.end(l.bytes)});const s=r.address().port;return await e.onBind(r,s)}const Ue=async e=>await new Promise(t=>{const r=[];e.on("data",o=>{r.push(o)}),e.on("end",()=>{t(new Uint8Array(Buffer.concat(r)))})}),We=e=>{const t={};if(e.rawHeaders&&e.rawHeaders.length)for(let r=0;r<e.rawHeaders.length;r+=2)t[e.rawHeaders[r].toLowerCase()]=e.rawHeaders[r+1];return t};function _e(e){return/^latest$|^trunk$|^nightly$|^(?:(\d+)\.(\d+)(?:\.(\d+))?)((?:-beta(?:\d+)?)|(?:-RC(?:\d+)?))?$/.test(e)}async function He({sourceString:e,blueprintMayReadAdjacentFiles:t}){if(!e)return;if(e.startsWith("http://")||e.startsWith("https://"))return await $.resolveRemoteBlueprint(e);let r=d.resolve(process.cwd(),e);if(!c.existsSync(r))throw new Error(`Blueprint file does not exist: ${r}`);const o=c.statSync(r);if(o.isDirectory()&&(r=d.join(r,"blueprint.json")),!o.isFile()&&o.isSymbolicLink())throw new Error(`Blueprint path is neither a file nor a directory: ${r}`);const s=d.extname(r);switch(s){case".zip":return U.ZipFilesystem.fromArrayBuffer(c.readFileSync(r).buffer);case".json":{const n=c.readFileSync(r,"utf-8");try{JSON.parse(n)}catch{throw new Error(`Blueprint file at ${r} is not a valid JSON file`)}const a=d.dirname(r),l=new U.NodeJsFilesystem(a);return new U.OverlayFilesystem([new U.InMemoryFilesystem({"blueprint.json":n}),{read(u){if(!t)throw new Error(`Error: Blueprint contained tried to read a local file at path "${u}" (via a resource of type "bundled"). Playground restricts access to local resources by default as a security measure.
15
+ `}};function ae(e){const t=e.autoMount,r=[...e.mount||[]],o=[...e["mount-before-install"]||[]],s={...e,mount:r,"mount-before-install":o,"additional-blueprint-steps":[...e["additional-blueprint-steps"]||[]]};if(Be(t)){const i=`/wordpress/wp-content/plugins/${d.basename(t)}`;r.push({hostPath:t,vfsPath:i,autoMounted:!0}),s["additional-blueprint-steps"].push({step:"activatePlugin",pluginPath:`/wordpress/wp-content/plugins/${d.basename(t)}`})}else if(Ce(t)){const n=d.basename(t),i=`/wordpress/wp-content/themes/${n}`;r.push({hostPath:t,vfsPath:i,autoMounted:!0}),s["additional-blueprint-steps"].push(e["experimental-blueprints-v2-runner"]?{step:"activateTheme",themeDirectoryName:n}:{step:"activateTheme",themeFolderName:n})}else if(Re(t)){const n=c.readdirSync(t);for(const i of n)i!=="index.php"&&r.push({hostPath:`${t}/${i}`,vfsPath:`/wordpress/wp-content/${i}`,autoMounted:!0});s["additional-blueprint-steps"].push(se)}else Me(t)&&(o.push({hostPath:t,vfsPath:"/wordpress",autoMounted:!0}),s.mode="apply-to-existing-site",s["additional-blueprint-steps"].push(se),s.wordpressInstallMode||(s.wordpressInstallMode="install-from-existing-files-if-needed"));return s}function Me(e){const t=c.readdirSync(e);return t.includes("wp-admin")&&t.includes("wp-includes")&&t.includes("wp-content")}function Re(e){const t=c.readdirSync(e);return t.includes("themes")||t.includes("plugins")||t.includes("mu-plugins")||t.includes("uploads")}function Ce(e){if(!c.readdirSync(e).includes("style.css"))return!1;const r=c.readFileSync(d.join(e,"style.css"),"utf8");return!!/^(?:[ \t]*<\?php)?[ \t/*#@]*Theme Name:(.*)$/im.exec(r)}function Be(e){const t=c.readdirSync(e),r=/^(?:[ \t]*<\?php)?[ \t/*#@]*Plugin Name:(.*)$/im;return!!t.filter(s=>s.endsWith(".php")).find(s=>{const n=c.readFileSync(d.join(e,s),"utf8");return!!r.exec(n)})}function Ae(e){if(e.length%2!==0)throw new Error("Invalid constant definition format. Expected pairs of NAME value");const t={};for(let r=0;r<e.length;r+=2){const o=e[r],s=e[r+1];if(!o||!o.trim())throw new Error("Constant name cannot be empty");t[o.trim()]=s}return t}function De(e){if(e.length%2!==0)throw new Error("Invalid boolean constant definition format. Expected pairs of NAME value");const t={};for(let r=0;r<e.length;r+=2){const o=e[r],s=e[r+1].trim().toLowerCase();if(!o||!o.trim())throw new Error("Constant name cannot be empty");if(s==="true"||s==="1")t[o.trim()]=!0;else if(s==="false"||s==="0")t[o.trim()]=!1;else throw new Error(`Invalid boolean value for constant "${o}": "${s}". Must be "true", "false", "1", or "0".`)}return t}function Le(e){if(e.length%2!==0)throw new Error("Invalid number constant definition format. Expected pairs of NAME value");const t={};for(let r=0;r<e.length;r+=2){const o=e[r],s=e[r+1].trim();if(!o||!o.trim())throw new Error("Constant name cannot be empty");const n=Number(s);if(isNaN(n))throw new Error(`Invalid number value for constant "${o}": "${s}". Must be a valid number.`);t[o.trim()]=n}return t}function Ue(e={},t={},r={}){const o={},s=new Set,n=(i,l)=>{for(const u in i){if(s.has(u))throw new Error(`Constant "${u}" is defined multiple times across different --define-${l} flags`);s.add(u),o[u]=i[u]}};return n(e,"string"),n(t,"bool"),n(r,"number"),o}function z(e){return Ue(e.define,e["define-bool"],e["define-number"])}async function We(e){const t=we(),r=await new Promise((n,i)=>{const l=t.listen(e.port,()=>{const u=l.address();u===null||typeof u=="string"?i(new Error("Server address is not available")):n(l)})});t.use("/",async(n,i)=>{try{const l={url:n.url,headers:Fe(n),method:n.method,body:await He(n)},u=await e.handleRequest(l);await _e(u,i)}catch(l){w.logger.error(l),i.headersSent||(i.statusCode=500,i.end("Internal Server Error"))}});const s=r.address().port;return await e.onBind(r,s)}async function _e(e,t){const[r,o]=await Promise.all([e.headers,e.httpStatusCode]);t.statusCode=o;for(const n in r)t.setHeader(n,r[n]);const s=ye.Readable.fromWeb(e.stdout);await be.pipeline(s,t)}const He=async e=>await new Promise(t=>{const r=[];e.on("data",o=>{r.push(o)}),e.on("end",()=>{t(new Uint8Array(Buffer.concat(r)))})}),Fe=e=>{const t={};if(e.rawHeaders&&e.rawHeaders.length)for(let r=0;r<e.rawHeaders.length;r+=2)t[e.rawHeaders[r].toLowerCase()]=e.rawHeaders[r+1];return t};function Ne(e){return/^latest$|^trunk$|^nightly$|^(?:(\d+)\.(\d+)(?:\.(\d+))?)((?:-beta(?:\d+)?)|(?:-RC(?:\d+)?))?$/.test(e)}async function qe({sourceString:e,blueprintMayReadAdjacentFiles:t}){if(!e)return;if(e.startsWith("http://")||e.startsWith("https://"))return await $.resolveRemoteBlueprint(e);let r=d.resolve(process.cwd(),e);if(!c.existsSync(r))throw new Error(`Blueprint file does not exist: ${r}`);const o=c.statSync(r);if(o.isDirectory()&&(r=d.join(r,"blueprint.json")),!o.isFile()&&o.isSymbolicLink())throw new Error(`Blueprint path is neither a file nor a directory: ${r}`);const s=d.extname(r);switch(s){case".zip":return L.ZipFilesystem.fromArrayBuffer(c.readFileSync(r).buffer);case".json":{const n=c.readFileSync(r,"utf-8");try{JSON.parse(n)}catch{throw new Error(`Blueprint file at ${r} is not a valid JSON file`)}const i=d.dirname(r),l=new L.NodeJsFilesystem(i);return new L.OverlayFilesystem([new L.InMemoryFilesystem({"blueprint.json":n}),{read(u){if(!t)throw new Error(`Error: Blueprint contained tried to read a local file at path "${u}" (via a resource of type "bundled"). Playground restricts access to local resources by default as a security measure.
16
16
 
17
- You can allow this Blueprint to read files from the same parent directory by explicitly adding the --blueprint-may-read-adjacent-files option to your command.`);return l.read(u)}}])}default:throw new Error(`Unsupported blueprint file extension: ${s}. Only .zip and .json files are supported.`)}}class Fe{constructor(t,r){this.args=t,this.siteUrl=r.siteUrl,this.phpVersion=t.php,this.cliOutput=r.cliOutput}getWorkerType(){return"v2"}async bootWordPress(t,r){const o={command:this.args.command,siteUrl:this.siteUrl,blueprint:this.args.blueprint,workerPostInstallMountsPort:r};return await t.bootWordPress(o,r),t}async bootRequestHandler({worker:t,fileLockManagerPort:r,nativeInternalDirPath:o}){const s=P.consumeAPI(t.phpPort);await s.useFileLockManager(r);const n={...this.args,phpVersion:this.phpVersion,siteUrl:this.siteUrl,processId:t.processId,trace:this.args.verbosity==="debug",withIntl:this.args.intl,withRedis:this.args.redis,withMemcached:this.args.memcached,withXdebug:!!this.args.xdebug,nativeInternalDirPath:o,mountsBeforeWpInstall:this.args["mount-before-install"]||[],mountsAfterWpInstall:this.args.mount||[],constants:z(this.args)};return await s.bootWorker(n),s}}const Y=d.join(F.homedir(),".wordpress-playground");async function Ne(){const e=typeof __dirname<"u"?__dirname:void 0;let t=d.join(e,"sqlite-database-integration.zip");if(!E.existsSync(t)){const r=ge.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:T&&T.tagName.toUpperCase()==="SCRIPT"&&T.src||new URL("run-cli-CIkDrr7x.cjs",document.baseURI).href),o=d.dirname(r.resolve("@wp-playground/wordpress-builds/package.json"));t=d.join(o,"src","sqlite-database-integration","sqlite-database-integration-trunk.zip")}return new File([await E.readFile(t)],d.basename(t))}async function Oe(e,t,r){const o=d.join(Y,t);return E.existsSync(o)||(E.ensureDirSync(Y),await qe(e,o,r)),le(o)}async function qe(e,t,r){const s=(await r.monitorFetch(fetch(e))).body.getReader(),n=`${t}.partial`,a=E.createWriteStream(n);for(;;){const{done:l,value:u}=await s.read();if(u&&a.write(u),l)break}a.close(),a.closed||await new Promise((l,u)=>{a.on("finish",()=>{E.renameSync(n,t),l(null)}),a.on("error",I=>{E.removeSync(n),u(I)})})}function le(e,t){return new File([E.readFileSync(e)],d.basename(e))}class je{constructor(t,r){this.args=t,this.siteUrl=r.siteUrl,this.cliOutput=r.cliOutput}getWorkerType(){return"v1"}async bootWordPress(t,r){let o,s,n;const a=new ee.EmscriptenDownloadMonitor;if(this.args.wordpressInstallMode==="download-and-install"){let I=!1;a.addEventListener("progress",x=>{if(I)return;const{loaded:p,total:i}=x.detail,w=Math.floor(Math.min(100,100*p/i));I=w===100,this.cliOutput.updateProgress("Downloading WordPress",w)}),o=await be.resolveWordPressRelease(this.args.wp),n=d.join(Y,`prebuilt-wp-content-for-wp-${o.version}.zip`),s=c.existsSync(n)?le(n):await Oe(o.releaseUrl,`${o.version}.zip`,a),f.logger.debug(`Resolved WordPress release URL: ${o?.releaseUrl}`)}let l;this.args.skipSqliteSetup?(f.logger.debug("Skipping SQLite integration plugin setup..."),l=void 0):(this.cliOutput.updateProgress("Preparing SQLite database"),l=await Ne()),this.cliOutput.updateProgress("Booting WordPress");const u=await $.resolveRuntimeConfiguration(this.getEffectiveBlueprint());return await t.bootWordPress({wpVersion:u.wpVersion,siteUrl:this.siteUrl,wordpressInstallMode:this.args.wordpressInstallMode||"download-and-install",wordPressZip:s&&await s.arrayBuffer(),sqliteIntegrationPluginZip:await l?.arrayBuffer(),constants:z(this.args)},r),n&&!this.args["mount-before-install"]&&!c.existsSync(n)&&(this.cliOutput.updateProgress("Caching WordPress for next boot"),c.writeFileSync(n,await B.zipDirectory(t,"/wordpress"))),t}async bootRequestHandler({worker:t,fileLockManagerPort:r,nativeInternalDirPath:o}){const s=P.consumeAPI(t.phpPort);await s.isConnected();const n=await $.resolveRuntimeConfiguration(this.getEffectiveBlueprint());return await s.useFileLockManager(r),await s.bootRequestHandler({phpVersion:n.phpVersion,siteUrl:this.siteUrl,mountsBeforeWpInstall:this.args["mount-before-install"]||[],mountsAfterWpInstall:this.args.mount||[],processId:t.processId,followSymlinks:this.args.followSymlinks===!0,trace:this.args.experimentalTrace===!0,withIntl:this.args.intl,withRedis:this.args.redis,withMemcached:this.args.memcached,withXdebug:!!this.args.xdebug,nativeInternalDirPath:o,pathAliases:this.args.pathAliases}),await s.isReady(),s}async compileInputBlueprint(t){const r=this.getEffectiveBlueprint(),o=new ee.ProgressTracker;let s="",n=!1;return o.addEventListener("progress",a=>{if(n)return;n=a.detail.progress===100;const l=Math.floor(a.detail.progress);s=a.detail.caption||s||"Running Blueprint",this.cliOutput.updateProgress(s.trim(),l)}),await $.compileBlueprintV1(r,{progress:o,additionalSteps:t})}getEffectiveBlueprint(){const t=this.args.blueprint;return $.isBlueprintBundle(t)?t:{login:this.args.login,...t||{},preferredVersions:{php:this.args.php??t?.preferredVersions?.php??B.RecommendedPHPVersion,wp:this.args.wp??t?.preferredVersions?.wp??"latest",...t?.preferredVersions||{}}}}}async function Ve(e,t=!0){const o=`${d.basename(process.argv0)}${e}${process.pid}-`,s=await te.dir({prefix:o,unsafeCleanup:!0});return t&&te.setGracefulCleanup(),s}async function Ye(e,t,r){const s=(await ze(e,t,r)).map(n=>new Promise(a=>{c.rm(n,{recursive:!0},l=>{l?f.logger.warn(`Failed to delete stale Playground temp dir: ${n}`,l):f.logger.info(`Deleted stale Playground temp dir: ${n}`),a()})}));await Promise.all(s)}async function ze(e,t,r){try{const o=c.readdirSync(r).map(n=>d.join(r,n)),s=[];for(const n of o)await Ge(e,t,n)&&s.push(n);return s}catch(o){return f.logger.warn(`Failed to find stale Playground temp dirs: ${o}`),[]}}async function Ge(e,t,r){if(!c.lstatSync(r).isDirectory())return!1;const s=d.basename(r);if(!s.includes(e))return!1;const n=s.match(new RegExp(`^(.+)${e}(\\d+)-`));if(!n)return!1;const a={executableName:n[1],pid:n[2]};if(await Qe(a.pid,a.executableName))return!1;const l=Date.now()-t;return c.statSync(r).mtime.getTime()<l}async function Qe(e,t){const[r]=await new Promise((o,s)=>{Se.list({pid:e,name:t,clean:!0},(n,a)=>{n?s(n):o(a)})});return!!r&&r.pid===e&&r.command===t}function ue(e){return process.env.CI==="true"||process.env.CI==="1"||process.env.GITHUB_ACTIONS==="true"||process.env.GITHUB_ACTIONS==="1"||(process.env.TERM||"").toLowerCase()==="dumb"?!1:e?!!e.isTTY:process.stdout.isTTY}class Xe{constructor(t){this.lastProgressLine="",this.progressActive=!1,this.verbosity=t.verbosity,this.writeStream=t.writeStream||process.stdout}get isTTY(){return!!this.writeStream.isTTY}get shouldRender(){return ue(this.writeStream)}get isQuiet(){return this.verbosity==="quiet"}bold(t){return this.isTTY?`\x1B[1m${t}\x1B[0m`:t}dim(t){return this.isTTY?`\x1B[2m${t}\x1B[0m`:t}green(t){return this.isTTY?`\x1B[32m${t}\x1B[0m`:t}cyan(t){return this.isTTY?`\x1B[36m${t}\x1B[0m`:t}yellow(t){return this.isTTY?`\x1B[33m${t}\x1B[0m`:t}red(t){return this.isTTY?`\x1B[31m${t}\x1B[0m`:t}printBanner(){if(this.isQuiet)return;const t=this.bold("WordPress Playground CLI");this.writeStream.write(`
17
+ You can allow this Blueprint to read files from the same parent directory by explicitly adding the --blueprint-may-read-adjacent-files option to your command.`);return l.read(u)}}])}default:throw new Error(`Unsupported blueprint file extension: ${s}. Only .zip and .json files are supported.`)}}class Oe{constructor(t,r){this.args=t,this.siteUrl=r.siteUrl,this.phpVersion=t.php,this.cliOutput=r.cliOutput}getWorkerType(){return"v2"}async bootWordPress(t,r){const o={command:this.args.command,siteUrl:this.siteUrl,blueprint:this.args.blueprint,workerPostInstallMountsPort:r};return await t.bootWordPress(o,r),t}async bootRequestHandler({worker:t,fileLockManagerPort:r,nativeInternalDirPath:o}){const s=P.consumeAPI(t.phpPort);await s.useFileLockManager(r);const n={...this.args,phpVersion:this.phpVersion,siteUrl:this.siteUrl,processId:t.processId,trace:this.args.verbosity==="debug",withIntl:this.args.intl,withRedis:this.args.redis,withMemcached:this.args.memcached,withXdebug:!!this.args.xdebug,nativeInternalDirPath:o,mountsBeforeWpInstall:this.args["mount-before-install"]||[],mountsAfterWpInstall:this.args.mount||[],constants:z(this.args)};return await s.bootWorker(n),s}}const Y=d.join(H.homedir(),".wordpress-playground");async function je(){const e=typeof __dirname<"u"?__dirname:void 0;let t=d.join(e,"sqlite-database-integration.zip");if(!E.existsSync(t)){const r=ve.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:T&&T.tagName.toUpperCase()==="SCRIPT"&&T.src||new URL("run-cli-DoRePwjp.cjs",document.baseURI).href),o=d.dirname(r.resolve("@wp-playground/wordpress-builds/package.json"));t=d.join(o,"src","sqlite-database-integration","sqlite-database-integration-trunk.zip")}return new File([await E.readFile(t)],d.basename(t))}async function Ve(e,t,r){const o=d.join(Y,t);return E.existsSync(o)||(E.ensureDirSync(Y),await Ye(e,o,r)),le(o)}async function Ye(e,t,r){const s=(await r.monitorFetch(fetch(e))).body.getReader(),n=`${t}.partial`,i=E.createWriteStream(n);for(;;){const{done:l,value:u}=await s.read();if(u&&i.write(u),l)break}i.close(),i.closed||await new Promise((l,u)=>{i.on("finish",()=>{E.renameSync(n,t),l(null)}),i.on("error",I=>{E.removeSync(n),u(I)})})}function le(e,t){return new File([E.readFileSync(e)],d.basename(e))}class ze{constructor(t,r){this.args=t,this.siteUrl=r.siteUrl,this.cliOutput=r.cliOutput}getWorkerType(){return"v1"}async bootWordPress(t,r){let o,s,n;const i=new ee.EmscriptenDownloadMonitor;if(this.args.wordpressInstallMode==="download-and-install"){let I=!1;i.addEventListener("progress",x=>{if(I)return;const{loaded:p,total:a}=x.detail,m=Math.floor(Math.min(100,100*p/a));I=m===100,this.cliOutput.updateProgress("Downloading WordPress",m)}),o=await Pe.resolveWordPressRelease(this.args.wp),n=d.join(Y,`prebuilt-wp-content-for-wp-${o.version}.zip`),s=c.existsSync(n)?le(n):await Ve(o.releaseUrl,`${o.version}.zip`,i),w.logger.debug(`Resolved WordPress release URL: ${o?.releaseUrl}`)}let l;this.args.skipSqliteSetup?(w.logger.debug("Skipping SQLite integration plugin setup..."),l=void 0):(this.cliOutput.updateProgress("Preparing SQLite database"),l=await je()),this.cliOutput.updateProgress("Booting WordPress");const u=await $.resolveRuntimeConfiguration(this.getEffectiveBlueprint());return await t.bootWordPress({wpVersion:u.wpVersion,siteUrl:this.siteUrl,wordpressInstallMode:this.args.wordpressInstallMode||"download-and-install",wordPressZip:s&&await s.arrayBuffer(),sqliteIntegrationPluginZip:await l?.arrayBuffer(),constants:z(this.args)},r),n&&!this.args["mount-before-install"]&&!c.existsSync(n)&&(this.cliOutput.updateProgress("Caching WordPress for next boot"),c.writeFileSync(n,await B.zipDirectory(t,"/wordpress"))),t}async bootRequestHandler({worker:t,fileLockManagerPort:r,nativeInternalDirPath:o}){const s=P.consumeAPI(t.phpPort);await s.isConnected();const n=await $.resolveRuntimeConfiguration(this.getEffectiveBlueprint());return await s.useFileLockManager(r),await s.bootRequestHandler({phpVersion:n.phpVersion,siteUrl:this.siteUrl,mountsBeforeWpInstall:this.args["mount-before-install"]||[],mountsAfterWpInstall:this.args.mount||[],processId:t.processId,followSymlinks:this.args.followSymlinks===!0,trace:this.args.experimentalTrace===!0,withIntl:this.args.intl,withRedis:this.args.redis,withMemcached:this.args.memcached,withXdebug:!!this.args.xdebug,nativeInternalDirPath:o,pathAliases:this.args.pathAliases}),await s.isReady(),s}async compileInputBlueprint(t){const r=this.getEffectiveBlueprint(),o=new ee.ProgressTracker;let s="",n=!1;return o.addEventListener("progress",i=>{if(n)return;n=i.detail.progress===100;const l=Math.floor(i.detail.progress);s=i.detail.caption||s||"Running Blueprint",this.cliOutput.updateProgress(s.trim(),l)}),await $.compileBlueprintV1(r,{progress:o,additionalSteps:t})}getEffectiveBlueprint(){const t=this.args.blueprint;return $.isBlueprintBundle(t)?t:{login:this.args.login,...t||{},preferredVersions:{php:this.args.php??t?.preferredVersions?.php??B.RecommendedPHPVersion,wp:this.args.wp??t?.preferredVersions?.wp??"latest",...t?.preferredVersions||{}}}}}async function Ge(e,t=!0){const o=`${d.basename(process.argv0)}${e}${process.pid}-`,s=await te.dir({prefix:o,unsafeCleanup:!0});return t&&te.setGracefulCleanup(),s}async function Qe(e,t,r){const s=(await Xe(e,t,r)).map(n=>new Promise(i=>{c.rm(n,{recursive:!0},l=>{l?w.logger.warn(`Failed to delete stale Playground temp dir: ${n}`,l):w.logger.info(`Deleted stale Playground temp dir: ${n}`),i()})}));await Promise.all(s)}async function Xe(e,t,r){try{const o=c.readdirSync(r).map(n=>d.join(r,n)),s=[];for(const n of o)await Ze(e,t,n)&&s.push(n);return s}catch(o){return w.logger.warn(`Failed to find stale Playground temp dirs: ${o}`),[]}}async function Ze(e,t,r){if(!c.lstatSync(r).isDirectory())return!1;const s=d.basename(r);if(!s.includes(e))return!1;const n=s.match(new RegExp(`^(.+)${e}(\\d+)-`));if(!n)return!1;const i={executableName:n[1],pid:n[2]};if(await Ke(i.pid,i.executableName))return!1;const l=Date.now()-t;return c.statSync(r).mtime.getTime()<l}async function Ke(e,t){const[r]=await new Promise((o,s)=>{Ie.list({pid:e,name:t,clean:!0},(n,i)=>{n?s(n):o(i)})});return!!r&&r.pid===e&&r.command===t}function ue(e){return process.env.CI==="true"||process.env.CI==="1"||process.env.GITHUB_ACTIONS==="true"||process.env.GITHUB_ACTIONS==="1"||(process.env.TERM||"").toLowerCase()==="dumb"?!1:e?!!e.isTTY:process.stdout.isTTY}class Je{constructor(t){this.lastProgressLine="",this.progressActive=!1,this.verbosity=t.verbosity,this.writeStream=t.writeStream||process.stdout}get isTTY(){return!!this.writeStream.isTTY}get shouldRender(){return ue(this.writeStream)}get isQuiet(){return this.verbosity==="quiet"}bold(t){return this.isTTY?`\x1B[1m${t}\x1B[0m`:t}dim(t){return this.isTTY?`\x1B[2m${t}\x1B[0m`:t}green(t){return this.isTTY?`\x1B[32m${t}\x1B[0m`:t}cyan(t){return this.isTTY?`\x1B[36m${t}\x1B[0m`:t}yellow(t){return this.isTTY?`\x1B[33m${t}\x1B[0m`:t}red(t){return this.isTTY?`\x1B[31m${t}\x1B[0m`:t}printBanner(){if(this.isQuiet)return;const t=this.bold("WordPress Playground CLI");this.writeStream.write(`
18
18
  ${t}
19
19
 
20
20
  `)}printConfig(t){if(this.isQuiet)return;const r=[];r.push(`${this.dim("PHP")} ${this.cyan(t.phpVersion)} ${this.dim("WordPress")} ${this.cyan(t.wpVersion)}`);const o=[];if(t.intl&&o.push("intl"),t.redis&&o.push("redis"),t.memcached&&o.push("memcached"),t.xdebug&&o.push(this.yellow("xdebug")),o.length>0&&r.push(`${this.dim("Extensions")} ${o.join(", ")}`),t.mounts.length>0)for(const s of t.mounts){const n=s.autoMounted?` ${this.dim("(auto-mount)")}`:"";r.push(`${this.dim("Mount")} ${s.hostPath} ${this.dim("→")} ${s.vfsPath}${n}`)}t.blueprint&&r.push(`${this.dim("Blueprint")} ${t.blueprint}`),this.writeStream.write(r.join(`
@@ -31,8 +31,8 @@ ${this.green("Ready!")} WordPress is running on ${this.bold(t)} ${this.dim(`(${r
31
31
  `)}printWarning(t){this.isQuiet||this.writeStream.write(`${this.yellow("Warning:")} ${t}
32
32
  `)}printPhpMyAdminUrl(t){this.isQuiet||this.writeStream.write(`${this.cyan("phpMyAdmin")} available at ${this.bold(t)}
33
33
 
34
- `)}}const G={Quiet:{name:"quiet",severity:f.LogSeverity.Fatal},Normal:{name:"normal",severity:f.LogSeverity.Info},Debug:{name:"debug",severity:f.LogSeverity.Debug}},Ze=10;async function Ke(e){try{const t={"site-url":{describe:"Site URL to use for WordPress. Defaults to http://127.0.0.1:{port}",type:"string"},php:{describe:"PHP version to use.",type:"string",default:B.RecommendedPHPVersion,choices:P.SupportedPHPVersions},wp:{describe:"WordPress version to use.",type:"string",default:"latest"},define:{describe:'Define PHP string constants (can be used multiple times). Format: NAME value. These constants are set via php.defineConstant() and only exist for the current request. Examples: --define API_KEY secret --define CON=ST "va=lu=e"',type:"string",nargs:2,array:!0,coerce:Ce},"define-bool":{describe:'Define PHP boolean constants (can be used multiple times). Format: NAME value. Value must be "true", "false", "1", or "0". Examples: --define-bool WP_DEBUG true --define-bool MY_FEATURE false',type:"string",nargs:2,array:!0,coerce:Be},"define-number":{describe:"Define PHP number constants (can be used multiple times). Format: NAME value. Examples: --define-number LIMIT 100 --define-number RATE 45.67",type:"string",nargs:2,array:!0,coerce:Ae},mount:{describe:"Mount a directory to the PHP runtime (can be used multiple times). Format: /host/path:/vfs/path",type:"array",string:!0,coerce:q},"mount-before-install":{describe:"Mount a directory to the PHP runtime before WordPress installation (can be used multiple times). Format: /host/path:/vfs/path",type:"array",string:!0,coerce:q},"mount-dir":{describe:'Mount a directory to the PHP runtime (can be used multiple times). Format: "/host/path" "/vfs/path"',type:"array",nargs:2,array:!0,coerce:oe},"mount-dir-before-install":{describe:'Mount a directory before WordPress installation (can be used multiple times). Format: "/host/path" "/vfs/path"',type:"string",nargs:2,array:!0,coerce:oe},login:{describe:"Should log the user in",type:"boolean",default:!1},blueprint:{describe:"Blueprint to execute.",type:"string"},"blueprint-may-read-adjacent-files":{describe:'Consent flag: Allow "bundled" resources in a local blueprint to read files in the same directory as the blueprint file.',type:"boolean",default:!1},"wordpress-install-mode":{describe:"Control how Playground prepares WordPress before booting.",type:"string",default:"download-and-install",choices:["download-and-install","install-from-existing-files","install-from-existing-files-if-needed","do-not-attempt-installing"]},"skip-wordpress-install":{describe:"[Deprecated] Use --wordpress-install-mode instead.",type:"boolean",hidden:!0},"skip-sqlite-setup":{describe:"Skip the SQLite integration plugin setup to allow the WordPress site to use MySQL.",type:"boolean",default:!1},quiet:{describe:"Do not output logs and progress messages.",type:"boolean",default:!1,hidden:!0},verbosity:{describe:"Output logs and progress messages.",type:"string",choices:Object.values(G).map(i=>i.name),default:"normal"},debug:{describe:"Print PHP error log content if an error occurs during Playground boot.",type:"boolean",default:!1,hidden:!0},"auto-mount":{describe:"Automatically mount the specified directory. If no path is provided, mount the current working directory. You can mount a WordPress directory, a plugin directory, a theme directory, a wp-content directory, or any directory containing PHP and HTML files.",type:"string"},"follow-symlinks":{describe:`Allow Playground to follow symlinks by automatically mounting symlinked directories and files encountered in mounted directories.
35
- Warning: Following symlinks will expose files outside mounted directories to Playground and could be a security risk.`,type:"boolean",default:!1},"experimental-trace":{describe:"Print detailed messages about system behavior to the console. Useful for troubleshooting.",type:"boolean",default:!1,hidden:!0},"internal-cookie-store":{describe:"Enable internal cookie handling. When enabled, Playground will manage cookies internally using an HttpCookieStore that persists cookies across requests. When disabled, cookies are handled externally (e.g., by a browser in Node.js environments).",type:"boolean",default:!1},intl:{describe:"Enable Intl.",type:"boolean",default:!0},redis:{describe:"Enable Redis (requires JSPI support).",type:"boolean"},memcached:{describe:"Enable Memcached.",type:"boolean"},xdebug:{describe:"Enable Xdebug.",type:"boolean",default:!1},"experimental-unsafe-ide-integration":{describe:"Enable experimental IDE development tools. This option edits IDE config files to set Xdebug path mappings and web server details. CAUTION: If there are bugs, this feature may break your IDE config files. Please consider backing up your IDE configs before using this feature.",type:"string",choices:["","vscode","phpstorm"],coerce:i=>i===""?["vscode","phpstorm"]:[i]},"experimental-blueprints-v2-runner":{describe:"Use the experimental Blueprint V2 runner.",type:"boolean",default:!1,hidden:!0},mode:{describe:"Blueprints v2 runner mode to use. This option is required when using the --experimental-blueprints-v2-runner flag with a blueprint.",type:"string",choices:["create-new-site","apply-to-existing-site"],hidden:!0},phpmyadmin:{describe:"Install phpMyAdmin for database management. The phpMyAdmin URL will be printed after boot. Optionally specify a custom URL path (default: /phpmyadmin).",type:"string",coerce:i=>i===""?"/phpmyadmin":i}},r={port:{describe:"Port to listen on when serving.",type:"number",default:9400},"experimental-multi-worker":{deprecated:"This option is not needed. Multiple workers are always used.",describe:"Enable experimental multi-worker support which requires a /wordpress directory backed by a real filesystem. Pass a positive number to specify the number of workers to use. Otherwise, default to the number of CPUs minus 1.",type:"number"},"experimental-devtools":{describe:"Enable experimental browser development tools.",type:"boolean"}},o={path:{describe:"Path to the project directory. Playground will auto-detect if this is a plugin, theme, wp-content, or WordPress directory.",type:"string",default:process.cwd()},php:{describe:"PHP version to use.",type:"string",default:B.RecommendedPHPVersion,choices:P.SupportedPHPVersions},wp:{describe:"WordPress version to use.",type:"string",default:"latest"},port:{describe:"Port to listen on.",type:"number",default:9400},blueprint:{describe:"Path to a Blueprint JSON file to execute on startup.",type:"string"},login:{describe:"Auto-login as the admin user.",type:"boolean",default:!0},xdebug:{describe:"Enable Xdebug for debugging.",type:"boolean",default:!1},"experimental-unsafe-ide-integration":t["experimental-unsafe-ide-integration"],"skip-browser":{describe:"Do not open the site in your default browser on startup.",type:"boolean",default:!1},quiet:{describe:"Suppress non-essential output.",type:"boolean",default:!1},"site-url":{describe:"Override the site URL. By default, derived from the port (http://127.0.0.1:<port>).",type:"string"},mount:{describe:"Mount a directory to the PHP runtime (can be used multiple times). Format: /host/path:/vfs/path. Use this for additional mounts beyond auto-detection.",type:"array",string:!0,coerce:q},reset:{describe:"Deletes the stored site directory and starts a new site from scratch.",type:"boolean",default:!1},"no-auto-mount":{describe:"Disable automatic project type detection. Use --mount to manually specify mounts instead.",type:"boolean",default:!1},define:t.define,"define-bool":t["define-bool"],"define-number":t["define-number"],phpmyadmin:t.phpmyadmin},s={outfile:{describe:"When building, write to this output file.",type:"string",default:"wordpress.zip"}},n=ye(e).usage("Usage: wp-playground <command> [options]").command("start","Start a local WordPress server with automatic project detection (recommended)",i=>i.usage(`Usage: wp-playground start [options]
34
+ `)}}const G={Quiet:{name:"quiet",severity:w.LogSeverity.Fatal},Normal:{name:"normal",severity:w.LogSeverity.Info},Debug:{name:"debug",severity:w.LogSeverity.Debug}},et=10;async function tt(e){try{const t={"site-url":{describe:"Site URL to use for WordPress. Defaults to http://127.0.0.1:{port}",type:"string"},php:{describe:"PHP version to use.",type:"string",default:B.RecommendedPHPVersion,choices:P.SupportedPHPVersions},wp:{describe:"WordPress version to use.",type:"string",default:"latest"},define:{describe:'Define PHP string constants (can be used multiple times). Format: NAME value. These constants are set via php.defineConstant() and only exist for the current request. Examples: --define API_KEY secret --define CON=ST "va=lu=e"',type:"string",nargs:2,array:!0,coerce:Ae},"define-bool":{describe:'Define PHP boolean constants (can be used multiple times). Format: NAME value. Value must be "true", "false", "1", or "0". Examples: --define-bool WP_DEBUG true --define-bool MY_FEATURE false',type:"string",nargs:2,array:!0,coerce:De},"define-number":{describe:"Define PHP number constants (can be used multiple times). Format: NAME value. Examples: --define-number LIMIT 100 --define-number RATE 45.67",type:"string",nargs:2,array:!0,coerce:Le},mount:{describe:"Mount a directory to the PHP runtime (can be used multiple times). Format: /host/path:/vfs/path",type:"array",string:!0,coerce:O},"mount-before-install":{describe:"Mount a directory to the PHP runtime before WordPress installation (can be used multiple times). Format: /host/path:/vfs/path",type:"array",string:!0,coerce:O},"mount-dir":{describe:'Mount a directory to the PHP runtime (can be used multiple times). Format: "/host/path" "/vfs/path"',type:"array",nargs:2,array:!0,coerce:oe},"mount-dir-before-install":{describe:'Mount a directory before WordPress installation (can be used multiple times). Format: "/host/path" "/vfs/path"',type:"string",nargs:2,array:!0,coerce:oe},login:{describe:"Should log the user in",type:"boolean",default:!1},blueprint:{describe:"Blueprint to execute.",type:"string"},"blueprint-may-read-adjacent-files":{describe:'Consent flag: Allow "bundled" resources in a local blueprint to read files in the same directory as the blueprint file.',type:"boolean",default:!1},"wordpress-install-mode":{describe:"Control how Playground prepares WordPress before booting.",type:"string",default:"download-and-install",choices:["download-and-install","install-from-existing-files","install-from-existing-files-if-needed","do-not-attempt-installing"]},"skip-wordpress-install":{describe:"[Deprecated] Use --wordpress-install-mode instead.",type:"boolean",hidden:!0},"skip-sqlite-setup":{describe:"Skip the SQLite integration plugin setup to allow the WordPress site to use MySQL.",type:"boolean",default:!1},quiet:{describe:"Do not output logs and progress messages.",type:"boolean",default:!1,hidden:!0},verbosity:{describe:"Output logs and progress messages.",type:"string",choices:Object.values(G).map(a=>a.name),default:"normal"},debug:{describe:"Print PHP error log content if an error occurs during Playground boot.",type:"boolean",default:!1,hidden:!0},"auto-mount":{describe:"Automatically mount the specified directory. If no path is provided, mount the current working directory. You can mount a WordPress directory, a plugin directory, a theme directory, a wp-content directory, or any directory containing PHP and HTML files.",type:"string"},"follow-symlinks":{describe:`Allow Playground to follow symlinks by automatically mounting symlinked directories and files encountered in mounted directories.
35
+ Warning: Following symlinks will expose files outside mounted directories to Playground and could be a security risk.`,type:"boolean",default:!1},"experimental-trace":{describe:"Print detailed messages about system behavior to the console. Useful for troubleshooting.",type:"boolean",default:!1,hidden:!0},"internal-cookie-store":{describe:"Enable internal cookie handling. When enabled, Playground will manage cookies internally using an HttpCookieStore that persists cookies across requests. When disabled, cookies are handled externally (e.g., by a browser in Node.js environments).",type:"boolean",default:!1},intl:{describe:"Enable Intl.",type:"boolean",default:!0},redis:{describe:"Enable Redis (requires JSPI support).",type:"boolean"},memcached:{describe:"Enable Memcached.",type:"boolean"},xdebug:{describe:"Enable Xdebug.",type:"boolean",default:!1},"experimental-unsafe-ide-integration":{describe:"Enable experimental IDE development tools. This option edits IDE config files to set Xdebug path mappings and web server details. CAUTION: If there are bugs, this feature may break your IDE config files. Please consider backing up your IDE configs before using this feature.",type:"string",choices:["","vscode","phpstorm"],coerce:a=>a===""?["vscode","phpstorm"]:[a]},"experimental-blueprints-v2-runner":{describe:"Use the experimental Blueprint V2 runner.",type:"boolean",default:!1,hidden:!0},mode:{describe:"Blueprints v2 runner mode to use. This option is required when using the --experimental-blueprints-v2-runner flag with a blueprint.",type:"string",choices:["create-new-site","apply-to-existing-site"],hidden:!0},phpmyadmin:{describe:"Install phpMyAdmin for database management. The phpMyAdmin URL will be printed after boot. Optionally specify a custom URL path (default: /phpmyadmin).",type:"string",coerce:a=>a===""?"/phpmyadmin":a}},r={port:{describe:"Port to listen on when serving.",type:"number",default:9400},"experimental-multi-worker":{deprecated:"This option is not needed. Multiple workers are always used.",describe:"Enable experimental multi-worker support which requires a /wordpress directory backed by a real filesystem. Pass a positive number to specify the number of workers to use. Otherwise, default to the number of CPUs minus 1.",type:"number"},"experimental-devtools":{describe:"Enable experimental browser development tools.",type:"boolean"}},o={path:{describe:"Path to the project directory. Playground will auto-detect if this is a plugin, theme, wp-content, or WordPress directory.",type:"string",default:process.cwd()},php:{describe:"PHP version to use.",type:"string",default:B.RecommendedPHPVersion,choices:P.SupportedPHPVersions},wp:{describe:"WordPress version to use.",type:"string",default:"latest"},port:{describe:"Port to listen on.",type:"number",default:9400},blueprint:{describe:"Path to a Blueprint JSON file to execute on startup.",type:"string"},login:{describe:"Auto-login as the admin user.",type:"boolean",default:!0},xdebug:{describe:"Enable Xdebug for debugging.",type:"boolean",default:!1},"experimental-unsafe-ide-integration":t["experimental-unsafe-ide-integration"],"skip-browser":{describe:"Do not open the site in your default browser on startup.",type:"boolean",default:!1},quiet:{describe:"Suppress non-essential output.",type:"boolean",default:!1},"site-url":{describe:"Override the site URL. By default, derived from the port (http://127.0.0.1:<port>).",type:"string"},mount:{describe:"Mount a directory to the PHP runtime (can be used multiple times). Format: /host/path:/vfs/path. Use this for additional mounts beyond auto-detection.",type:"array",string:!0,coerce:O},reset:{describe:"Deletes the stored site directory and starts a new site from scratch.",type:"boolean",default:!1},"no-auto-mount":{describe:"Disable automatic project type detection. Use --mount to manually specify mounts instead.",type:"boolean",default:!1},define:t.define,"define-bool":t["define-bool"],"define-number":t["define-number"],phpmyadmin:t.phpmyadmin},s={outfile:{describe:"When building, write to this output file.",type:"string",default:"wordpress.zip"}},n=ge(e).usage("Usage: wp-playground <command> [options]").command("start","Start a local WordPress server with automatic project detection (recommended)",a=>a.usage(`Usage: wp-playground start [options]
36
36
 
37
37
  The easiest way to run WordPress locally. Automatically detects
38
38
  if your directory contains a plugin, theme, wp-content, or
@@ -43,9 +43,9 @@ Examples:
43
43
  wp-playground start --path=./my-plugin # Start with a specific path
44
44
  wp-playground start --wp=6.7 --php=8.3 # Use specific versions
45
45
  wp-playground start --skip-browser # Skip opening browser
46
- wp-playground start --no-auto-mount # Disable auto-detection`).options(o)).command("server","Start a local WordPress server (advanced, low-level)",i=>i.options({...t,...r})).command("run-blueprint","Execute a Blueprint without starting a server",i=>i.options({...t})).command("build-snapshot","Build a ZIP snapshot of a WordPress site based on a Blueprint",i=>i.options({...t,...s})).demandCommand(1,"Please specify a command").strictCommands().conflicts("experimental-unsafe-ide-integration","experimental-devtools").showHelpOnFail(!1).fail((i,w,b)=>{if(w)throw w;i&&i.includes("Please specify a command")&&(b.showHelp(),console.error(`
47
- `+i),process.exit(1)),console.error(i),process.exit(1)}).strictOptions().check(async i=>{if(i["skip-wordpress-install"]===!0&&(i["wordpress-install-mode"]="do-not-attempt-installing",i.wordpressInstallMode="do-not-attempt-installing"),i.wp!==void 0&&typeof i.wp=="string"&&!_e(i.wp))try{new URL(i.wp)}catch{throw new Error('Unrecognized WordPress version. Please use "latest", a URL, or a numeric version such as "6.2", "6.0.1", "6.2-beta1", or "6.2-RC1"')}const w=i["site-url"];if(typeof w=="string"&&w.trim()!=="")try{new URL(w)}catch{throw new Error(`Invalid site-url "${w}". Please provide a valid URL (e.g., http://localhost:8080 or https://example.com)`)}if(i["auto-mount"]){let b=!1;try{b=c.statSync(i["auto-mount"]).isDirectory()}catch{b=!1}if(!b)throw new Error(`The specified --auto-mount path is not a directory: '${i["auto-mount"]}'.`)}if(i["experimental-blueprints-v2-runner"]===!0)throw new Error("Blueprints v2 are temporarily disabled while we rework their runtime implementation.");if(i.mode!==void 0)throw new Error("The --mode option requires the --experimentalBlueprintsV2Runner flag.");return!0});n.wrap(n.terminalWidth());const a=await n.argv,l=a._[0];["start","run-blueprint","server","build-snapshot"].includes(l)||(n.showHelp(),process.exit(1));const u=a.define||{};!("WP_DEBUG"in u)&&!("WP_DEBUG_LOG"in u)&&!("WP_DEBUG_DISPLAY"in u)&&(u.WP_DEBUG="true",u.WP_DEBUG_LOG="true",u.WP_DEBUG_DISPLAY="true");const I={...a,define:u,command:l,mount:[...a.mount||[],...a["mount-dir"]||[]],"mount-before-install":[...a["mount-before-install"]||[],...a["mount-dir-before-install"]||[]]},x=await de(I);x===void 0&&process.exit(0);const p=(()=>{let i;return async()=>{i===void 0&&(i=x[Symbol.asyncDispose]()),await i,process.exit(0)}})();return process.on("SIGINT",p),process.on("SIGTERM",p),{[Symbol.asyncDispose]:async()=>{process.off("SIGINT",p),process.off("SIGTERM",p),await x[Symbol.asyncDispose]()},[Q]:{cliServer:x}}}catch(t){if(console.error(t),!(t instanceof Error))throw t;if(process.argv.includes("--debug"))P.printDebugDetails(t);else{const o=[];let s=t;do o.push(s.message),s=s.cause;while(s instanceof Error);console.error("\x1B[1m"+o.join(" caused by: ")+"\x1B[0m")}process.exit(1)}}function ne(e,t){return e.find(r=>r.vfsPath.replace(/\/$/,"")===t.replace(/\/$/,""))}const Q=Symbol("playground-cli-testing"),C=e=>process.stdout.isTTY?"\x1B[1m"+e+"\x1B[0m":e,Je=e=>process.stdout.isTTY?"\x1B[31m"+e+"\x1B[0m":e,et=e=>process.stdout.isTTY?`\x1B[2m${e}\x1B[0m`:e,j=e=>process.stdout.isTTY?`\x1B[3m${e}\x1B[0m`:e,ie=e=>process.stdout.isTTY?`\x1B[33m${e}\x1B[0m`:e;async function de(e){let t;const r=e.internalCookieStore?new P.HttpCookieStore:void 0,o=[],s=new Map;if(e.command==="start"&&(e=tt(e)),e.autoMount!==void 0&&(e.autoMount===""&&(e={...e,autoMount:process.cwd()}),e=ae(e)),e.wordpressInstallMode===void 0&&(e.wordpressInstallMode="download-and-install"),e.quiet&&(e.verbosity="quiet",delete e.quiet),e.debug&&(e.verbosity="debug",delete e.debug),e.verbosity){const p=Object.values(G).find(i=>i.name===e.verbosity).severity;f.logger.setSeverityFilterLevel(p)}if(e.intl||(e.intl=!0),e.redis===void 0&&(e.redis=await re.jspi()),e.memcached===void 0&&(e.memcached=await re.jspi()),e.phpmyadmin){if(e.phpmyadmin===!0&&(e.phpmyadmin="/phpmyadmin"),e.skipSqliteSetup)throw new Error("--phpmyadmin requires SQLite. Cannot be used with --skip-sqlite-setup.");e.pathAliases=[{urlPrefix:e.phpmyadmin,fsPath:_.PHPMYADMIN_INSTALL_PATH}]}const n=new Xe({verbosity:e.verbosity||"normal"});e.command==="server"&&(n.printBanner(),n.printConfig({phpVersion:e.php||B.RecommendedPHPVersion,wpVersion:e.wp||"latest",port:e.port||9400,xdebug:!!e.xdebug,intl:!!e.intl,redis:!!e.redis,memcached:!!e.memcached,mounts:[...e.mount||[],...e["mount-before-install"]||[]],blueprint:typeof e.blueprint=="string"?e.blueprint:void 0}));const a=e.command==="server"?e.port??9400:0,l=new P.FileLockManagerInMemory;let u=!1,I=!0;const x=await Le({port:a,onBind:async(p,i)=>{const w="127.0.0.1",b=`http://${w}:${i}`,N=e["site-url"]||b,A=Math.max(F.cpus().length-1,Ze),X="-playground-cli-site-",M=await Ve(X);f.logger.debug(`Native temp dir for VFS root: ${M.path}`);const D="WP Playground CLI - Listen for Xdebug",Z=".playground-xdebug-root",K=d.join(process.cwd(),Z);if(await W.removeTempDirSymlink(K),e.xdebug&&e.experimentalUnsafeIdeIntegration){await W.createTempDirSymlink(M.path,K,process.platform);const m={hostPath:d.join(".",d.sep,Z),vfsPath:"/"};try{await W.clearXdebugIDEConfig(D,process.cwd());const y=typeof e.xdebug=="object"?e.xdebug:void 0,h=await W.addXdebugIDEConfig({name:D,host:w,port:i,ides:e.experimentalUnsafeIdeIntegration,cwd:process.cwd(),mounts:[m,...e["mount-before-install"]||[],...e.mount||[]],ideKey:y?.ideKey}),g=e.experimentalUnsafeIdeIntegration,v=g.includes("vscode"),S=g.includes("phpstorm"),k=Object.values(h);console.log(""),k.length>0?(console.log(C("Xdebug configured successfully")),console.log(ie("Updated IDE config: ")+k.join(" ")),console.log(ie("Playground source root: ")+".playground-xdebug-root"+j(et(" – you can set breakpoints and preview Playground's VFS structure in there.")))):(console.log(C("Xdebug configuration failed.")),console.log("No IDE-specific project settings directory was found in the current working directory.")),console.log(""),v&&h.vscode&&(console.log(C("VS Code / Cursor instructions:")),console.log(" 1. Ensure you have installed an IDE extension for PHP Debugging"),console.log(` (The ${C("PHP Debug")} extension by ${C("Xdebug")} has been a solid option)`),console.log(" 2. Open the Run and Debug panel on the left sidebar"),console.log(` 3. Select "${j(D)}" from the dropdown`),console.log(' 3. Click "start debugging"'),console.log(" 5. Set a breakpoint. For example, in .playground-xdebug-root/wordpress/index.php"),console.log(" 6. Visit Playground in your browser to hit the breakpoint"),S&&console.log("")),S&&h.phpstorm&&(console.log(C("PhpStorm instructions:")),console.log(` 1. Choose "${j(D)}" debug configuration in the toolbar`),console.log(" 2. Click the debug button (bug icon)`"),console.log(" 3. Set a breakpoint. For example, in .playground-xdebug-root/wordpress/index.php"),console.log(" 4. Visit Playground in your browser to hit the breakpoint")),console.log("")}catch(y){throw new Error("Could not configure Xdebug",{cause:y})}}const pe=d.dirname(M.path),me=2*24*60*60*1e3;Ye(X,me,pe);const J=d.join(M.path,"internal");c.mkdirSync(J);const he=["wordpress","tools","tmp","home"];for(const m of he){const y=g=>g.vfsPath===`/${m}`;if(!(e["mount-before-install"]?.some(y)||e.mount?.some(y))){const g=d.join(M.path,m);c.mkdirSync(g),e["mount-before-install"]===void 0&&(e["mount-before-install"]=[]),e["mount-before-install"].unshift({vfsPath:`/${m}`,hostPath:g})}}if(e["mount-before-install"])for(const m of e["mount-before-install"])f.logger.debug(`Mount before WP install: ${m.vfsPath} -> ${m.hostPath}`);if(e.mount)for(const m of e.mount)f.logger.debug(`Mount after WP install: ${m.vfsPath} -> ${m.hostPath}`);let R;e["experimental-blueprints-v2-runner"]?R=new Fe(e,{siteUrl:N,cliOutput:n}):(R=new je(e,{siteUrl:N,cliOutput:n}),typeof e.blueprint=="string"&&(e.blueprint=await He({sourceString:e.blueprint,blueprintMayReadAdjacentFiles:e["blueprint-may-read-adjacent-files"]===!0})));let O=!1;const L=async function(){O||(O=!0,await Promise.all(o.map(async y=>{await s.get(y)?.dispose(),await y.worker.terminate()})),p&&await new Promise(y=>{p.close(y),p.closeAllConnections()}),await M.cleanup())};try{const m=[],y=R.getWorkerType();for(let h=0;h<A;h++){const g=ce(y,{onExit:v=>{O||v===0&&f.logger.error(`Worker ${h} exited with code ${v}
48
- `)}}).then(async v=>{o.push(v);const S=await rt(l),k=await R.bootRequestHandler({worker:v,fileLockManagerPort:S,nativeInternalDirPath:J});return s.set(v,k),[v,k]});m.push(g),h===0&&await g}await Promise.all(m),t=P.createObjectPoolProxy(o.map(h=>s.get(h)));{const h=new H.MessageChannel,g=h.port1,v=h.port2;if(await P.exposeAPI({applyPostInstallMountsToAllWorkers:async()=>{await Promise.all(Array.from(s.values()).map(S=>S.mountAfterWordPressInstall(e.mount||[])))}},void 0,g),await R.bootWordPress(t,v),g.close(),u=!0,!e["experimental-blueprints-v2-runner"]){const S=await R.compileInputBlueprint(e["additional-blueprint-steps"]||[]);S&&await $.runBlueprintV1Steps(S,t)}if(e.phpmyadmin&&!await t.fileExists(`${_.PHPMYADMIN_INSTALL_PATH}/index.php`)){const S=await _.getPhpMyAdminInstallSteps(),k=await $.compileBlueprintV1({steps:S});await $.runBlueprintV1Steps(k,t)}if(e.command==="build-snapshot"){await st(t,e.outfile),n.printStatus(`Exported to ${e.outfile}`),await L();return}else if(e.command==="run-blueprint"){n.finishProgress("Done"),await L();return}}if(n.finishProgress(),n.printReady(b,A),n.finishProgress(),n.printReady(b,A),e.phpmyadmin){const h=d.join(e.phpmyadmin,_.PHPMYADMIN_ENTRY_PATH);n.printPhpMyAdminUrl(new URL(h,b).toString())}return e.xdebug&&e.experimentalDevtools&&(await Pe.startBridge({phpInstance:t,phpRoot:"/wordpress"})).start(),{playground:t,server:p,serverUrl:b,[Symbol.asyncDispose]:L,[Q]:{workerThreadCount:A}}}catch(m){if(e.verbosity!=="debug")throw m;let y="";throw await t?.fileExists(f.errorLogPath)&&(y=await t.readFileAsText(f.errorLogPath)),await L(),new Error(y,{cause:m})}},async handleRequest(p){if(!u)return P.PHPResponse.forHttpCode(502,"WordPress is not ready yet");if(I){I=!1;const w={"Content-Type":["text/plain"],"Content-Length":["0"],Location:[p.url]};return p.headers?.cookie?.includes("playground_auto_login_already_happened")&&(w["Set-Cookie"]=["playground_auto_login_already_happened=1; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/"]),new P.PHPResponse(302,w,new Uint8Array)}r&&(p={...p,headers:{...p.headers,cookie:r.getCookieRequestHeader()}});const i=await t.request(p);return r&&(r.rememberCookiesFromResponseHeaders(i.headers),delete i.headers["set-cookie"]),i}});return x&&e.command==="start"&&!e.skipBrowser&&ot(x.serverUrl),x}function tt(e){let t={...e,command:"server"};e.noAutoMount||(t.autoMount=d.resolve(process.cwd(),t.path??""),t=ae(t),delete t.autoMount);const r=ne(t["mount-before-install"]||[],"/wordpress")||ne(t.mount||[],"/wordpress");if(r)console.log("Site files stored at:",r?.hostPath),e.reset&&(console.log(""),console.log(Je("This site is not managed by Playground CLI and cannot be reset.")),console.log("(It's not stored in the ~/.wordpress-playground/sites/<site-id> directory.)"),console.log(""),console.log("You may still remove the site's directory manually if you wish."),process.exit(1));else{const o=t.autoMount||process.cwd(),s=xe.createHash("sha256").update(o).digest("hex"),n=F.homedir(),a=d.join(n,".wordpress-playground/sites",s);console.log("Site files stored at:",a),c.existsSync(a)&&e.reset&&(console.log("Resetting site..."),c.rmdirSync(a,{recursive:!0})),c.mkdirSync(a,{recursive:!0}),t["mount-before-install"]=[...t["mount-before-install"]||[],{vfsPath:"/wordpress",hostPath:a}],t.wordpressInstallMode=c.readdirSync(a).length===0?"download-and-install":"install-from-existing-files-if-needed"}return t}const V=new Te;function ce(e,{onExit:t}={}){let r;return e==="v1"?r=new H.Worker(new URL("./worker-thread-v1.cjs",typeof document>"u"?require("url").pathToFileURL(__filename).href:T&&T.tagName.toUpperCase()==="SCRIPT"&&T.src||new URL("run-cli-CIkDrr7x.cjs",document.baseURI).href)):r=new H.Worker(new URL("./worker-thread-v2.cjs",typeof document>"u"?require("url").pathToFileURL(__filename).href:T&&T.tagName.toUpperCase()==="SCRIPT"&&T.src||new URL("run-cli-CIkDrr7x.cjs",document.baseURI).href)),new Promise((o,s)=>{const n=V.claim();r.once("message",function(l){l.command==="worker-script-initialized"&&o({processId:n,worker:r,phpPort:l.phpPort})}),r.once("error",function(l){V.release(n),console.error(l);const u=new Error(`Worker failed to load worker. ${l.message?`Original error: ${l.message}`:""}`);s(u)});let a=!1;r.once("spawn",()=>{a=!0}),r.once("exit",l=>{V.release(n),a||s(new Error(`Worker exited before spawning: ${l}`)),t?.(l)})})}async function rt(e){const{port1:t,port2:r}=new H.MessageChannel;return await P.exposeSyncAPI(e,t),r}function ot(e){const t=F.platform();let r;switch(t){case"darwin":r=`open "${e}"`;break;case"win32":r=`start "" "${e}"`;break;default:r=`xdg-open "${e}"`;break}ve.exec(r,o=>{o&&f.logger.debug(`Could not open browser: ${o.message}`)})}async function st(e,t){await e.run({code:`<?php
46
+ wp-playground start --no-auto-mount # Disable auto-detection`).options(o)).command("server","Start a local WordPress server (advanced, low-level)",a=>a.options({...t,...r})).command("run-blueprint","Execute a Blueprint without starting a server",a=>a.options({...t})).command("build-snapshot","Build a ZIP snapshot of a WordPress site based on a Blueprint",a=>a.options({...t,...s})).demandCommand(1,"Please specify a command").strictCommands().conflicts("experimental-unsafe-ide-integration","experimental-devtools").showHelpOnFail(!1).fail((a,m,b)=>{if(m)throw m;a&&a.includes("Please specify a command")&&(b.showHelp(),console.error(`
47
+ `+a),process.exit(1)),console.error(a),process.exit(1)}).strictOptions().check(async a=>{if(a["skip-wordpress-install"]===!0&&(a["wordpress-install-mode"]="do-not-attempt-installing",a.wordpressInstallMode="do-not-attempt-installing"),a.wp!==void 0&&typeof a.wp=="string"&&!Ne(a.wp))try{new URL(a.wp)}catch{throw new Error('Unrecognized WordPress version. Please use "latest", a URL, or a numeric version such as "6.2", "6.0.1", "6.2-beta1", or "6.2-RC1"')}const m=a["site-url"];if(typeof m=="string"&&m.trim()!=="")try{new URL(m)}catch{throw new Error(`Invalid site-url "${m}". Please provide a valid URL (e.g., http://localhost:8080 or https://example.com)`)}if(a["auto-mount"]){let b=!1;try{b=c.statSync(a["auto-mount"]).isDirectory()}catch{b=!1}if(!b)throw new Error(`The specified --auto-mount path is not a directory: '${a["auto-mount"]}'.`)}if(a["experimental-blueprints-v2-runner"]===!0)throw new Error("Blueprints v2 are temporarily disabled while we rework their runtime implementation.");if(a.mode!==void 0)throw new Error("The --mode option requires the --experimentalBlueprintsV2Runner flag.");return!0});n.wrap(n.terminalWidth());const i=await n.argv,l=i._[0];["start","run-blueprint","server","build-snapshot"].includes(l)||(n.showHelp(),process.exit(1));const u=i.define||{};!("WP_DEBUG"in u)&&!("WP_DEBUG_LOG"in u)&&!("WP_DEBUG_DISPLAY"in u)&&(u.WP_DEBUG="true",u.WP_DEBUG_LOG="true",u.WP_DEBUG_DISPLAY="true");const I={...i,define:u,command:l,mount:[...i.mount||[],...i["mount-dir"]||[]],"mount-before-install":[...i["mount-before-install"]||[],...i["mount-dir-before-install"]||[]]},x=await de(I);x===void 0&&process.exit(0);const p=(()=>{let a;return async()=>{a===void 0&&(a=x[Symbol.asyncDispose]()),await a,process.exit(0)}})();return process.on("SIGINT",p),process.on("SIGTERM",p),{[Symbol.asyncDispose]:async()=>{process.off("SIGINT",p),process.off("SIGTERM",p),await x[Symbol.asyncDispose]()},[Q]:{cliServer:x}}}catch(t){if(console.error(t),!(t instanceof Error))throw t;if(process.argv.includes("--debug"))P.printDebugDetails(t);else{const o=[];let s=t;do o.push(s.message),s=s.cause;while(s instanceof Error);console.error("\x1B[1m"+o.join(" caused by: ")+"\x1B[0m")}process.exit(1)}}function ne(e,t){return e.find(r=>r.vfsPath.replace(/\/$/,"")===t.replace(/\/$/,""))}const Q=Symbol("playground-cli-testing"),C=e=>process.stdout.isTTY?"\x1B[1m"+e+"\x1B[0m":e,rt=e=>process.stdout.isTTY?"\x1B[31m"+e+"\x1B[0m":e,ot=e=>process.stdout.isTTY?`\x1B[2m${e}\x1B[0m`:e,j=e=>process.stdout.isTTY?`\x1B[3m${e}\x1B[0m`:e,ie=e=>process.stdout.isTTY?`\x1B[33m${e}\x1B[0m`:e;async function de(e){let t;const r=e.internalCookieStore?new P.HttpCookieStore:void 0,o=[],s=new Map;if(e.command==="start"&&(e=st(e)),e.autoMount!==void 0&&(e.autoMount===""&&(e={...e,autoMount:process.cwd()}),e=ae(e)),e.wordpressInstallMode===void 0&&(e.wordpressInstallMode="download-and-install"),e.quiet&&(e.verbosity="quiet",delete e.quiet),e.debug&&(e.verbosity="debug",delete e.debug),e.verbosity){const p=Object.values(G).find(a=>a.name===e.verbosity).severity;w.logger.setSeverityFilterLevel(p)}if(e.intl||(e.intl=!0),e.redis===void 0&&(e.redis=await re.jspi()),e.memcached===void 0&&(e.memcached=await re.jspi()),e.phpmyadmin){if(e.phpmyadmin===!0&&(e.phpmyadmin="/phpmyadmin"),e.skipSqliteSetup)throw new Error("--phpmyadmin requires SQLite. Cannot be used with --skip-sqlite-setup.");e.pathAliases=[{urlPrefix:e.phpmyadmin,fsPath:W.PHPMYADMIN_INSTALL_PATH}]}const n=new Je({verbosity:e.verbosity||"normal"});e.command==="server"&&(n.printBanner(),n.printConfig({phpVersion:e.php||B.RecommendedPHPVersion,wpVersion:e.wp||"latest",port:e.port||9400,xdebug:!!e.xdebug,intl:!!e.intl,redis:!!e.redis,memcached:!!e.memcached,mounts:[...e.mount||[],...e["mount-before-install"]||[]],blueprint:typeof e.blueprint=="string"?e.blueprint:void 0}));const i=e.command==="server"?e.port??9400:0,l=new P.FileLockManagerInMemory;let u=!1,I=!0;const x=await We({port:i,onBind:async(p,a)=>{const m="127.0.0.1",b=`http://${m}:${a}`,F=e["site-url"]||b,N=Math.max(H.cpus().length-1,et),X="-playground-cli-site-",M=await Ge(X);w.logger.debug(`Native temp dir for VFS root: ${M.path}`);const A="WP Playground CLI - Listen for Xdebug",Z=".playground-xdebug-root",K=d.join(process.cwd(),Z);if(await U.removeTempDirSymlink(K),e.xdebug&&e.experimentalUnsafeIdeIntegration){await U.createTempDirSymlink(M.path,K,process.platform);const h={hostPath:d.join(".",d.sep,Z),vfsPath:"/"};try{await U.clearXdebugIDEConfig(A,process.cwd());const y=typeof e.xdebug=="object"?e.xdebug:void 0,f=await U.addXdebugIDEConfig({name:A,host:m,port:a,ides:e.experimentalUnsafeIdeIntegration,cwd:process.cwd(),mounts:[h,...e["mount-before-install"]||[],...e.mount||[]],ideKey:y?.ideKey}),g=e.experimentalUnsafeIdeIntegration,v=g.includes("vscode"),S=g.includes("phpstorm"),k=Object.values(f);console.log(""),k.length>0?(console.log(C("Xdebug configured successfully")),console.log(ie("Updated IDE config: ")+k.join(" ")),console.log(ie("Playground source root: ")+".playground-xdebug-root"+j(ot(" – you can set breakpoints and preview Playground's VFS structure in there.")))):(console.log(C("Xdebug configuration failed.")),console.log("No IDE-specific project settings directory was found in the current working directory.")),console.log(""),v&&f.vscode&&(console.log(C("VS Code / Cursor instructions:")),console.log(" 1. Ensure you have installed an IDE extension for PHP Debugging"),console.log(` (The ${C("PHP Debug")} extension by ${C("Xdebug")} has been a solid option)`),console.log(" 2. Open the Run and Debug panel on the left sidebar"),console.log(` 3. Select "${j(A)}" from the dropdown`),console.log(' 3. Click "start debugging"'),console.log(" 5. Set a breakpoint. For example, in .playground-xdebug-root/wordpress/index.php"),console.log(" 6. Visit Playground in your browser to hit the breakpoint"),S&&console.log("")),S&&f.phpstorm&&(console.log(C("PhpStorm instructions:")),console.log(` 1. Choose "${j(A)}" debug configuration in the toolbar`),console.log(" 2. Click the debug button (bug icon)`"),console.log(" 3. Set a breakpoint. For example, in .playground-xdebug-root/wordpress/index.php"),console.log(" 4. Visit Playground in your browser to hit the breakpoint")),console.log("")}catch(y){throw new Error("Could not configure Xdebug",{cause:y})}}const pe=d.dirname(M.path),me=2*24*60*60*1e3;Qe(X,me,pe);const J=d.join(M.path,"internal");c.mkdirSync(J);const he=["wordpress","tools","tmp","home"];for(const h of he){const y=g=>g.vfsPath===`/${h}`;if(!(e["mount-before-install"]?.some(y)||e.mount?.some(y))){const g=d.join(M.path,h);c.mkdirSync(g),e["mount-before-install"]===void 0&&(e["mount-before-install"]=[]),e["mount-before-install"].unshift({vfsPath:`/${h}`,hostPath:g})}}if(e["mount-before-install"])for(const h of e["mount-before-install"])w.logger.debug(`Mount before WP install: ${h.vfsPath} -> ${h.hostPath}`);if(e.mount)for(const h of e.mount)w.logger.debug(`Mount after WP install: ${h.vfsPath} -> ${h.hostPath}`);let R;e["experimental-blueprints-v2-runner"]?R=new Oe(e,{siteUrl:F,cliOutput:n}):(R=new ze(e,{siteUrl:F,cliOutput:n}),typeof e.blueprint=="string"&&(e.blueprint=await qe({sourceString:e.blueprint,blueprintMayReadAdjacentFiles:e["blueprint-may-read-adjacent-files"]===!0})));let q=!1;const D=async function(){q||(q=!0,await Promise.all(o.map(async y=>{await s.get(y)?.dispose(),await y.worker.terminate()})),p&&await new Promise(y=>{p.close(y),p.closeAllConnections()}),await M.cleanup())};try{const h=[],y=R.getWorkerType();for(let f=0;f<N;f++){const g=ce(y,{onExit:v=>{q||v===0&&w.logger.error(`Worker ${f} exited with code ${v}
48
+ `)}}).then(async v=>{o.push(v);const S=await nt(l),k=await R.bootRequestHandler({worker:v,fileLockManagerPort:S,nativeInternalDirPath:J});return s.set(v,k),[v,k]});h.push(g),f===0&&await g}await Promise.all(h),t=P.createObjectPoolProxy(o.map(f=>s.get(f)));{const f=new _.MessageChannel,g=f.port1,v=f.port2;if(await P.exposeAPI({applyPostInstallMountsToAllWorkers:async()=>{await Promise.all(Array.from(s.values()).map(S=>S.mountAfterWordPressInstall(e.mount||[])))}},void 0,g),await R.bootWordPress(t,v),g.close(),u=!0,!e["experimental-blueprints-v2-runner"]){const S=await R.compileInputBlueprint(e["additional-blueprint-steps"]||[]);S&&await $.runBlueprintV1Steps(S,t)}if(e.phpmyadmin&&!await t.fileExists(`${W.PHPMYADMIN_INSTALL_PATH}/index.php`)){const S=await W.getPhpMyAdminInstallSteps(),k=await $.compileBlueprintV1({steps:S});await $.runBlueprintV1Steps(k,t)}if(e.command==="build-snapshot"){await at(t,e.outfile),n.printStatus(`Exported to ${e.outfile}`),await D();return}else if(e.command==="run-blueprint"){n.finishProgress("Done"),await D();return}}if(n.finishProgress(),n.printReady(b,N),e.phpmyadmin){const f=d.join(e.phpmyadmin,W.PHPMYADMIN_ENTRY_PATH);n.printPhpMyAdminUrl(new URL(f,b).toString())}return e.xdebug&&e.experimentalDevtools&&(await Se.startBridge({phpInstance:t,phpRoot:"/wordpress"})).start(),{playground:t,server:p,serverUrl:b,[Symbol.asyncDispose]:D,[Q]:{workerThreadCount:N}}}catch(h){if(e.verbosity!=="debug")throw h;let y="";throw await t?.fileExists(w.errorLogPath)&&(y=await t.readFileAsText(w.errorLogPath)),await D(),new Error(y,{cause:h})}},async handleRequest(p){if(!u)return P.StreamedPHPResponse.forHttpCode(502,"WordPress is not ready yet");if(I){I=!1;const m={"Content-Type":["text/plain"],"Content-Length":["0"],Location:[p.url]};return p.headers?.cookie?.includes("playground_auto_login_already_happened")&&(m["Set-Cookie"]=["playground_auto_login_already_happened=1; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/"]),P.StreamedPHPResponse.fromPHPResponse(new P.PHPResponse(302,m,new Uint8Array))}r&&(p={...p,headers:{...p.headers,cookie:r.getCookieRequestHeader()}});const a=await t.requestStreamed(p);if(r){const m=await a.headers;r.rememberCookiesFromResponseHeaders(m),delete m["set-cookie"]}return a}});return x&&e.command==="start"&&!e.skipBrowser&&it(x.serverUrl),x}function st(e){let t={...e,command:"server"};e.noAutoMount||(t.autoMount=d.resolve(process.cwd(),t.path??""),t=ae(t),delete t.autoMount);const r=ne(t["mount-before-install"]||[],"/wordpress")||ne(t.mount||[],"/wordpress");if(r)console.log("Site files stored at:",r?.hostPath),e.reset&&(console.log(""),console.log(rt("This site is not managed by Playground CLI and cannot be reset.")),console.log("(It's not stored in the ~/.wordpress-playground/sites/<site-id> directory.)"),console.log(""),console.log("You may still remove the site's directory manually if you wish."),process.exit(1));else{const o=t.autoMount||process.cwd(),s=Te.createHash("sha256").update(o).digest("hex"),n=H.homedir(),i=d.join(n,".wordpress-playground/sites",s);console.log("Site files stored at:",i),c.existsSync(i)&&e.reset&&(console.log("Resetting site..."),c.rmdirSync(i,{recursive:!0})),c.mkdirSync(i,{recursive:!0}),t["mount-before-install"]=[...t["mount-before-install"]||[],{vfsPath:"/wordpress",hostPath:i}],t.wordpressInstallMode=c.readdirSync(i).length===0?"download-and-install":"install-from-existing-files-if-needed"}return t}const V=new Ee;function ce(e,{onExit:t}={}){let r;return e==="v1"?r=new _.Worker(new URL("./worker-thread-v1.cjs",typeof document>"u"?require("url").pathToFileURL(__filename).href:T&&T.tagName.toUpperCase()==="SCRIPT"&&T.src||new URL("run-cli-DoRePwjp.cjs",document.baseURI).href)):r=new _.Worker(new URL("./worker-thread-v2.cjs",typeof document>"u"?require("url").pathToFileURL(__filename).href:T&&T.tagName.toUpperCase()==="SCRIPT"&&T.src||new URL("run-cli-DoRePwjp.cjs",document.baseURI).href)),new Promise((o,s)=>{const n=V.claim();r.once("message",function(l){l.command==="worker-script-initialized"&&o({processId:n,worker:r,phpPort:l.phpPort})}),r.once("error",function(l){V.release(n),console.error(l);const u=new Error(`Worker failed to load worker. ${l.message?`Original error: ${l.message}`:""}`);s(u)});let i=!1;r.once("spawn",()=>{i=!0}),r.once("exit",l=>{V.release(n),i||s(new Error(`Worker exited before spawning: ${l}`)),t?.(l)})})}async function nt(e){const{port1:t,port2:r}=new _.MessageChannel;return await P.exposeSyncAPI(e,t),r}function it(e){const t=H.platform();let r;switch(t){case"darwin":r=`open "${e}"`;break;case"win32":r=`start "" "${e}"`;break;default:r=`xdg-open "${e}"`;break}xe.exec(r,o=>{o&&w.logger.debug(`Could not open browser: ${o.message}`)})}async function at(e,t){await e.run({code:`<?php
49
49
  $zip = new ZipArchive();
50
50
  if(false === $zip->open('/tmp/build.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
51
51
  throw new Exception('Failed to create ZIP');
@@ -62,5 +62,5 @@ Examples:
62
62
  }
63
63
  $zip->close();
64
64
 
65
- `});const r=await e.readFileAsBuffer("/tmp/build.zip");c.writeFileSync(t,r)}exports.LogVerbosity=G;exports.internalsKeyForTesting=Q;exports.mergeDefinedConstants=z;exports.mountResources=$e;exports.parseOptionsAndRunCLI=Ke;exports.runCLI=de;exports.shouldRenderProgress=ue;exports.spawnWorkerThread=ce;
66
- //# sourceMappingURL=run-cli-CIkDrr7x.cjs.map
65
+ `});const r=await e.readFileAsBuffer("/tmp/build.zip");c.writeFileSync(t,r)}exports.LogVerbosity=G;exports.internalsKeyForTesting=Q;exports.mergeDefinedConstants=z;exports.mountResources=ke;exports.parseOptionsAndRunCLI=tt;exports.runCLI=de;exports.shouldRenderProgress=ue;exports.spawnWorkerThread=ce;
66
+ //# sourceMappingURL=run-cli-DoRePwjp.cjs.map