@wp-playground/cli 3.1.36 → 3.1.38
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/README.md +93 -20
- package/cli.cjs +1 -1
- package/cli.js +1 -1
- package/index.cjs +1 -1
- package/index.js +1 -1
- package/package.json +17 -16
- package/{run-cli-B5GdKs2V.js → run-cli-B6snvP5v.js} +3 -2
- package/{run-cli-B5GdKs2V.js.map → run-cli-B6snvP5v.js.map} +1 -1
- package/{run-cli-BCIvTpD9.cjs → run-cli-CsqeBu36.cjs} +3 -3
- package/{run-cli-BCIvTpD9.cjs.map → run-cli-CsqeBu36.cjs.map} +1 -1
- package/sqlite-database-integration.zip +0 -0
- package/worker-thread-v1.cjs +1 -1
- package/worker-thread-v1.js +1 -1
- package/worker-thread-v2.cjs +1 -1
- package/worker-thread-v2.js +1 -1
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
}
|
|
15
15
|
`}};function he(e){if(typeof e.autoMount!="string")return e;const t=e.autoMount,r=[...e.mount||[]],o=[...e["mount-before-install"]||[]],i={...e,mount:r,"mount-before-install":o,"additional-blueprint-steps":[...e["additional-blueprint-steps"]||[]]};if(Ue(t)){const a=`/wordpress/wp-content/plugins/${d.basename(t)}`;r.push({hostPath:t,vfsPath:a,autoMounted:!0}),i["additional-blueprint-steps"].push({step:"activatePlugin",pluginPath:`/wordpress/wp-content/plugins/${d.basename(t)}`})}else if(Le(t)){const n=d.basename(t),a=`/wordpress/wp-content/themes/${n}`;r.push({hostPath:t,vfsPath:a,autoMounted:!0}),i["additional-blueprint-steps"].push(e["experimental-blueprints-v2-runner"]?{step:"activateTheme",themeDirectoryName:n}:{step:"activateTheme",themeFolderName:n})}else if(De(t)){const n=c.readdirSync(t);for(const a of n)a!=="index.php"&&r.push({hostPath:d.join(t,a),vfsPath:`/wordpress/wp-content/${a}`,autoMounted:!0});i["additional-blueprint-steps"].push(ue)}else Ae(t)&&(o.push({hostPath:t,vfsPath:"/wordpress",autoMounted:!0}),i.mode="apply-to-existing-site",i["additional-blueprint-steps"].push(ue),i.wordpressInstallMode||(i.wordpressInstallMode="install-from-existing-files-if-needed"));return i}function Ae(e){const t=c.readdirSync(e);return t.includes("wp-admin")&&t.includes("wp-includes")&&t.includes("wp-content")}function De(e){const t=c.readdirSync(e);return t.includes("themes")||t.includes("plugins")||t.includes("mu-plugins")||t.includes("uploads")}function Le(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 Ue(e){const t=c.readdirSync(e),r=/^(?:[ \t]*<\?php)?[ \t/*#@]*Plugin Name:(.*)$/im;return!!t.filter(i=>i.endsWith(".php")).find(i=>{const n=c.readFileSync(d.join(e,i),"utf8");return!!r.exec(n)})}function _e(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],i=e[r+1];if(!o||!o.trim())throw new Error("Constant name cannot be empty");t[o.trim()]=i}return t}function He(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],i=e[r+1].trim().toLowerCase();if(!o||!o.trim())throw new Error("Constant name cannot be empty");if(i==="true"||i==="1")t[o.trim()]=!0;else if(i==="false"||i==="0")t[o.trim()]=!1;else throw new Error(`Invalid boolean value for constant "${o}": "${i}". Must be "true", "false", "1", or "0".`)}return t}function We(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],i=e[r+1].trim();if(!o||!o.trim())throw new Error("Constant name cannot be empty");const n=Number(i);if(isNaN(n))throw new Error(`Invalid number value for constant "${o}": "${i}". Must be a valid number.`);t[o.trim()]=n}return t}function Be(e={},t={},r={}){const o={},i=new Set,n=(a,l)=>{for(const u in a){if(i.has(u))throw new Error(`Constant "${u}" is defined multiple times across different --define-${l} flags`);i.add(u),o[u]=a[u]}};return n(e,"string"),n(t,"bool"),n(r,"number"),o}function j(e){return Be(e.define,e["define-bool"],e["define-number"])}const Ne=xe.promisify(pe.exec);function Fe(e){return new Promise(t=>{if(e===0)return t(!1);const r=fe().listen(e);r.once("listening",()=>r.close(()=>t(!1))),r.once("error",o=>t(o.code==="EADDRINUSE"))})}async function Ve(e){const t=fe(),r=await new Promise((a,l)=>{const u=t.listen(e.port,()=>{const f=u.address();f===null||typeof f=="string"?l(new Error("Server address is not available")):a(u)}).once("error",l)});t.use("/",async(a,l)=>{try{const u={url:a.url,headers:ze(a),method:a.method,body:await qe(a)},f=await e.handleRequest(u);await Oe(f,l)}catch(u){p.logger.error(u),l.headersSent||(l.statusCode=500,l.end("Internal Server Error"))}});const i=r.address().port,n=process.env.CODESPACE_NAME;return n&&je(i,n),await e.onBind(r,i)}async function Oe(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 i=Ee.Readable.fromWeb(e.stdout);try{await ke.pipeline(i,t)}catch(n){if(n instanceof Error&&"code"in n&&(n.code==="ERR_STREAM_PREMATURE_CLOSE"||n.code==="ERR_STREAM_UNABLE_TO_PIPE"))return;throw n}}const qe=async e=>await new Promise(t=>{const r=[];e.on("data",o=>{r.push(o)}),e.on("end",()=>{t(new Uint8Array(Buffer.concat(r)))})});async function je(e,t){p.logger.log(`Publishing port ${e}...`);const r=`gh codespace ports visibility ${e}:public -c ${t}`;for(let o=0;o<10;o++)try{await Ne(r);return}catch{await new Promise(i=>setTimeout(i,2e3))}}const ze=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 Ge(e){return/^latest$|^beta$|^trunk$|^nightly$|^(?:(\d+)\.(\d+)(?:\.(\d+))?)((?:-beta(?:\d+)?)|(?:-RC(?:\d+)?))?$/.test(e)}async function Ye({sourceString:e,blueprintMayReadAdjacentFiles:t}){if(!e)return;if(e.startsWith("http://")||e.startsWith("https://"))return await L.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 i=d.extname(r);switch(i){case".zip":return V.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 V.NodeJsFilesystem(a);return new V.OverlayFilesystem([new V.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: ${i}. Only .zip and .json files are supported.`)}}function me(e){const t=[];e.intl&&t.push("intl"),e.redis&&t.push("redis"),e.memcached&&t.push("memcached"),e.xdebug&&t.push(typeof e.xdebug=="object"?{name:"xdebug",options:e.xdebug}:"xdebug");for(const r of e.phpExtension||[])t.push({source:{format:"manifest",manifestUrl:r}});return t}class Qe{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 i=m.consumeAPI(t.phpPort);await i.useFileLockManager(r);const n={...this.args,phpVersion:this.phpVersion,siteUrl:this.siteUrl,processId:t.processId,trace:this.args.verbosity==="debug",extensions:me(this.args),nativeInternalDirPath:o,mountsBeforeWpInstall:this.args["mount-before-install"]||[],mountsAfterWpInstall:this.args.mount||[],constants:j(this.args)};return await i.bootWorker(n),i}}const J=d.join(N.homedir(),".wordpress-playground");async function Xe(e="trunk"){const t=typeof __dirname<"u"?__dirname:void 0;let r=d.join(t,"sqlite-database-integration.zip");if(!U.existsSync(r)){const o=Ce.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:M&&M.tagName.toUpperCase()==="SCRIPT"&&M.src||new URL("run-cli-
|
|
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: ${i}. Only .zip and .json files are supported.`)}}function me(e){const t=[];e.intl&&t.push("intl"),e.redis&&t.push("redis"),e.memcached&&t.push("memcached"),e.xdebug&&t.push(typeof e.xdebug=="object"?{name:"xdebug",options:e.xdebug}:"xdebug");for(const r of e.phpExtension||[])t.push({source:{format:"manifest",manifestUrl:r}});return t}class Qe{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 i=m.consumeAPI(t.phpPort);await i.useFileLockManager(r);const n={...this.args,phpVersion:this.phpVersion,siteUrl:this.siteUrl,processId:t.processId,trace:this.args.verbosity==="debug",extensions:me(this.args),nativeInternalDirPath:o,mountsBeforeWpInstall:this.args["mount-before-install"]||[],mountsAfterWpInstall:this.args.mount||[],constants:j(this.args)};return await i.bootWorker(n),i}}const J=d.join(N.homedir(),".wordpress-playground");async function Xe(e="trunk"){const t=typeof __dirname<"u"?__dirname:void 0;let r=d.join(t,"sqlite-database-integration.zip");if(!U.existsSync(r)){const o=Ce.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:M&&M.tagName.toUpperCase()==="SCRIPT"&&M.src||new URL("run-cli-CsqeBu36.cjs",document.baseURI).href),i=d.dirname(o.resolve("@wp-playground/wordpress-builds/package.json"));r=d.join(i,"src","sqlite-database-integration",`sqlite-database-integration-${e}.zip`)}return new File([await U.readFile(r)],d.basename(r))}async function Ze(e,t,r){const o=d.join(J,t);return U.existsSync(o)||(U.ensureDirSync(J),await Ke(e,o,r)),we(o)}async function Ke(e,t,r){const i=(await r.monitorFetch(fetch(e))).body.getReader(),n=`${t}.partial`,a=U.createWriteStream(n);for(;;){const{done:l,value:u}=await i.read();if(u&&a.write(u),l)break}a.close(),a.closed||await new Promise((l,u)=>{a.on("finish",()=>{U.renameSync(n,t),l(null)}),a.on("error",f=>{U.removeSync(n),u(f)})})}function we(e,t){return new File([U.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,i,n;const a=new ie.EmscriptenDownloadMonitor;if(this.args.wordpressInstallMode==="download-and-install"){let f=!1;a.addEventListener("progress",D=>{if(f)return;const{loaded:k,total:w}=D.detail,I=Math.floor(Math.min(100,100*k/w));f=I===100,this.cliOutput.updateProgress("Downloading WordPress",I)}),o=await $e.resolveWordPressRelease(this.args.wp),n=d.join(J,`prebuilt-wp-content-for-wp-${o.version}.zip`),i=c.existsSync(n)?we(n):await Ze(o.releaseUrl,`${o.version}.zip`,a),p.logger.debug(`Resolved WordPress release URL: ${o?.releaseUrl}`)}let l;if(this.args.skipSqliteSetup)p.logger.debug("Skipping SQLite integration plugin setup..."),l=void 0;else{this.cliOutput.updateProgress("Preparing SQLite database");const f=this.args.php||A.RecommendedPHPVersion,k=m.isLegacyPHPVersion(f)?"v3.0.0-rc.3-php52":"trunk";l=await Xe(k)}this.cliOutput.updateProgress("Booting WordPress");const u=await L.resolveRuntimeConfiguration(this.getEffectiveBlueprint());return await t.bootWordPress({phpVersion:u.phpVersion,wpVersion:u.wpVersion,siteUrl:this.siteUrl,wordpressInstallMode:this.args.wordpressInstallMode||"download-and-install",wordPressZip:i&&await i.arrayBuffer(),sqliteIntegrationPluginZip:await l?.arrayBuffer(),constants:j(this.args)},r),n&&!this.args["mount-before-install"]&&!c.existsSync(n)&&(this.cliOutput.updateProgress("Caching WordPress for next boot"),c.writeFileSync(n,await A.zipDirectory(t,"/wordpress"))),t}async bootRequestHandler({worker:t,fileLockManagerPort:r,nativeInternalDirPath:o}){const i=m.consumeAPI(t.phpPort);await i.isConnected();const n=await L.resolveRuntimeConfiguration(this.getEffectiveBlueprint());return await i.useFileLockManager(r),await i.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,extensions:me(this.args),nativeInternalDirPath:o,pathAliases:this.args.pathAliases}),await i.isReady(),i}async compileInputBlueprint(t){const r=this.getEffectiveBlueprint(),o=new ie.ProgressTracker;let i="",n=!1;return o.addEventListener("progress",a=>{if(n)return;n=a.detail.progress===100;const l=Math.floor(a.detail.progress);i=a.detail.caption||i||"Running Blueprint",this.cliOutput.updateProgress(i.trim(),l)}),await L.compileBlueprintV1(r,{progress:o,additionalSteps:t})}getEffectiveBlueprint(){const t=this.args.blueprint;return L.isBlueprintBundle(t)?t:{login:this.args.login,...t||{},preferredVersions:{php:this.args.php??t?.preferredVersions?.php??A.RecommendedPHPVersion,wp:this.args.wp??t?.preferredVersions?.wp??"latest",...t?.preferredVersions||{}}}}}async function et(e,t=!0){const o=`${d.basename(process.argv0)}${e}${process.pid}-`,i=await se.dir({prefix:o,unsafeCleanup:!0});return t&&se.setGracefulCleanup(),i}async function tt(e,t,r){const i=(await rt(e,t,r)).map(n=>new Promise(a=>{c.rm(n,{recursive:!0},l=>{l?p.logger.warn(`Failed to delete stale Playground temp dir: ${n}`,l):p.logger.info(`Deleted stale Playground temp dir: ${n}`),a()})}));await Promise.all(i)}async function rt(e,t,r){try{const o=c.readdirSync(r).map(n=>d.join(r,n)),i=[];for(const n of o)await nt(e,t,n)&&i.push(n);return i}catch(o){return p.logger.warn(`Failed to find stale Playground temp dirs: ${o}`),[]}}async function nt(e,t,r){if(!c.lstatSync(r).isDirectory())return!1;const i=d.basename(r);if(!i.includes(e))return!1;const n=i.match(new RegExp(`^(.+)${e}(\\d+)-`));if(!n)return!1;const a={executableName:n[1],pid:n[2]};if(ot(a.pid))return!1;const l=Date.now()-t;return c.statSync(r).mtime.getTime()<l}function ot(e,t){try{return process.kill(Number(e),0),!0}catch(r){const o=r,i=o&&typeof o.code=="string"?o.code:void 0;return i==="ESRCH"?!1:i==="EPERM"||i==="EACCES"?(p.logger.debug(`Permission denied while checking if process ${e} exists (code: ${i}).`,r),!0):(p.logger.warn(`Could not determine if process ${e} exists due to unexpected error${i?` (code: ${i})`:""}.`,r),!0)}}function ye(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 it extends R.CLIOutput{constructor(){super(...arguments),this.lastProgressLine="",this.progressActive=!1}get shouldRender(){return ye(this.writeStream)}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 i of t.mounts){const n=i.autoMounted?` ${this.dim("(auto-mount)")}`:"";r.push(`${this.dim("Mount")} ${i.hostPath} ${this.dim("→")} ${i.vfsPath}${n}`)}t.blueprint&&r.push(`${this.dim("Blueprint")} ${t.blueprint}`),this.writeStream.write(r.join(`
|
|
@@ -44,7 +44,7 @@ Examples:
|
|
|
44
44
|
wp-playground start --skip-browser # Skip opening browser
|
|
45
45
|
wp-playground start --no-auto-mount # Disable auto-detection`).options(o)).command("server","Start a local WordPress server (advanced, low-level)",s=>s.options({...t,...r})).command("run-blueprint","Execute a Blueprint without starting a server",s=>s.options({...t})).command("build-snapshot","Build a ZIP snapshot of a WordPress site based on a Blueprint",s=>s.options({...t,...i})).command("php","Run a PHP script",s=>s.options({...t})).demandCommand(1,"Please specify a command").strictCommands().conflicts("experimental-unsafe-ide-integration","experimental-devtools").showHelpOnFail(!1).fail((s,b,g)=>{if(b)throw b;s&&s.includes("Please specify a command")&&(g.showHelp(),console.error(`
|
|
46
46
|
`+s),process.exit(1)),console.error(s),process.exit(1)}).strictOptions().check(async s=>{if(s["skip-wordpress-install"]===!0&&(s["wordpress-install-mode"]="do-not-attempt-installing",s.wordpressInstallMode="do-not-attempt-installing"),s.phpmyadmin&&s["skip-sqlite-setup"])throw new Error("The --phpmyadmin option requires SQLite setup. Remove --skip-sqlite-setup to use phpMyAdmin.");if(s.wp!==void 0&&typeof s.wp=="string"&&!Ge(s.wp))try{new URL(s.wp)}catch{throw new Error('Unrecognized WordPress version. Please use "latest", "beta", "trunk", "nightly", a URL, or a numeric version such as "6.2", "6.0.1", "6.2-beta1", or "6.2-RC1" (see --help for details).')}const b=s["site-url"];if(typeof b=="string"&&b.trim()!=="")try{new URL(b)}catch{throw new Error(`Invalid site-url "${b}". Please provide a valid URL (e.g., http://localhost:8080 or https://example.com)`)}const g=s.autoMount;if(s._[0]!=="start"&&typeof g=="string"&&g){let E=!1;try{E=c.statSync(g).isDirectory()}catch{E=!1}if(!E)throw new Error(`The specified --auto-mount path is not a directory: '${g}'.`)}if(s["experimental-blueprints-v2-runner"]===!0)throw new Error("Blueprints v2 are temporarily disabled while we rework their runtime implementation.");if(s.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","php"].includes(l)||(n.showHelp(),process.exit(1));const u=a.define||{},f=a["define-bool"]||{},D=a["define-number"]||{},k=s=>s in u||s in f||s in D,w=a.php||A.RecommendedPHPVersion;m.isLegacyPHPVersion(w)||(k("WP_DEBUG")||(f.WP_DEBUG=!0),k("WP_DEBUG_LOG")||(f.WP_DEBUG_LOG=!0),k("WP_DEBUG_DISPLAY")||(f.WP_DEBUG_DISPLAY=!1));const $={...a,define:u,"define-bool":f,"define-number":D,command:l,mount:[...a.mount||[],...a["mount-dir"]||[]],"mount-before-install":[...a["mount-before-install"]||[],...a["mount-dir-before-install"]||[]]},T=await re($);T===void 0&&process.exit(0);const _=(()=>{let s;return async()=>{s===void 0&&(s=T[Symbol.asyncDispose]()),await s,process.exit(0)}})();return process.on("SIGINT",_),process.on("SIGTERM",_),{[Symbol.asyncDispose]:async()=>{process.off("SIGINT",_),process.off("SIGTERM",_),await T[Symbol.asyncDispose]()},[G]:{cliServer:T}}}catch(t){console.error(t);const r=process.argv.includes("--debug");if(t instanceof Error)if(r)m.printDebugDetails(t);else{const o=[],i=new Set;let n=t;for(let a=0;n&&a<20;a++){if(i.has(n)){o.push("[Circular error cause]"),n=void 0;break}i.add(n),o.push(ee(n)),n=n.cause instanceof Error?n.cause:void 0}n&&o.push("[Error cause chain truncated]"),console.error("\x1B[1m"+o.join(" caused by: ")+"\x1B[0m")}else console.error("\x1B[1m"+ee(t)+"\x1B[0m");process.exit(1)}}function ee(e){if(e instanceof Error){if(e.message)return e.message;const t=[];e.name&&e.name!=="Error"&&t.push(e.name);const r=e;return r.errno!==void 0&&t.push(`errno: ${r.errno}`),r.code!==void 0&&t.push(`code: ${r.code}`),t.length>0?t.join(" — "):e.stack||String(e)}if(e&&typeof e=="object"){const t=[],r=e;if(r.name&&t.push(String(r.name)),r.message&&t.push(String(r.message)),r.errno!==void 0&&t.push(`errno: ${r.errno}`),t.length>0)return t.join(" — ");try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function ce(e,t){return e.find(r=>r.vfsPath.replace(/\/$/,"")===t.replace(/\/$/,""))}function te(e){const t=Math.max(1,N.cpus().length-1);return e===void 0?Math.min(6,t):e==="auto"?t:e}const G=Symbol("playground-cli-testing");async function re(e){let t;const r=e.internalCookieStore?new m.HttpCookieStore:void 0,o=[],i=new Map,n=new it({verbosity:e.verbosity||"normal"});if(e.command==="start"&&(e=st(e,n)),e.autoMount!==void 0&&(e.autoMount===""&&(e={...e,autoMount:process.cwd()}),e=he(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 w=Object.values(z).find(I=>I.name===e.verbosity).severity;p.logger.setSeverityFilterLevel(w)}e.intl||(e.intl=!0),e.redis===void 0&&(e.redis=await ae.jspi()),e.memcached===void 0&&(e.memcached=await ae.jspi()),m.isLegacyPHPVersion(e.php||A.RecommendedPHPVersion)&&(e.intl=!1,e.redis=!1,e.memcached=!1,e.xdebug=!1),e.phpmyadmin&&(e.phpmyadmin===!0&&(e.phpmyadmin="/phpmyadmin"),e.pathAliases=[{urlPrefix:e.phpmyadmin,fsPath:O.PHPMYADMIN_INSTALL_PATH}]),e.command==="server"&&(n.printBanner(),n.printConfig({phpVersion:e.php||A.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 l=e.command==="server"?e.port??9400:0,u=new m.FileLockManagerInMemory;let f=!1,D=!0;const k=await Ve({port:e.port?e.port:await Fe(l)?0:l,onBind:async(w,I)=>{const $="127.0.0.1",T=`http://${$}:${I}`,_=e["site-url"]||T;e["experimental-multi-worker"]!==void 0&&p.logger.warn("--experimental-multi-worker is deprecated and its value is ignored. Use --workers=<n|auto> instead.");const s=te(e.workers);if(s<6){const h="Running fewer than 6 workers may increase the likelihood of deadlock due to workers blocking on file locks.";e.workers===void 0?p.logger.warn(`The default worker count has been reduced to ${s} because this machine has only ${N.cpus().length} CPU(s). `+h):p.logger.warn(`Worker count (${s}) is below the recommended threshold (6). `+h)}const b="-playground-cli-site-",g=await et(b);p.logger.debug(`Native temp dir for VFS root: ${g.path}`);const E="WP Playground CLI - Listen for Xdebug",Y=".playground-xdebug-root",Q=d.join(process.cwd(),Y);if(await R.removeTempDirSymlink(Q),e.xdebug){const h={hostPath:d.join(".",d.sep,Y),vfsPath:"/"},y=e.php||A.RecommendedPHPVersion;if(m.SupportedPHPVersions.includes(y)&&m.SupportedPHPVersions.indexOf(y)<=m.SupportedPHPVersions.indexOf("8.5"))await R.createTempDirSymlink(g.path,Q,process.platform),e.xdebug=R.makeXdebugConfig({cwd:process.cwd(),mounts:[h,...e["mount-before-install"]||[],...e.mount||[]],pathSkippings:[...R.DEFAULT_PATH_SKIPPINGS]}),n.print(n.bold("Xdebug configured successfully")),n.print(n.highlight("Playground source root: ")+".playground-xdebug-root"+n.italic(n.dim(" – you can set breakpoints and preview Playground's VFS structure in there.")));else if(e.experimentalUnsafeIdeIntegration){await R.createTempDirSymlink(g.path,Q,process.platform);try{await R.clearXdebugIDEConfig(E,process.cwd());const v=typeof e.xdebug=="object"?e.xdebug:{},S=await R.addXdebugIDEConfig({name:E,host:$,port:I,ides:e.experimentalUnsafeIdeIntegration,cwd:process.cwd(),mounts:[h,...e["mount-before-install"]||[],...e.mount||[]],pathSkippings:[...R.DEFAULT_PATH_SKIPPINGS],ideKey:v.ideKey||"WPPLAYGROUNDCLI"}),x=e.experimentalUnsafeIdeIntegration,C=x.includes("vscode"),F=x.includes("phpstorm"),W=Object.values(S);n.print(""),W.length>0?(n.print(n.bold("Xdebug configured successfully")),n.print(n.highlight("Updated IDE config: ")+W.join(" ")),n.print(n.highlight("Playground source root: ")+".playground-xdebug-root"+n.italic(n.dim(" – you can set breakpoints and preview Playground's VFS structure in there.")))):(n.print(n.bold("Xdebug configuration failed.")),n.print("No IDE-specific project settings directory was found in the current working directory.")),n.print(""),C&&S.vscode&&(n.print(n.bold("VS Code / Cursor instructions:")),n.print(" 1. Ensure you have installed an IDE extension for PHP Debugging"),n.print(` (The ${n.bold("PHP Debug")} extension by ${n.bold("Xdebug")} has been a solid option)`),n.print(" 2. Open the Run and Debug panel on the left sidebar"),n.print(` 3. Select "${n.italic(E)}" from the dropdown`),n.print(' 4. Click "start debugging"'),n.print(" 5. Set a breakpoint. For example, in .playground-xdebug-root/wordpress/index.php"),n.print(" 6. Visit Playground in your browser to hit the breakpoint"),F&&n.print("")),F&&S.phpstorm&&(n.print(n.bold("PhpStorm instructions:")),n.print(` 1. Choose "${n.italic(E)}" debug configuration in the toolbar`),n.print(" 2. Click the debug button (bug icon)"),n.print(" 3. Set a breakpoint. For example, in .playground-xdebug-root/wordpress/index.php"),n.print(" 4. Visit Playground in your browser to hit the breakpoint")),n.print("")}catch(v){throw new Error("Could not configure Xdebug",{cause:v})}}}const ge=d.dirname(g.path),Pe=2*24*60*60*1e3;tt(b,Pe,ge);const oe=d.join(g.path,"internal");c.mkdirSync(oe);const ve=["wordpress","tools","tmp","home"];for(const h of ve){const y=v=>v.vfsPath===`/${h}`;if(!(e["mount-before-install"]?.some(y)||e.mount?.some(y))){const v=d.join(g.path,h);c.mkdirSync(v),e["mount-before-install"]===void 0&&(e["mount-before-install"]=[]),e["mount-before-install"].unshift({vfsPath:`/${h}`,hostPath:v})}}if(e["mount-before-install"])for(const h of e["mount-before-install"])p.logger.debug(`Mount before WP install: ${h.vfsPath} -> ${h.hostPath}`);if(e.mount)for(const h of e.mount)p.logger.debug(`Mount after WP install: ${h.vfsPath} -> ${h.hostPath}`);let H;e["experimental-blueprints-v2-runner"]?H=new Qe(e,{siteUrl:_,cliOutput:n}):(H=new Je(e,{siteUrl:_,cliOutput:n}),typeof e.blueprint=="string"&&(e.blueprint=await Ye({sourceString:e.blueprint,blueprintMayReadAdjacentFiles:e["blueprint-may-read-adjacent-files"]===!0})));let X=!1;const B=async function(){X||(X=!0,await Promise.all(o.map(async y=>{await i.get(y)?.dispose(),await y.worker.terminate()})),w&&await new Promise(y=>{w.close(y),w.closeAllConnections()}),await g.cleanup())};try{const h=[],y=H.getWorkerType();for(let P=0;P<s;P++){const v=ne(y,{onExit:S=>{X||S!==0&&p.logger.error(`Worker ${P} exited with code ${S}
|
|
47
|
-
`)}}).then(async S=>{o.push(S);const x=await at(u),C=await H.bootRequestHandler({worker:S,fileLockManagerPort:x,nativeInternalDirPath:oe});return i.set(S,C),[S,C]});h.push(v),P===0&&await v}await Promise.all(h),t=m.createObjectPoolProxy(o.map(P=>i.get(P)));{const P=new q.MessageChannel,v=P.port1,S=P.port2;if(await m.exposeAPI({applyPostInstallMountsToAllWorkers:async()=>{for(const x of i.values())await x.mountAfterWordPressInstall(e.mount||[])}},void 0,v),await H.bootWordPress(t,S),v.close(),f=!0,!e["experimental-blueprints-v2-runner"]){const x=await H.compileInputBlueprint(e["additional-blueprint-steps"]||[]);x&&await L.runBlueprintV1Steps(x,t)}if(e.phpmyadmin&&!await t.fileExists(`${O.PHPMYADMIN_INSTALL_PATH}/index.php`)){const x=await O.getPhpMyAdminInstallSteps(),C=await L.compileBlueprintV1({steps:x});await L.runBlueprintV1Steps(C,t)}if(e.command==="build-snapshot"){await ut(t,e.outfile),n.printStatus(`Exported to ${e.outfile}`),await B();return}else if(e.command==="run-blueprint"){n.finishProgress("Done"),await B();return}else if(e.command==="php"){const x=["/internal/shared/bin/php",...(e._||[]).slice(1)],C=await t.cli(x),[F]=await Promise.all([C.exitCode,C.stdout.pipeTo(new WritableStream({write(W){process.stdout.write(W)}})),C.stderr.pipeTo(new WritableStream({write(W){process.stderr.write(W)}}))]);await B(),process.exit(F)}}if(n.finishProgress(),n.printReady(T,s),e.phpmyadmin){const P=d.join(e.phpmyadmin,O.PHPMYADMIN_ENTRY_PATH);n.printPhpMyAdminUrl(new URL(P,T).toString())}return e.xdebug&&e.experimentalDevtools&&(await Te.startBridge({phpInstance:t,phpRoot:"/wordpress"})).start(),{playground:t,server:w,serverUrl:T,[Symbol.asyncDispose]:B,[G]:{workerThreadCount:s}}}catch(h){if(e.verbosity!=="debug")throw h;let y="";throw await t?.fileExists(p.errorLogPath)&&(y=await t.readFileAsText(p.errorLogPath)),await B(),new Error(y,{cause:h})}},async handleRequest(w){if(!f)return m.StreamedPHPResponse.forHttpCode(502,"WordPress is not ready yet");if(D){D=!1;const $={"Content-Type":["text/plain"],"Content-Length":["0"],Location:[w.url]};return w.headers?.cookie?.includes("playground_auto_login_already_happened")&&($["Set-Cookie"]=["playground_auto_login_already_happened=1; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/"]),m.StreamedPHPResponse.fromPHPResponse(new m.PHPResponse(302,$,new Uint8Array))}r&&(w={...w,headers:{...w.headers,cookie:r.getCookieRequestHeader()}});const I=await t.requestStreamed(w);if(r){const $=await I.headers;r.rememberCookiesFromResponseHeaders($),delete $["set-cookie"]}return I}}).catch(w=>{n.printError(ee(w)),process.exit(1)});return k&&e.command==="start"&&!e.skipBrowser&<(k.serverUrl),k}function st(e,t){let r={...e,command:"server"};const o=e.autoMount!==!1;delete r.autoMount,delete r["auto-mount"],o&&(r.autoMount=d.resolve(process.cwd(),r.path??""),r=he(r),delete r.autoMount);const i=ce(r["mount-before-install"]||[],"/wordpress")||ce(r.mount||[],"/wordpress");if(i)t.print(`Site files stored at: ${i?.hostPath}`),e.reset&&(t.print(""),t.print(t.red("This site is not managed by Playground CLI and cannot be reset.")),t.print("(It's not stored in the ~/.wordpress-playground/sites/<site-id> directory.)"),t.print(""),t.print("You may still remove the site's directory manually if you wish."),process.exit(1));else{const n=r.autoMount||process.cwd(),a=Re.createHash("sha256").update(n).digest("hex"),l=N.homedir(),u=d.join(l,".wordpress-playground/sites",a);t.print(`Site files stored at: ${u}`),c.existsSync(u)&&e.reset&&(t.print("Resetting site..."),c.rmSync(u,{recursive:!0,force:!0})),c.mkdirSync(u,{recursive:!0}),r["mount-before-install"]=[...r["mount-before-install"]||[],{vfsPath:"/wordpress",hostPath:u}],r.wordpressInstallMode=c.readdirSync(u).length===0?"download-and-install":"install-from-existing-files-if-needed"}return r}const K=new m.ProcessIdAllocator;function ne(e,{onExit:t}={}){let r;return e==="v1"?r=new q.Worker(new URL("./worker-thread-v1.cjs",typeof document>"u"?require("url").pathToFileURL(__filename).href:M&&M.tagName.toUpperCase()==="SCRIPT"&&M.src||new URL("run-cli-
|
|
47
|
+
`)}}).then(async S=>{o.push(S);const x=await at(u),C=await H.bootRequestHandler({worker:S,fileLockManagerPort:x,nativeInternalDirPath:oe});return i.set(S,C),[S,C]});h.push(v),P===0&&await v}await Promise.all(h),t=m.createObjectPoolProxy(o.map(P=>i.get(P)));{const P=new q.MessageChannel,v=P.port1,S=P.port2;if(await m.exposeAPI({applyPostInstallMountsToAllWorkers:async()=>{for(const x of i.values())await x.mountAfterWordPressInstall(e.mount||[])}},void 0,v),await H.bootWordPress(t,S),v.close(),f=!0,!e["experimental-blueprints-v2-runner"]){const x=await H.compileInputBlueprint(e["additional-blueprint-steps"]||[]);x&&await L.runBlueprintV1Steps(x,t)}if(e.phpmyadmin&&!await t.fileExists(`${O.PHPMYADMIN_INSTALL_PATH}/index.php`)){const x=await O.getPhpMyAdminInstallSteps(),C=await L.compileBlueprintV1({steps:x});await L.runBlueprintV1Steps(C,t)}if(e.command==="build-snapshot"){await ut(t,e.outfile),n.printStatus(`Exported to ${e.outfile}`),await B();return}else if(e.command==="run-blueprint"){n.finishProgress("Done"),await B();return}else if(e.command==="php"){const x=["/internal/shared/bin/php",...(e._||[]).slice(1)],C=await t.cli(x),[F]=await Promise.all([C.exitCode,C.stdout.pipeTo(new WritableStream({write(W){process.stdout.write(W)}})),C.stderr.pipeTo(new WritableStream({write(W){process.stderr.write(W)}}))]);await B(),process.exit(F)}}if(n.finishProgress(),n.printReady(T,s),e.phpmyadmin){const P=d.join(e.phpmyadmin,O.PHPMYADMIN_ENTRY_PATH);n.printPhpMyAdminUrl(new URL(P,T).toString())}return e.xdebug&&e.experimentalDevtools&&(await Te.startBridge({phpInstance:t,phpRoot:"/wordpress",excludedPaths:["/internal"]})).start(),{playground:t,server:w,serverUrl:T,[Symbol.asyncDispose]:B,[G]:{workerThreadCount:s}}}catch(h){if(e.verbosity!=="debug")throw h;let y="";throw await t?.fileExists(p.errorLogPath)&&(y=await t.readFileAsText(p.errorLogPath)),await B(),new Error(y,{cause:h})}},async handleRequest(w){if(!f)return m.StreamedPHPResponse.forHttpCode(502,"WordPress is not ready yet");if(D){D=!1;const $={"Content-Type":["text/plain"],"Content-Length":["0"],Location:[w.url]};return w.headers?.cookie?.includes("playground_auto_login_already_happened")&&($["Set-Cookie"]=["playground_auto_login_already_happened=1; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/"]),m.StreamedPHPResponse.fromPHPResponse(new m.PHPResponse(302,$,new Uint8Array))}r&&(w={...w,headers:{...w.headers,cookie:r.getCookieRequestHeader()}});const I=await t.requestStreamed(w);if(r){const $=await I.headers;r.rememberCookiesFromResponseHeaders($),delete $["set-cookie"]}return I}}).catch(w=>{n.printError(ee(w)),process.exit(1)});return k&&e.command==="start"&&!e.skipBrowser&<(k.serverUrl),k}function st(e,t){let r={...e,command:"server"};const o=e.autoMount!==!1;delete r.autoMount,delete r["auto-mount"],o&&(r.autoMount=d.resolve(process.cwd(),r.path??""),r=he(r),delete r.autoMount);const i=ce(r["mount-before-install"]||[],"/wordpress")||ce(r.mount||[],"/wordpress");if(i)t.print(`Site files stored at: ${i?.hostPath}`),e.reset&&(t.print(""),t.print(t.red("This site is not managed by Playground CLI and cannot be reset.")),t.print("(It's not stored in the ~/.wordpress-playground/sites/<site-id> directory.)"),t.print(""),t.print("You may still remove the site's directory manually if you wish."),process.exit(1));else{const n=r.autoMount||process.cwd(),a=Re.createHash("sha256").update(n).digest("hex"),l=N.homedir(),u=d.join(l,".wordpress-playground/sites",a);t.print(`Site files stored at: ${u}`),c.existsSync(u)&&e.reset&&(t.print("Resetting site..."),c.rmSync(u,{recursive:!0,force:!0})),c.mkdirSync(u,{recursive:!0}),r["mount-before-install"]=[...r["mount-before-install"]||[],{vfsPath:"/wordpress",hostPath:u}],r.wordpressInstallMode=c.readdirSync(u).length===0?"download-and-install":"install-from-existing-files-if-needed"}return r}const K=new m.ProcessIdAllocator;function ne(e,{onExit:t}={}){let r;return e==="v1"?r=new q.Worker(new URL("./worker-thread-v1.cjs",typeof document>"u"?require("url").pathToFileURL(__filename).href:M&&M.tagName.toUpperCase()==="SCRIPT"&&M.src||new URL("run-cli-CsqeBu36.cjs",document.baseURI).href)):r=new q.Worker(new URL("./worker-thread-v2.cjs",typeof document>"u"?require("url").pathToFileURL(__filename).href:M&&M.tagName.toUpperCase()==="SCRIPT"&&M.src||new URL("run-cli-CsqeBu36.cjs",document.baseURI).href)),new Promise((o,i)=>{const n=K.claim();r.once("message",function(l){l.command==="worker-script-initialized"&&o({processId:n,worker:r,phpPort:l.phpPort})}),r.once("error",function(l){K.release(n),console.error(l);const u=l?.message||(l?String(l):"unknown error"),f=new Error(`Worker failed to load. Original error: ${u}`,{cause:l});i(f)});let a=!1;r.once("spawn",()=>{a=!0}),r.once("exit",l=>{K.release(n),a||i(new Error(`Worker exited before spawning: ${l}`)),t?.(l)})})}async function at(e){const{port1:t,port2:r}=new q.MessageChannel;return await m.exposeSyncAPI(e,t),r}function lt(e){const t=N.platform();let r;switch(t){case"darwin":r=`open "${e}"`;break;case"win32":r=`start "" "${e}"`;break;default:r=`xdg-open "${e}"`;break}pe.exec(r,o=>{o&&p.logger.debug(`Could not open browser: ${o.message}`)})}async function ut(e,t){await e.run({code:`<?php
|
|
48
48
|
$zip = new ZipArchive();
|
|
49
49
|
if(false === $zip->open('/tmp/build.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
|
|
50
50
|
throw new Exception('Failed to create ZIP');
|
|
@@ -62,4 +62,4 @@ Examples:
|
|
|
62
62
|
$zip->close();
|
|
63
63
|
|
|
64
64
|
`});const r=await e.readFileAsBuffer("/tmp/build.zip");c.writeFileSync(t,r)}const dt=Object.freeze(Object.defineProperty({__proto__:null,LogVerbosity:z,internalsKeyForTesting:G,mergeDefinedConstants:j,parseOptionsAndRunCLI:be,resolveWorkerCount:te,runCLI:re,spawnWorkerThread:ne},Symbol.toStringTag,{value:"Module"}));exports.LogVerbosity=z;exports.internalsKeyForTesting=G;exports.mergeDefinedConstants=j;exports.mountResources=Me;exports.parseOptionsAndRunCLI=be;exports.resolveWorkerCount=te;exports.runCLI=re;exports.runCli=dt;exports.shouldRenderProgress=ye;exports.spawnWorkerThread=ne;
|
|
65
|
-
//# sourceMappingURL=run-cli-
|
|
65
|
+
//# sourceMappingURL=run-cli-CsqeBu36.cjs.map
|