@wp-playground/cli 3.0.2 → 3.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/blueprints-v1/blueprints-v1-handler.d.ts +1 -0
- package/cli.cjs +1 -1
- package/cli.js +1 -1
- package/index.cjs +1 -1
- package/index.js +1 -1
- package/package.json +12 -12
- package/{run-cli-B2OOyNez.cjs → run-cli-DdsLZ1X6.cjs} +8 -8
- package/run-cli-DdsLZ1X6.cjs.map +1 -0
- package/{run-cli-8MDZfFdj.js → run-cli-Md2TQOSk.js} +168 -164
- package/run-cli-Md2TQOSk.js.map +1 -0
- package/worker-thread-v1.cjs +2 -2
- package/worker-thread-v1.cjs.map +1 -1
- package/worker-thread-v1.js +36 -36
- package/worker-thread-v1.js.map +1 -1
- package/worker-thread-v2.cjs +2 -2
- package/worker-thread-v2.cjs.map +1 -1
- package/worker-thread-v2.js +13 -13
- package/worker-thread-v2.js.map +1 -1
- package/run-cli-8MDZfFdj.js.map +0 -1
- package/run-cli-B2OOyNez.cjs.map +0 -1
|
@@ -28,5 +28,6 @@ export declare class BlueprintsV1Handler {
|
|
|
28
28
|
nativeInternalDirPath: string;
|
|
29
29
|
}): Promise<import("@php-wasm/universal").RemoteAPI<PlaygroundCliBlueprintV1Worker>>;
|
|
30
30
|
compileInputBlueprint(additionalBlueprintSteps: any[]): Promise<import("@wp-playground/blueprints").CompiledBlueprintV1>;
|
|
31
|
+
private getEffectiveBlueprint;
|
|
31
32
|
writeProgressUpdate(writeStream: NodeJS.WriteStream, message: string, finalUpdate: boolean): void;
|
|
32
33
|
}
|
package/cli.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";const n=require("./run-cli-
|
|
1
|
+
"use strict";const n=require("./run-cli-DdsLZ1X6.cjs");n.parseOptionsAndRunCLI();
|
|
2
2
|
//# sourceMappingURL=cli.cjs.map
|
package/cli.js
CHANGED
package/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./run-cli-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./run-cli-DdsLZ1X6.cjs");exports.LogVerbosity=e.LogVerbosity;exports.parseOptionsAndRunCLI=e.parseOptionsAndRunCLI;exports.runCLI=e.runCLI;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wp-playground/cli",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.4",
|
|
4
4
|
"description": "WordPress Playground CLI",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"bin": {
|
|
35
35
|
"wp-playground-cli": "wp-playground.js"
|
|
36
36
|
},
|
|
37
|
-
"gitHead": "
|
|
37
|
+
"gitHead": "878b2c84eea28790c7e8fc8651cc53d5d829072a",
|
|
38
38
|
"dependencies": {
|
|
39
39
|
"@zip.js/zip.js": "2.7.57",
|
|
40
40
|
"ajv": "8.12.0",
|
|
@@ -59,16 +59,16 @@
|
|
|
59
59
|
"ws": "8.18.1",
|
|
60
60
|
"xml2js": "0.6.2",
|
|
61
61
|
"yargs": "17.7.2",
|
|
62
|
-
"@php-wasm/logger": "3.0.
|
|
63
|
-
"@php-wasm/progress": "3.0.
|
|
64
|
-
"@php-wasm/universal": "3.0.
|
|
65
|
-
"@wp-playground/blueprints": "3.0.
|
|
66
|
-
"@wp-playground/common": "3.0.
|
|
67
|
-
"@wp-playground/wordpress": "3.0.
|
|
68
|
-
"@php-wasm/node": "3.0.
|
|
69
|
-
"@php-wasm/util": "3.0.
|
|
70
|
-
"@wp-playground/storage": "3.0.
|
|
71
|
-
"@php-wasm/xdebug-bridge": "3.0.
|
|
62
|
+
"@php-wasm/logger": "3.0.4",
|
|
63
|
+
"@php-wasm/progress": "3.0.4",
|
|
64
|
+
"@php-wasm/universal": "3.0.4",
|
|
65
|
+
"@wp-playground/blueprints": "3.0.4",
|
|
66
|
+
"@wp-playground/common": "3.0.4",
|
|
67
|
+
"@wp-playground/wordpress": "3.0.4",
|
|
68
|
+
"@php-wasm/node": "3.0.4",
|
|
69
|
+
"@php-wasm/util": "3.0.4",
|
|
70
|
+
"@wp-playground/storage": "3.0.4",
|
|
71
|
+
"@php-wasm/xdebug-bridge": "3.0.4"
|
|
72
72
|
},
|
|
73
73
|
"overrides": {
|
|
74
74
|
"rollup": "^4.34.6",
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var K=Object.create;var V=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var re=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty;var ie=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of te(r))!oe.call(e,o)&&o!==t&&V(e,o,{get:()=>r[o],enumerable:!(s=ee(r,o))||s.enumerable});return e};var se=(e,r,t)=>(t=e!=null?K(re(e)):{},ie(r||!e||!e.__esModule?V(t,"default",{value:e,enumerable:!0}):t,e));const u=require("@php-wasm/logger"),
|
|
1
|
+
"use strict";var K=Object.create;var V=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var re=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty;var ie=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of te(r))!oe.call(e,o)&&o!==t&&V(e,o,{get:()=>r[o],enumerable:!(s=ee(r,o))||s.enumerable});return e};var se=(e,r,t)=>(t=e!=null?K(re(e)):{},ie(r||!e||!e.__esModule?V(t,"default",{value:e,enumerable:!0}):t,e));const u=require("@php-wasm/logger"),w=require("@php-wasm/universal"),R=require("@wp-playground/blueprints"),C=require("@wp-playground/common"),p=require("fs"),A=require("worker_threads"),T=require("./mounts-BJFrPHGW.cjs"),ne=require("express"),ae=require("@php-wasm/node"),D=require("os"),le=require("wasm-feature-detect"),ue=require("yargs"),d=require("path"),M=require("@wp-playground/storage"),j=require("@php-wasm/progress"),ce=require("@wp-playground/wordpress"),W=require("fs-extra"),pe=require("@php-wasm/xdebug-bridge"),O=require("tmp-promise"),de=require("ps-man");var x=typeof document<"u"?document.currentScript:null;async function fe(e){const r=ne(),t=await new Promise((i,n)=>{const a=r.listen(e.port,()=>{const l=a.address();l===null||typeof l=="string"?n(new Error("Server address is not available")):i(a)})});r.use("/",async(i,n)=>{const a=await e.handleRequest({url:i.url,headers:me(i),method:i.method,body:await he(i)});n.statusCode=a.httpStatusCode;for(const l in a.headers)n.setHeader(l,a.headers[l]);n.end(a.bytes)});const o=t.address().port;return await e.onBind(t,o)}const he=async e=>await new Promise(r=>{const t=[];e.on("data",s=>{t.push(s)}),e.on("end",()=>{r(new Uint8Array(Buffer.concat(t)))})}),me=e=>{const r={};if(e.rawHeaders&&e.rawHeaders.length)for(let t=0;t<e.rawHeaders.length;t+=2)r[e.rawHeaders[t].toLowerCase()]=e.rawHeaders[t+1];return r};class we{constructor(r){this.workerLoads=[],this.addWorker(r)}addWorker(r){this.workerLoads.push({worker:r,activeRequests:new Set})}async handleRequest(r){let t=this.workerLoads[0];for(let o=1;o<this.workerLoads.length;o++){const i=this.workerLoads[o];i.activeRequests.size<t.activeRequests.size&&(t=i)}const s=t.worker.request(r);return t.activeRequests.add(s),s.url=r.url,s.finally(()=>{t.activeRequests.delete(s)})}}function ge(e){return/^latest$|^trunk$|^nightly$|^(?:(\d+)\.(\d+)(?:\.(\d+))?)((?:-beta(?:\d+)?)|(?:-RC(?:\d+)?))?$/.test(e)}async function ye({sourceString:e,blueprintMayReadAdjacentFiles:r}){if(!e)return;if(e.startsWith("http://")||e.startsWith("https://"))return await R.resolveRemoteBlueprint(e);let t=d.resolve(process.cwd(),e);if(!p.existsSync(t))throw new Error(`Blueprint file does not exist: ${t}`);const s=p.statSync(t);if(s.isDirectory()&&(t=d.join(t,"blueprint.json")),!s.isFile()&&s.isSymbolicLink())throw new Error(`Blueprint path is neither a file nor a directory: ${t}`);const o=d.extname(t);switch(o){case".zip":return M.ZipFilesystem.fromArrayBuffer(p.readFileSync(t).buffer);case".json":{const i=p.readFileSync(t,"utf-8");try{JSON.parse(i)}catch{throw new Error(`Blueprint file at ${t} is not a valid JSON file`)}const n=d.dirname(t),a=new M.NodeJsFilesystem(n);return new M.OverlayFilesystem([new M.InMemoryFilesystem({"blueprint.json":i}),{read(l){if(!r)throw new Error(`Error: Blueprint contained tried to read a local file at path "${l}" (via a resource of type "bundled"). Playground restricts access to local resources by default as a security measure.
|
|
2
2
|
|
|
3
|
-
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 a.read(l)}}])}default:throw new Error(`Unsupported blueprint file extension: ${o}. Only .zip and .json files are supported.`)}}class be{constructor(r,t){this.lastProgressMessage="",this.args=r,this.siteUrl=t.siteUrl,this.processIdSpaceLength=t.processIdSpaceLength,this.phpVersion=r.php}getWorkerType(){return"v2"}async bootPrimaryWorker(r,t,s){const o=
|
|
3
|
+
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 a.read(l)}}])}default:throw new Error(`Unsupported blueprint file extension: ${o}. Only .zip and .json files are supported.`)}}class be{constructor(r,t){this.lastProgressMessage="",this.args=r,this.siteUrl=t.siteUrl,this.processIdSpaceLength=t.processIdSpaceLength,this.phpVersion=r.php}getWorkerType(){return"v2"}async bootPrimaryWorker(r,t,s){const o=w.consumeAPI(r);await o.useFileLockManager(t);const i={...this.args,phpVersion:this.phpVersion,siteUrl:this.siteUrl,firstProcessId:1,processIdSpaceLength:this.processIdSpaceLength,trace:this.args.debug||!1,blueprint:this.args.blueprint,nativeInternalDirPath:s};return await o.bootAsPrimaryWorker(i),o}async bootSecondaryWorker({worker:r,fileLockManagerPort:t,firstProcessId:s,nativeInternalDirPath:o}){const i=w.consumeAPI(r.phpPort);await i.useFileLockManager(t);const n={...this.args,phpVersion:this.phpVersion,siteUrl:this.siteUrl,firstProcessId:s,processIdSpaceLength:this.processIdSpaceLength,trace:this.args.debug||!1,nativeInternalDirPath:o,mountsBeforeWpInstall:this.args["mount-before-install"]||[],mountsAfterWpInstall:this.args.mount||[]};return await i.bootAsSecondaryWorker(n),i}writeProgressUpdate(r,t,s){t!==this.lastProgressMessage&&(this.lastProgressMessage=t,r.isTTY?(r.cursorTo(0),r.write(t),r.clearLine(1),s&&r.write(`
|
|
4
4
|
`)):r.write(`${t}
|
|
5
|
-
`))}}const
|
|
5
|
+
`))}}const q=d.join(D.homedir(),".wordpress-playground");async function Pe(e){return await N("https://github.com/WordPress/sqlite-database-integration/archive/refs/heads/develop.zip","sqlite.zip",e)}async function N(e,r,t){const s=d.join(q,r);return W.existsSync(s)||(W.ensureDirSync(q),await ve(e,s,t)),Z(s)}async function ve(e,r,t){const o=(await t.monitorFetch(fetch(e))).body.getReader(),i=`${r}.partial`,n=W.createWriteStream(i);for(;;){const{done:a,value:l}=await o.read();if(l&&n.write(l),a)break}n.close(),n.closed||await new Promise((a,l)=>{n.on("finish",()=>{W.renameSync(i,r),a(null)}),n.on("error",c=>{W.removeSync(i),l(c)})})}function Z(e,r){return new File([W.readFileSync(e)],d.basename(e))}class ke{constructor(r,t){this.lastProgressMessage="",this.args=r,this.siteUrl=t.siteUrl,this.processIdSpaceLength=t.processIdSpaceLength}getWorkerType(){return"v1"}async bootPrimaryWorker(r,t,s){let o;const i=new j.EmscriptenDownloadMonitor;if(!this.args.skipWordPressSetup){let b=!1;i.addEventListener("progress",$=>{if(b)return;const{loaded:H,total:F}=$.detail,k=Math.floor(Math.min(100,100*H/F));b=k===100,this.writeProgressUpdate(process.stdout,`Downloading WordPress ${k}%...`,b)}),o=await ce.resolveWordPressRelease(this.args.wp),u.logger.log(`Resolved WordPress release URL: ${o?.releaseUrl}`)}const n=o&&d.join(q,`prebuilt-wp-content-for-wp-${o.version}.zip`),a=o?p.existsSync(n)?Z(n):await N(o.releaseUrl,`${o.version}.zip`,i):void 0;u.logger.log("Fetching SQLite integration plugin...");const l=this.args.skipSqliteSetup?void 0:await Pe(i),c=this.args.followSymlinks===!0,P=this.args.experimentalTrace===!0,I=this.args["mount-before-install"]||[],v=this.args.mount||[],m=w.consumeAPI(r);await m.isConnected(),u.logger.log("Booting WordPress...");const L=await R.resolveRuntimeConfiguration(this.getEffectiveBlueprint());return await m.useFileLockManager(t),await m.bootAsPrimaryWorker({phpVersion:L.phpVersion,wpVersion:L.wpVersion,siteUrl:this.siteUrl,mountsBeforeWpInstall:I,mountsAfterWpInstall:v,wordPressZip:a&&await a.arrayBuffer(),sqliteIntegrationPluginZip:await l?.arrayBuffer(),firstProcessId:0,processIdSpaceLength:this.processIdSpaceLength,followSymlinks:c,trace:P,internalCookieStore:this.args.internalCookieStore,withXdebug:this.args.xdebug,nativeInternalDirPath:s}),o&&!this.args["mount-before-install"]&&!p.existsSync(n)&&(u.logger.log("Caching preinstalled WordPress for the next boot..."),p.writeFileSync(n,await C.zipDirectory(m,"/wordpress")),u.logger.log("Cached!")),m}async bootSecondaryWorker({worker:r,fileLockManagerPort:t,firstProcessId:s,nativeInternalDirPath:o}){const i=w.consumeAPI(r.phpPort);return await i.isConnected(),await i.useFileLockManager(t),await i.bootAsSecondaryWorker({phpVersion:this.phpVersion,siteUrl:this.siteUrl,mountsBeforeWpInstall:this.args["mount-before-install"]||[],mountsAfterWpInstall:this.args.mount||[],firstProcessId:s,processIdSpaceLength:this.processIdSpaceLength,followSymlinks:this.args.followSymlinks===!0,trace:this.args.experimentalTrace===!0,internalCookieStore:this.args.internalCookieStore,withXdebug:this.args.xdebug,nativeInternalDirPath:o}),await i.isReady(),i}async compileInputBlueprint(r){const t=this.getEffectiveBlueprint(),s=new j.ProgressTracker;let o="",i=!1;return s.addEventListener("progress",n=>{if(i)return;i=n.detail.progress===100;const a=Math.floor(n.detail.progress);o=n.detail.caption||o||"Running the Blueprint";const l=`${o.trim()} – ${a}%`;this.writeProgressUpdate(process.stdout,l,i)}),await R.compileBlueprintV1(t,{progress:s,additionalSteps:r})}getEffectiveBlueprint(){const r=this.args.blueprint;return R.isBlueprintBundle(r)?r:{login:this.args.login,...r||{},preferredVersions:{php:this.args.php??r?.preferredVersions?.php??C.RecommendedPHPVersion,wp:this.args.wp??r?.preferredVersions?.wp??"latest",...r?.preferredVersions||{}}}}writeProgressUpdate(r,t,s){this.args.verbosity!==E.Quiet.name&&t!==this.lastProgressMessage&&(this.lastProgressMessage=t,r.isTTY?(r.cursorTo(0),r.write(t),r.clearLine(1),s&&r.write(`
|
|
6
6
|
`)):r.write(`${t}
|
|
7
|
-
`))}}async function Se(e,r=!0){const s=`${d.basename(process.argv0)}${e}${process.pid}-`,o=(await O.dir({prefix:s,unsafeCleanup:!0})).path;return r&&O.setGracefulCleanup(),o}async function xe(e,r,t){const o=(await We(e,r,t)).map(i=>new Promise(n=>{p.rm(i,{recursive:!0},a=>{a?u.logger.warn(`Failed to delete stale Playground temp dir: ${i}`,a):u.logger.info(`Deleted stale Playground temp dir: ${i}`),n()})}));await Promise.all(o)}async function We(e,r,t){try{const s=p.readdirSync(t).map(i=>d.join(t,i)),o=[];for(const i of s)await Le(e,r,i)&&o.push(i);return o}catch(s){return u.logger.warn(`Failed to find stale Playground temp dirs: ${s}`),[]}}async function Le(e,r,t){if(!p.lstatSync(t).isDirectory())return!1;const o=d.basename(t);if(!o.includes(e))return!1;const i=o.match(new RegExp(`^(.+)${e}(\\d+)-`));if(!i)return!1;const n={executableName:i[1],pid:i[2]};if(await Re(n.pid,n.executableName))return!1;const a=Date.now()-r;return p.statSync(t).mtime.getTime()<a}async function Re(e,r){const[t]=await new Promise((s,o)=>{de.list({pid:e,name:r,clean:!0},(i,n)=>{i?o(i):s(n)})});return!!t&&t.pid===e&&t.command===r}const
|
|
8
|
-
Warning: Following symlinks will expose files outside mounted directories to Playground and could be a security risk.`,type:"boolean",default:!1}).option("experimental-trace",{describe:"Print detailed messages about system behavior to the console. Useful for troubleshooting.",type:"boolean",default:!1,hidden:!0}).option("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}).option("xdebug",{describe:"Enable Xdebug.",type:"boolean",default:!1}).option("experimental-devtools",{describe:"Enable experimental browser development tools.",type:"boolean",default:!1}).option("experimental-multi-worker",{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",coerce:o=>o??D.cpus().length-1}).option("experimental-blueprints-v2-runner",{describe:"Use the experimental Blueprint V2 runner.",type:"boolean",default:!1,hidden:!0}).option("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}).showHelpOnFail(!1).strictOptions().check(async o=>{if((o["skip-wordpress-setup"]||o.skipWordpressSetup)&&(o.skipWordPressSetup=!0),o.wp!==void 0&&!
|
|
9
|
-
`),
|
|
7
|
+
`))}}async function Se(e,r=!0){const s=`${d.basename(process.argv0)}${e}${process.pid}-`,o=(await O.dir({prefix:s,unsafeCleanup:!0})).path;return r&&O.setGracefulCleanup(),o}async function xe(e,r,t){const o=(await We(e,r,t)).map(i=>new Promise(n=>{p.rm(i,{recursive:!0},a=>{a?u.logger.warn(`Failed to delete stale Playground temp dir: ${i}`,a):u.logger.info(`Deleted stale Playground temp dir: ${i}`),n()})}));await Promise.all(o)}async function We(e,r,t){try{const s=p.readdirSync(t).map(i=>d.join(t,i)),o=[];for(const i of s)await Le(e,r,i)&&o.push(i);return o}catch(s){return u.logger.warn(`Failed to find stale Playground temp dirs: ${s}`),[]}}async function Le(e,r,t){if(!p.lstatSync(t).isDirectory())return!1;const o=d.basename(t);if(!o.includes(e))return!1;const i=o.match(new RegExp(`^(.+)${e}(\\d+)-`));if(!i)return!1;const n={executableName:i[1],pid:i[2]};if(await Re(n.pid,n.executableName))return!1;const a=Date.now()-r;return p.statSync(t).mtime.getTime()<a}async function Re(e,r){const[t]=await new Promise((s,o)=>{de.list({pid:e,name:r,clean:!0},(i,n)=>{i?o(i):s(n)})});return!!t&&t.pid===e&&t.command===r}const E={Quiet:{name:"quiet",severity:u.LogSeverity.Fatal},Normal:{name:"normal",severity:u.LogSeverity.Info},Debug:{name:"debug",severity:u.LogSeverity.Debug}};async function Ie(){try{const e=ue(process.argv.slice(2)).usage("Usage: wp-playground <command> [options]").positional("command",{describe:"Command to run",choices:["server","run-blueprint","build-snapshot"],demandOption:!0}).option("outfile",{describe:"When building, write to this output file.",type:"string",default:"wordpress.zip"}).option("port",{describe:"Port to listen on when serving.",type:"number",default:9400}).option("site-url",{describe:"Site URL to use for WordPress. Defaults to http://127.0.0.1:{port}",type:"string"}).option("php",{describe:"PHP version to use.",type:"string",default:C.RecommendedPHPVersion,choices:w.SupportedPHPVersions}).option("wp",{describe:"WordPress version to use.",type:"string",default:"latest"}).option("mount",{describe:"Mount a directory to the PHP runtime (can be used multiple times). Format: /host/path:/vfs/path",type:"array",string:!0,coerce:T.parseMountWithDelimiterArguments}).option("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:T.parseMountWithDelimiterArguments}).option("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}).option("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:T.parseMountDirArguments}).option("login",{describe:"Should log the user in",type:"boolean",default:!1}).option("blueprint",{describe:"Blueprint to execute.",type:"string"}).option("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}).option("skip-wordpress-setup",{describe:"Do not download, unzip, and install WordPress. Useful for mounting a pre-configured WordPress directory at /wordpress.",type:"boolean",default:!1}).option("skip-sqlite-setup",{describe:"Skip the SQLite integration plugin setup to allow the WordPress site to use MySQL.",type:"boolean",default:!1}).option("quiet",{describe:"Do not output logs and progress messages.",type:"boolean",default:!1,hidden:!0}).option("verbosity",{describe:"Output logs and progress messages.",type:"string",choices:Object.values(E).map(o=>o.name),default:"normal"}).option("debug",{describe:"Print PHP error log content if an error occurs during Playground boot.",type:"boolean",default:!1}).option("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"}).option("follow-symlinks",{describe:`Allow Playground to follow symlinks by automatically mounting symlinked directories and files encountered in mounted directories.
|
|
8
|
+
Warning: Following symlinks will expose files outside mounted directories to Playground and could be a security risk.`,type:"boolean",default:!1}).option("experimental-trace",{describe:"Print detailed messages about system behavior to the console. Useful for troubleshooting.",type:"boolean",default:!1,hidden:!0}).option("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}).option("xdebug",{describe:"Enable Xdebug.",type:"boolean",default:!1}).option("experimental-devtools",{describe:"Enable experimental browser development tools.",type:"boolean",default:!1}).option("experimental-multi-worker",{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",coerce:o=>o??D.cpus().length-1}).option("experimental-blueprints-v2-runner",{describe:"Use the experimental Blueprint V2 runner.",type:"boolean",default:!1,hidden:!0}).option("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}).showHelpOnFail(!1).strictOptions().check(async o=>{if((o["skip-wordpress-setup"]||o.skipWordpressSetup)&&(o.skipWordPressSetup=!0),o.wp!==void 0&&!ge(o.wp))try{new URL(o.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"')}if(o["site-url"]!==void 0&&o["site-url"]!=="")try{new URL(o["site-url"])}catch{throw new Error(`Invalid site-url "${o["site-url"]}". Please provide a valid URL (e.g., http://localhost:8080 or https://example.com)`)}if(o["auto-mount"]){let i=!1;try{i=p.statSync(o["auto-mount"]).isDirectory()}catch{i=!1}if(!i)throw new Error(`The specified --auto-mount path is not a directory: '${o["auto-mount"]}'.`)}if(o["experimental-multi-worker"]!==void 0&&o["experimental-multi-worker"]<=1)throw new Error("The --experimental-multi-worker flag must be a positive integer greater than 1.");if(o["experimental-blueprints-v2-runner"]===!0){if(o.mode!==void 0){if("skip-wordpress-setup"in o)throw new Error("The --skipWordPressSetup option cannot be used with the --mode option. Use one or the other.");if("skip-sqlite-setup"in o)throw new Error("The --skipSqliteSetup option is not supported in Blueprint V2 mode.");if(o["auto-mount"]!==void 0)throw new Error("The --mode option cannot be used with --auto-mount because --auto-mount automatically sets the mode.")}else o["skip-wordpress-setup"]===!0?o.mode="apply-to-existing-site":o.mode="create-new-site";const i=o.allow||[];o.followSymlinks===!0&&i.push("follow-symlinks"),o["blueprint-may-read-adjacent-files"]===!0&&i.push("read-local-fs"),o.allow=i}else if(o.mode!==void 0)throw new Error("The --mode option requires the --experimentalBlueprintsV2Runner flag.");return!0});e.wrap(e.terminalWidth());const r=await e.argv,t=r._[0];["run-blueprint","server","build-snapshot"].includes(t)||(e.showHelp(),process.exit(1));const s={...r,command:t,mount:[...r.mount||[],...r["mount-dir"]||[]],"mount-before-install":[...r["mount-before-install"]||[],...r["mount-dir-before-install"]||[]]};await J(s)}catch(e){if(!(e instanceof Error))throw e;if(process.argv.includes("--debug"))w.printDebugDetails(e);else{const t=[];let s=e;do t.push(s.message),s=s.cause;while(s instanceof Error);console.error("\x1B[1m"+t.join(" caused by ")+"\x1B[0m")}process.exit(1)}}async function J(e){let r,t;const s=[];if(e.autoMount!==void 0&&(e.autoMount===""&&(e={...e,autoMount:process.cwd()}),e=T.expandAutoMounts(e)),e.quiet&&(e.verbosity="quiet",delete e.quiet),e.debug?e.verbosity="debug":e.verbosity==="debug"&&(e.debug=!0),e.verbosity){const l=Object.values(E).find(c=>c.name===e.verbosity).severity;u.logger.setSeverityFilterLevel(l)}const o=D.platform()==="win32"?void 0:await import("fs-ext").then(l=>l.flockSync).catch(()=>{u.logger.warn("The fs-ext package is not installed. Internal file locking will not be integrated with host OS file locking.")}),i=new ae.FileLockManagerForNode(o);let n=!1,a=!0;return u.logger.log("Starting a PHP server..."),fe({port:e.port,onBind:async(l,c)=>{const P=`http://127.0.0.1:${c}`,I=e["site-url"]||P,v=e.experimentalMultiWorker??1,m=Math.floor(Number.MAX_SAFE_INTEGER/v),L="-playground-cli-site-",b=await Se(L),$=d.dirname(b),F=2*24*60*60*1e3;xe(L,F,$);const k=d.join(b,"internal");p.mkdirSync(k);const Q=["wordpress","tmp","home"];for(const f of Q){const g=h=>h.vfsPath===`/${f}`;if(!(e["mount-before-install"]?.some(g)||e.mount?.some(g))){const h=d.join(b,f);p.mkdirSync(h),e["mount-before-install"]===void 0&&(e["mount-before-install"]=[]),e["mount-before-install"].unshift({vfsPath:`/${f}`,hostPath:h})}}let S;e["experimental-blueprints-v2-runner"]?S=new be(e,{siteUrl:I,processIdSpaceLength:m}):(S=new ke(e,{siteUrl:I,processIdSpaceLength:m}),typeof e.blueprint=="string"&&(e.blueprint=await ye({sourceString:e.blueprint,blueprintMayReadAdjacentFiles:e["blueprint-may-read-adjacent-files"]===!0})));const X=Be(v,S.getWorkerType(),({exitCode:f,isMain:g,workerIndex:B})=>{f!==0&&(u.logger.error(`Worker ${B} exited with code ${f}
|
|
9
|
+
`),g&&e.exitOnPrimaryWorkerCrash&&process.exit(1))});u.logger.log(`Setting up WordPress ${e.wp}`);try{const[f,...g]=await X,B=await z(i);if(t=await S.bootPrimaryWorker(f.phpPort,B,k),s.push({playground:t,worker:f.worker}),await t.isReady(),n=!0,u.logger.log("Booted!"),r=new we(t),!e["experimental-blueprints-v2-runner"]){const h=await S.compileInputBlueprint(e["additional-blueprint-steps"]||[]);h&&(u.logger.log("Running the Blueprint..."),await R.runBlueprintV1Steps(h,t),u.logger.log("Finished running the blueprint"))}if(e.command==="build-snapshot"?(await Te(t,e.outfile),u.logger.log(`WordPress exported to ${e.outfile}`),process.exit(0)):e.command==="run-blueprint"&&(u.logger.log("Blueprint executed"),process.exit(0)),e.experimentalMultiWorker&&e.experimentalMultiWorker>1){u.logger.log("Preparing additional workers...");const h=m;await Promise.all(g.map(async(y,U)=>{const Y=h+U*m,G=await z(i),_=await S.bootSecondaryWorker({worker:y,fileLockManagerPort:G,firstProcessId:Y,nativeInternalDirPath:k});s.push({playground:_,worker:y.worker}),r.addWorker(_)}))}return u.logger.log(`WordPress is running on ${P} with ${v} worker(s)`),e.experimentalDevtools&&e.xdebug&&(await pe.startBridge({getPHPFile:async y=>await t.readFileAsText(y)})).start(),{playground:t,server:l,[Symbol.asyncDispose]:async function(){await Promise.all(s.map(async({playground:y,worker:U})=>{await y.dispose(),await U.terminate()})),await new Promise(y=>l.close(y))},workerThreadCount:v}}catch(f){if(!e.debug)throw f;let g="";throw await t?.fileExists(u.errorLogPath)&&(g=await t.readFileAsText(u.errorLogPath)),new Error(g,{cause:f})}},async handleRequest(l){if(!n)return w.PHPResponse.forHttpCode(502,"WordPress is not ready yet");if(a){a=!1;const c={"Content-Type":["text/plain"],"Content-Length":["0"],Location:["/"]};return l.headers?.cookie?.includes("playground_auto_login_already_happened")&&(c["Set-Cookie"]=["playground_auto_login_already_happened=1; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/"]),new w.PHPResponse(302,c,new Uint8Array)}return await r.handleRequest(l)}})}async function Be(e,r,t){const s=[];for(let o=0;o<e;o++){const i=await Me(r),n=a=>{t({exitCode:a,isMain:o===0,workerIndex:o})};s.push(new Promise((a,l)=>{i.once("message",function(c){c.command==="worker-script-initialized"&&a({worker:i,phpPort:c.phpPort})}),i.once("error",function(c){console.error(c);const P=new Error(`Worker failed to load worker. ${c.message?`Original error: ${c.message}`:""}`);l(P)}),i.once("exit",n)}))}return Promise.all(s)}async function Me(e){return e==="v1"?new A.Worker(new URL("./worker-thread-v1.cjs",typeof document>"u"?require("url").pathToFileURL(__filename).href:x&&x.tagName.toUpperCase()==="SCRIPT"&&x.src||new URL("run-cli-DdsLZ1X6.cjs",document.baseURI).href)):new A.Worker(new URL("./worker-thread-v2.cjs",typeof document>"u"?require("url").pathToFileURL(__filename).href:x&&x.tagName.toUpperCase()==="SCRIPT"&&x.src||new URL("run-cli-DdsLZ1X6.cjs",document.baseURI).href))}async function z(e){const{port1:r,port2:t}=new A.MessageChannel;return await le.jspi()?w.exposeAPI(e,null,r):await w.exposeSyncAPI(e,r),t}async function Te(e,r){await e.run({code:`<?php
|
|
10
10
|
$zip = new ZipArchive();
|
|
11
11
|
if(false === $zip->open('/tmp/build.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
|
|
12
12
|
throw new Exception('Failed to create ZIP');
|
|
@@ -23,5 +23,5 @@ Warning: Following symlinks will expose files outside mounted directories to Pla
|
|
|
23
23
|
}
|
|
24
24
|
$zip->close();
|
|
25
25
|
|
|
26
|
-
`});const t=await e.readFileAsBuffer("/tmp/build.zip");p.writeFileSync(r,t)}exports.LogVerbosity
|
|
27
|
-
//# sourceMappingURL=run-cli-
|
|
26
|
+
`});const t=await e.readFileAsBuffer("/tmp/build.zip");p.writeFileSync(r,t)}exports.LogVerbosity=E;exports.parseOptionsAndRunCLI=Ie;exports.runCLI=J;
|
|
27
|
+
//# sourceMappingURL=run-cli-DdsLZ1X6.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-cli-DdsLZ1X6.cjs","sources":["../../../../packages/playground/cli/src/start-server.ts","../../../../packages/playground/cli/src/load-balancer.ts","../../../../packages/playground/cli/src/is-valid-wordpress-slug.ts","../../../../packages/playground/cli/src/resolve-blueprint.ts","../../../../packages/playground/cli/src/blueprints-v2/blueprints-v2-handler.ts","../../../../packages/playground/cli/src/blueprints-v1/download.ts","../../../../packages/playground/cli/src/blueprints-v1/blueprints-v1-handler.ts","../../../../packages/playground/cli/src/temp-dir.ts","../../../../packages/playground/cli/src/run-cli.ts"],"sourcesContent":["import type { PHPRequest, PHPResponse } from '@php-wasm/universal';\nimport type { Request } from 'express';\nimport express from 'express';\nimport type { IncomingMessage, Server, ServerResponse } from 'http';\nimport type { AddressInfo } from 'net';\nimport type { RunCLIServer } from './run-cli';\n\nexport interface ServerOptions {\n\tport: number;\n\tonBind: (server: Server, port: number) => Promise<RunCLIServer>;\n\thandleRequest: (request: PHPRequest) => Promise<PHPResponse>;\n}\n\nexport async function startServer(\n\toptions: ServerOptions\n): Promise<RunCLIServer> {\n\tconst app = express();\n\n\tconst server = await new Promise<\n\t\tServer<typeof IncomingMessage, typeof ServerResponse>\n\t>((resolve, reject) => {\n\t\tconst server = app.listen(options.port, () => {\n\t\t\tconst address = server.address();\n\t\t\tif (address === null || typeof address === 'string') {\n\t\t\t\treject(new Error('Server address is not available'));\n\t\t\t} else {\n\t\t\t\tresolve(server);\n\t\t\t}\n\t\t});\n\t});\n\n\tapp.use('/', async (req, res) => {\n\t\tconst phpResponse = await options.handleRequest({\n\t\t\turl: req.url,\n\t\t\theaders: parseHeaders(req),\n\t\t\tmethod: req.method as any,\n\t\t\tbody: await bufferRequestBody(req),\n\t\t});\n\n\t\tres.statusCode = phpResponse.httpStatusCode;\n\t\tfor (const key in phpResponse.headers) {\n\t\t\tres.setHeader(key, phpResponse.headers[key]);\n\t\t}\n\t\tres.end(phpResponse.bytes);\n\t});\n\n\tconst address = server.address();\n\tconst port = (address! as AddressInfo).port;\n\treturn await options.onBind(server, port);\n}\n\nconst bufferRequestBody = async (req: Request): Promise<Uint8Array> =>\n\tawait new Promise((resolve) => {\n\t\tconst body: Uint8Array[] = [];\n\t\treq.on('data', (chunk) => {\n\t\t\tbody.push(chunk);\n\t\t});\n\t\treq.on('end', () => {\n\t\t\tresolve(new Uint8Array(Buffer.concat(body)));\n\t\t});\n\t});\n\nconst parseHeaders = (req: Request): Record<string, string> => {\n\tconst requestHeaders: Record<string, string> = {};\n\tif (req.rawHeaders && req.rawHeaders.length) {\n\t\tfor (let i = 0; i < req.rawHeaders.length; i += 2) {\n\t\t\trequestHeaders[req.rawHeaders[i].toLowerCase()] =\n\t\t\t\treq.rawHeaders[i + 1];\n\t\t}\n\t}\n\treturn requestHeaders;\n};\n","import type { PHPRequest, PHPResponse, RemoteAPI } from '@php-wasm/universal';\nimport type { PlaygroundCliBlueprintV1Worker as PlaygroundCliWorkerV1 } from './blueprints-v1/worker-thread-v1';\nimport type { PlaygroundCliBlueprintV2Worker as PlaygroundCliWorkerV2 } from './blueprints-v2/worker-thread-v2';\n\ntype PlaygroundCliWorker = PlaygroundCliWorkerV1 | PlaygroundCliWorkerV2;\n\n// TODO: Let's merge worker management into PHPProcessManager\n// when we can have multiple workers in both CLI and web.\n// ¡ATTENTION!:Please don't expand upon this as an independent abstraction.\n\n// TODO: Could we just spawn a worker using the factory function to PHPProcessManager?\ntype WorkerLoad = {\n\tworker: RemoteAPI<PlaygroundCliWorker>;\n\tactiveRequests: Set<Promise<PHPResponse>>;\n};\nexport class LoadBalancer {\n\tworkerLoads: WorkerLoad[] = [];\n\n\tconstructor(\n\t\t// NOTE: We require a worker to start so that a load balancer\n\t\t// may not exist without being able to service requests.\n\t\t// Playground CLI initialization, as of 2025-06-11, requires that\n\t\t// an initial worker is booted alone and initialized via Blueprint\n\t\t// before additional workers are created based on the initialized worker.\n\t\tinitialWorker: RemoteAPI<PlaygroundCliWorker>\n\t) {\n\t\tthis.addWorker(initialWorker);\n\t}\n\n\taddWorker(worker: RemoteAPI<PlaygroundCliWorker>) {\n\t\tthis.workerLoads.push({\n\t\t\tworker,\n\t\t\tactiveRequests: new Set(),\n\t\t});\n\t}\n\n\tasync handleRequest(request: PHPRequest) {\n\t\tlet smallestWorkerLoad = this.workerLoads[0];\n\n\t\t// TODO: Is there any way for us to track CPU load so we could avoid\n\t\t// picking a worker that is under heavy load despite few requests?\n\t\t// Possibly this: https://nodejs.org/api/worker_threads.html#workerperformance\n\t\t// Though we probably don't need to worry about it.\n\t\tfor (let i = 1; i < this.workerLoads.length; i++) {\n\t\t\tconst workerLoad = this.workerLoads[i];\n\t\t\tif (\n\t\t\t\tworkerLoad.activeRequests.size <\n\t\t\t\tsmallestWorkerLoad.activeRequests.size\n\t\t\t) {\n\t\t\t\tsmallestWorkerLoad = workerLoad;\n\t\t\t}\n\t\t}\n\n\t\t// TODO: Add trace facility to Playground CLI to observe internals like request routing.\n\n\t\tconst promiseForResponse = smallestWorkerLoad.worker.request(request);\n\t\tsmallestWorkerLoad.activeRequests.add(promiseForResponse);\n\n\t\t// Add URL to promise for use while debugging\n\t\t(promiseForResponse as any).url = request.url;\n\n\t\treturn promiseForResponse.finally(() => {\n\t\t\tsmallestWorkerLoad.activeRequests.delete(promiseForResponse);\n\t\t});\n\t}\n}\n","/**\n * Checks if the given version string is a valid WordPress version.\n *\n * The Regex is based on the releases on https://wordpress.org/download/releases/#betas\n * The version string can be one of the following formats:\n * - \"latest\"\n * - \"trunk\"\n * - \"nightly\"\n * - \"x.y\" (x and y are integers) e.g. \"6.2\"\n * - \"x.y.z\" (x, y and z are integers) e.g. \"6.2.1\"\n * - \"x.y.z-betaN\" (N is an integer) e.g. \"6.2.1-beta1\"\n * - \"x.y.z-RCN\" (N is an integer) e.g. \"6.2-RC1\"\n *\n * @param version The version string to check.\n * @returns A boolean value indicating whether the version string is a valid WordPress version.\n */\nexport function isValidWordPressSlug(version: string): boolean {\n\tconst versionPattern =\n\t\t/^latest$|^trunk$|^nightly$|^(?:(\\d+)\\.(\\d+)(?:\\.(\\d+))?)((?:-beta(?:\\d+)?)|(?:-RC(?:\\d+)?))?$/;\n\treturn versionPattern.test(version);\n}\n","import fs from 'fs';\nimport path from 'path';\nimport {\n\tZipFilesystem,\n\tNodeJsFilesystem,\n\tOverlayFilesystem,\n\tInMemoryFilesystem,\n} from '@wp-playground/storage';\nimport { resolveRemoteBlueprint } from '@wp-playground/blueprints';\n\ntype ResolveBlueprintOptions = {\n\tsourceString: string | undefined;\n\tblueprintMayReadAdjacentFiles: boolean;\n};\n\n/**\n * Resolves a blueprint from a URL or a local path.\n *\n * @TODO: Extract the common Blueprint resolution logic between CLI and\n * the website into a single, isomorphic resolveBlueprint() function.\n * Still retain the CLI-specific bits in the CLI package.\n *\n * @param sourceString - The source string to resolve the blueprint from.\n * @param blueprintMayReadAdjacentFiles - Whether the blueprint may read adjacent files.\n * @returns The resolved blueprint.\n */\nexport async function resolveBlueprint({\n\tsourceString,\n\tblueprintMayReadAdjacentFiles,\n}: ResolveBlueprintOptions) {\n\tif (!sourceString) {\n\t\treturn undefined;\n\t}\n\n\tif (\n\t\tsourceString.startsWith('http://') ||\n\t\tsourceString.startsWith('https://')\n\t) {\n\t\treturn await resolveRemoteBlueprint(sourceString);\n\t}\n\n\t// If the sourceString does not refer to a remote blueprint, try to\n\t// resolve it from a local filesystem.\n\n\tlet blueprintPath = path.resolve(process.cwd(), sourceString);\n\tif (!fs.existsSync(blueprintPath)) {\n\t\tthrow new Error(`Blueprint file does not exist: ${blueprintPath}`);\n\t}\n\n\tconst stat = fs.statSync(blueprintPath);\n\tif (stat.isDirectory()) {\n\t\tblueprintPath = path.join(blueprintPath, 'blueprint.json');\n\t}\n\n\tif (!stat.isFile() && stat.isSymbolicLink()) {\n\t\tthrow new Error(\n\t\t\t`Blueprint path is neither a file nor a directory: ${blueprintPath}`\n\t\t);\n\t}\n\n\tconst extension = path.extname(blueprintPath);\n\tswitch (extension) {\n\t\tcase '.zip':\n\t\t\treturn ZipFilesystem.fromArrayBuffer(\n\t\t\t\tfs.readFileSync(blueprintPath).buffer as ArrayBuffer\n\t\t\t);\n\t\tcase '.json': {\n\t\t\tconst blueprintText = fs.readFileSync(blueprintPath, 'utf-8');\n\t\t\ttry {\n\t\t\t\tJSON.parse(blueprintText);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Blueprint file at ${blueprintPath} is not a valid JSON file`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst contextPath = path.dirname(blueprintPath);\n\t\t\tconst nodeJsFilesystem = new NodeJsFilesystem(contextPath);\n\t\t\treturn new OverlayFilesystem([\n\t\t\t\tnew InMemoryFilesystem({\n\t\t\t\t\t'blueprint.json': blueprintText,\n\t\t\t\t}),\n\t\t\t\t/**\n\t\t\t\t * Wrap the NodeJS filesystem to prevent access to local files\n\t\t\t\t * unless the user explicitly allowed it.\n\t\t\t\t */\n\t\t\t\t{\n\t\t\t\t\tread(path) {\n\t\t\t\t\t\tif (!blueprintMayReadAdjacentFiles) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Error: Blueprint contained tried to read a local file at path \"${path}\" (via a resource of type \"bundled\"). ` +\n\t\t\t\t\t\t\t\t\t`Playground restricts access to local resources by default as a security measure. \\n\\n` +\n\t\t\t\t\t\t\t\t\t`You can allow this Blueprint to read files from the same parent directory by explicitly adding the ` +\n\t\t\t\t\t\t\t\t\t`--blueprint-may-read-adjacent-files option to your command.`\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn nodeJsFilesystem.read(path);\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t]);\n\t\t}\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Unsupported blueprint file extension: ${extension}. Only .zip and .json files are supported.`\n\t\t\t);\n\t}\n}\n","import type { RemoteAPI, SupportedPHPVersion } from '@php-wasm/universal';\nimport { consumeAPI } from '@php-wasm/universal';\nimport type {\n\tPlaygroundCliBlueprintV2Worker,\n\tSecondaryWorkerBootArgs,\n} from './worker-thread-v2';\nimport type { MessagePort as NodeMessagePort } from 'worker_threads';\nimport type { RunCLIArgs, SpawnedWorker, WorkerType } from '../run-cli';\n\n/**\n * Boots Playground CLI workers using Blueprint version 2.\n *\n * Progress tracking, downloads, steps, and all other features are\n * implemented in PHP and orchestrated by the worker thread.\n */\nexport class BlueprintsV2Handler {\n\tprivate phpVersion: SupportedPHPVersion;\n\tprivate lastProgressMessage = '';\n\n\tprivate siteUrl: string;\n\tprivate processIdSpaceLength: number;\n\tprivate args: RunCLIArgs;\n\n\tconstructor(\n\t\targs: RunCLIArgs,\n\t\toptions: {\n\t\t\tsiteUrl: string;\n\t\t\tprocessIdSpaceLength: number;\n\t\t}\n\t) {\n\t\tthis.args = args;\n\t\tthis.siteUrl = options.siteUrl;\n\t\tthis.processIdSpaceLength = options.processIdSpaceLength;\n\t\tthis.phpVersion = args.php as SupportedPHPVersion;\n\t}\n\n\tgetWorkerType(): WorkerType {\n\t\treturn 'v2';\n\t}\n\n\tasync bootPrimaryWorker(\n\t\tphpPort: NodeMessagePort,\n\t\tfileLockManagerPort: NodeMessagePort,\n\t\tnativeInternalDirPath: string\n\t) {\n\t\tconst playground: RemoteAPI<PlaygroundCliBlueprintV2Worker> =\n\t\t\tconsumeAPI(phpPort);\n\n\t\tawait playground.useFileLockManager(fileLockManagerPort);\n\n\t\tconst workerBootArgs = {\n\t\t\t...this.args,\n\t\t\tphpVersion: this.phpVersion,\n\t\t\tsiteUrl: this.siteUrl,\n\t\t\tfirstProcessId: 1,\n\t\t\tprocessIdSpaceLength: this.processIdSpaceLength,\n\t\t\ttrace: this.args.debug || false,\n\t\t\tblueprint: this.args.blueprint!,\n\t\t\tnativeInternalDirPath,\n\t\t};\n\n\t\tawait playground.bootAsPrimaryWorker(workerBootArgs);\n\t\treturn playground;\n\t}\n\n\tasync bootSecondaryWorker({\n\t\tworker,\n\t\tfileLockManagerPort,\n\t\tfirstProcessId,\n\t\tnativeInternalDirPath,\n\t}: {\n\t\tworker: SpawnedWorker;\n\t\tfileLockManagerPort: NodeMessagePort;\n\t\tfirstProcessId: number;\n\t\tnativeInternalDirPath: string;\n\t}) {\n\t\tconst playground: RemoteAPI<PlaygroundCliBlueprintV2Worker> =\n\t\t\tconsumeAPI(worker.phpPort);\n\n\t\tawait playground.useFileLockManager(fileLockManagerPort);\n\n\t\tconst workerBootArgs: SecondaryWorkerBootArgs = {\n\t\t\t...this.args,\n\t\t\tphpVersion: this.phpVersion!,\n\t\t\tsiteUrl: this.siteUrl,\n\t\t\tfirstProcessId,\n\t\t\tprocessIdSpaceLength: this.processIdSpaceLength,\n\t\t\ttrace: this.args.debug || false,\n\t\t\tnativeInternalDirPath,\n\t\t\tmountsBeforeWpInstall: this.args['mount-before-install'] || [],\n\t\t\tmountsAfterWpInstall: this.args.mount || [],\n\t\t};\n\n\t\tawait playground.bootAsSecondaryWorker(workerBootArgs);\n\n\t\treturn playground;\n\t}\n\n\twriteProgressUpdate(\n\t\twriteStream: NodeJS.WriteStream,\n\t\tmessage: string,\n\t\tfinalUpdate: boolean\n\t) {\n\t\tif (message === this.lastProgressMessage) {\n\t\t\t// Avoid repeating the same message\n\t\t\treturn;\n\t\t}\n\t\tthis.lastProgressMessage = message;\n\n\t\tif (writeStream.isTTY) {\n\t\t\t// Overwrite previous progress updates in-place for a quieter UX.\n\t\t\twriteStream.cursorTo(0);\n\t\t\twriteStream.write(message);\n\t\t\twriteStream.clearLine(1);\n\n\t\t\tif (finalUpdate) {\n\t\t\t\twriteStream.write('\\n');\n\t\t\t}\n\t\t} else {\n\t\t\t// Fall back to writing one line per progress update\n\t\t\twriteStream.write(`${message}\\n`);\n\t\t}\n\t}\n}\n","import type { EmscriptenDownloadMonitor } from '@php-wasm/progress';\nimport fs from 'fs-extra';\nimport os from 'os';\nimport path, { basename } from 'path';\n\nexport const CACHE_FOLDER = path.join(os.homedir(), '.wordpress-playground');\n\nexport async function fetchSqliteIntegration(\n\tmonitor: EmscriptenDownloadMonitor\n) {\n\tconst sqliteZip = await cachedDownload(\n\t\t'https://github.com/WordPress/sqlite-database-integration/archive/refs/heads/develop.zip',\n\t\t'sqlite.zip',\n\t\tmonitor\n\t);\n\treturn sqliteZip;\n}\n\n// @TODO: Support HTTP cache, invalidate the local file if the remote file has\n// changed\nexport async function cachedDownload(\n\tremoteUrl: string,\n\tcacheKey: string,\n\tmonitor: EmscriptenDownloadMonitor\n) {\n\tconst artifactPath = path.join(CACHE_FOLDER, cacheKey);\n\tif (!fs.existsSync(artifactPath)) {\n\t\tfs.ensureDirSync(CACHE_FOLDER);\n\t\tawait downloadTo(remoteUrl, artifactPath, monitor);\n\t}\n\treturn readAsFile(artifactPath);\n}\n\nasync function downloadTo(\n\tremoteUrl: string,\n\tlocalPath: string,\n\tmonitor: EmscriptenDownloadMonitor\n) {\n\tconst response = await monitor.monitorFetch(fetch(remoteUrl));\n\tconst reader = response.body!.getReader();\n\tconst tmpPath = `${localPath}.partial`;\n\tconst writer = fs.createWriteStream(tmpPath);\n\twhile (true) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (value) {\n\t\t\twriter.write(value);\n\t\t}\n\t\tif (done) {\n\t\t\tbreak;\n\t\t}\n\t}\n\twriter.close();\n\tif (!writer.closed) {\n\t\tawait new Promise((resolve, reject) => {\n\t\t\twriter.on('finish', () => {\n\t\t\t\tfs.renameSync(tmpPath, localPath);\n\t\t\t\tresolve(null);\n\t\t\t});\n\t\t\twriter.on('error', (err: any) => {\n\t\t\t\tfs.removeSync(tmpPath);\n\t\t\t\treject(err);\n\t\t\t});\n\t\t});\n\t}\n}\n\nexport function readAsFile(path: string, fileName?: string): File {\n\treturn new File([fs.readFileSync(path)], fileName ?? basename(path));\n}\n","import { logger } from '@php-wasm/logger';\nimport { EmscriptenDownloadMonitor, ProgressTracker } from '@php-wasm/progress';\nimport type { SupportedPHPVersion } from '@php-wasm/universal';\nimport { consumeAPI } from '@php-wasm/universal';\nimport type { BlueprintV1Declaration } from '@wp-playground/blueprints';\nimport {\n\tcompileBlueprintV1,\n\tisBlueprintBundle,\n\tresolveRuntimeConfiguration,\n} from '@wp-playground/blueprints';\nimport { RecommendedPHPVersion, zipDirectory } from '@wp-playground/common';\nimport fs from 'fs';\nimport path from 'path';\nimport { resolveWordPressRelease } from '@wp-playground/wordpress';\nimport {\n\tCACHE_FOLDER,\n\tcachedDownload,\n\tfetchSqliteIntegration,\n\treadAsFile,\n} from './download';\nimport type { PlaygroundCliBlueprintV1Worker } from './worker-thread-v1';\nimport type { MessagePort as NodeMessagePort } from 'worker_threads';\nimport {\n\tLogVerbosity,\n\ttype RunCLIArgs,\n\ttype SpawnedWorker,\n\ttype WorkerType,\n} from '../run-cli';\n\n/**\n * Boots Playground CLI workers using Blueprint version 1.\n *\n * Progress tracking, downloads, steps, and all other features are\n * implemented in TypeScript and orchestrated by this class.\n */\nexport class BlueprintsV1Handler {\n\tprivate phpVersion: SupportedPHPVersion | undefined;\n\tprivate lastProgressMessage = '';\n\n\tprivate siteUrl: string;\n\tprivate processIdSpaceLength: number;\n\tprivate args: RunCLIArgs;\n\n\tconstructor(\n\t\targs: RunCLIArgs,\n\t\toptions: {\n\t\t\tsiteUrl: string;\n\t\t\tprocessIdSpaceLength: number;\n\t\t}\n\t) {\n\t\tthis.args = args;\n\t\tthis.siteUrl = options.siteUrl;\n\t\tthis.processIdSpaceLength = options.processIdSpaceLength;\n\t}\n\n\tgetWorkerType(): WorkerType {\n\t\treturn 'v1';\n\t}\n\n\tasync bootPrimaryWorker(\n\t\tphpPort: NodeMessagePort,\n\t\tfileLockManagerPort: NodeMessagePort,\n\t\tnativeInternalDirPath: string\n\t) {\n\t\tlet wpDetails: any = undefined;\n\t\t// @TODO: Rename to FetchProgressMonitor. There's nothing Emscripten\n\t\t// about that class anymore.\n\t\tconst monitor = new EmscriptenDownloadMonitor();\n\t\tif (!this.args.skipWordPressSetup) {\n\t\t\tlet progressReached100 = false;\n\t\t\tmonitor.addEventListener('progress', ((\n\t\t\t\te: CustomEvent<ProgressEvent & { finished: boolean }>\n\t\t\t) => {\n\t\t\t\tif (progressReached100) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// @TODO Every progress bar will want percentages. The\n\t\t\t\t// download monitor should just provide that.\n\t\t\t\tconst { loaded, total } = e.detail;\n\t\t\t\t// Use floor() so we don't report 100% until truly there.\n\t\t\t\tconst percentProgress = Math.floor(\n\t\t\t\t\tMath.min(100, (100 * loaded) / total)\n\t\t\t\t);\n\t\t\t\tprogressReached100 = percentProgress === 100;\n\n\t\t\t\tthis.writeProgressUpdate(\n\t\t\t\t\tprocess.stdout,\n\t\t\t\t\t`Downloading WordPress ${percentProgress}%...`,\n\t\t\t\t\tprogressReached100\n\t\t\t\t);\n\t\t\t}) as any);\n\n\t\t\twpDetails = await resolveWordPressRelease(this.args.wp);\n\t\t\tlogger.log(\n\t\t\t\t`Resolved WordPress release URL: ${wpDetails?.releaseUrl}`\n\t\t\t);\n\t\t}\n\n\t\tconst preinstalledWpContentPath =\n\t\t\twpDetails &&\n\t\t\tpath.join(\n\t\t\t\tCACHE_FOLDER,\n\t\t\t\t`prebuilt-wp-content-for-wp-${wpDetails.version}.zip`\n\t\t\t);\n\t\tconst wordPressZip = !wpDetails\n\t\t\t? undefined\n\t\t\t: fs.existsSync(preinstalledWpContentPath)\n\t\t\t? readAsFile(preinstalledWpContentPath)\n\t\t\t: await cachedDownload(\n\t\t\t\t\twpDetails.releaseUrl,\n\t\t\t\t\t`${wpDetails.version}.zip`,\n\t\t\t\t\tmonitor\n\t\t\t );\n\n\t\tlogger.log(`Fetching SQLite integration plugin...`);\n\t\tconst sqliteIntegrationPluginZip = this.args.skipSqliteSetup\n\t\t\t? undefined\n\t\t\t: await fetchSqliteIntegration(monitor);\n\n\t\tconst followSymlinks = this.args.followSymlinks === true;\n\t\tconst trace = this.args.experimentalTrace === true;\n\n\t\tconst mountsBeforeWpInstall = this.args['mount-before-install'] || [];\n\t\tconst mountsAfterWpInstall = this.args.mount || [];\n\n\t\tconst playground = consumeAPI<PlaygroundCliBlueprintV1Worker>(phpPort);\n\n\t\t// Comlink communication proxy\n\t\tawait playground.isConnected();\n\n\t\tlogger.log(`Booting WordPress...`);\n\n\t\tconst runtimeConfiguration = await resolveRuntimeConfiguration(\n\t\t\tthis.getEffectiveBlueprint()\n\t\t);\n\t\tawait playground.useFileLockManager(fileLockManagerPort);\n\t\tawait playground.bootAsPrimaryWorker({\n\t\t\tphpVersion: runtimeConfiguration.phpVersion,\n\t\t\twpVersion: runtimeConfiguration.wpVersion,\n\t\t\tsiteUrl: this.siteUrl,\n\t\t\tmountsBeforeWpInstall,\n\t\t\tmountsAfterWpInstall,\n\t\t\twordPressZip: wordPressZip && (await wordPressZip!.arrayBuffer()),\n\t\t\tsqliteIntegrationPluginZip:\n\t\t\t\tawait sqliteIntegrationPluginZip?.arrayBuffer(),\n\t\t\tfirstProcessId: 0,\n\t\t\tprocessIdSpaceLength: this.processIdSpaceLength,\n\t\t\tfollowSymlinks,\n\t\t\ttrace,\n\t\t\tinternalCookieStore: this.args.internalCookieStore,\n\t\t\twithXdebug: this.args.xdebug,\n\t\t\tnativeInternalDirPath,\n\t\t});\n\n\t\tif (\n\t\t\twpDetails &&\n\t\t\t!this.args['mount-before-install'] &&\n\t\t\t!fs.existsSync(preinstalledWpContentPath)\n\t\t) {\n\t\t\tlogger.log(`Caching preinstalled WordPress for the next boot...`);\n\t\t\tfs.writeFileSync(\n\t\t\t\tpreinstalledWpContentPath,\n\t\t\t\t(await zipDirectory(playground, '/wordpress'))!\n\t\t\t);\n\t\t\tlogger.log(`Cached!`);\n\t\t}\n\n\t\treturn playground;\n\t}\n\n\tasync bootSecondaryWorker({\n\t\tworker,\n\t\tfileLockManagerPort,\n\t\tfirstProcessId,\n\t\tnativeInternalDirPath,\n\t}: {\n\t\tworker: SpawnedWorker;\n\t\tfileLockManagerPort: NodeMessagePort;\n\t\tfirstProcessId: number;\n\t\tnativeInternalDirPath: string;\n\t}) {\n\t\tconst additionalPlayground = consumeAPI<PlaygroundCliBlueprintV1Worker>(\n\t\t\tworker.phpPort\n\t\t);\n\n\t\tawait additionalPlayground.isConnected();\n\t\tawait additionalPlayground.useFileLockManager(fileLockManagerPort);\n\t\tawait additionalPlayground.bootAsSecondaryWorker({\n\t\t\tphpVersion: this.phpVersion!,\n\t\t\tsiteUrl: this.siteUrl,\n\t\t\tmountsBeforeWpInstall: this.args['mount-before-install'] || [],\n\t\t\tmountsAfterWpInstall: this.args['mount'] || [],\n\t\t\tfirstProcessId,\n\t\t\tprocessIdSpaceLength: this.processIdSpaceLength,\n\t\t\tfollowSymlinks: this.args.followSymlinks === true,\n\t\t\ttrace: this.args.experimentalTrace === true,\n\t\t\t// @TODO: Move this to the request handler or else every worker\n\t\t\t// will have a separate cookie store.\n\t\t\tinternalCookieStore: this.args.internalCookieStore,\n\t\t\twithXdebug: this.args.xdebug,\n\t\t\tnativeInternalDirPath,\n\t\t});\n\t\tawait additionalPlayground.isReady();\n\t\treturn additionalPlayground;\n\t}\n\n\tasync compileInputBlueprint(additionalBlueprintSteps: any[]) {\n\t\tconst blueprint = this.getEffectiveBlueprint();\n\n\t\tconst tracker = new ProgressTracker();\n\t\tlet lastCaption = '';\n\t\tlet progressReached100 = false;\n\t\ttracker.addEventListener('progress', (e: any) => {\n\t\t\tif (progressReached100) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tprogressReached100 = e.detail.progress === 100;\n\n\t\t\t// Use floor() so we don't report 100% until truly there.\n\t\t\tconst progressInteger = Math.floor(e.detail.progress);\n\t\t\tlastCaption =\n\t\t\t\te.detail.caption || lastCaption || 'Running the Blueprint';\n\t\t\tconst message = `${lastCaption.trim()} – ${progressInteger}%`;\n\t\t\tthis.writeProgressUpdate(\n\t\t\t\tprocess.stdout,\n\t\t\t\tmessage,\n\t\t\t\tprogressReached100\n\t\t\t);\n\t\t});\n\t\treturn await compileBlueprintV1(blueprint as BlueprintV1Declaration, {\n\t\t\tprogress: tracker,\n\t\t\tadditionalSteps: additionalBlueprintSteps,\n\t\t});\n\t}\n\n\tprivate getEffectiveBlueprint() {\n\t\tconst resolvedBlueprint = this.args.blueprint as BlueprintV1Declaration;\n\t\t/**\n\t\t * @TODO This looks similar to the resolveBlueprint() call in the website package:\n\t\t * \t https://github.com/WordPress/wordpress-playground/blob/ce586059e5885d185376184fdd2f52335cca32b0/packages/playground/website/src/main.tsx#L41\n\t\t *\n\t\t * \t\t Also the Blueprint Builder tool does something similar.\n\t\t * Perhaps all these cases could be handled by the same function?\n\t\t */\n\t\treturn isBlueprintBundle(resolvedBlueprint)\n\t\t\t? resolvedBlueprint\n\t\t\t: {\n\t\t\t\t\tlogin: this.args.login,\n\t\t\t\t\t...(resolvedBlueprint || {}),\n\t\t\t\t\tpreferredVersions: {\n\t\t\t\t\t\tphp:\n\t\t\t\t\t\t\tthis.args.php ??\n\t\t\t\t\t\t\tresolvedBlueprint?.preferredVersions?.php ??\n\t\t\t\t\t\t\tRecommendedPHPVersion,\n\t\t\t\t\t\twp:\n\t\t\t\t\t\t\tthis.args.wp ??\n\t\t\t\t\t\t\tresolvedBlueprint?.preferredVersions?.wp ??\n\t\t\t\t\t\t\t'latest',\n\t\t\t\t\t\t...(resolvedBlueprint?.preferredVersions || {}),\n\t\t\t\t\t},\n\t\t\t };\n\t}\n\n\twriteProgressUpdate(\n\t\twriteStream: NodeJS.WriteStream,\n\t\tmessage: string,\n\t\tfinalUpdate: boolean\n\t) {\n\t\tif (this.args.verbosity === LogVerbosity.Quiet.name) {\n\t\t\treturn;\n\t\t}\n\t\tif (message === this.lastProgressMessage) {\n\t\t\t// Avoid repeating the same message\n\t\t\treturn;\n\t\t}\n\t\tthis.lastProgressMessage = message;\n\n\t\tif (writeStream.isTTY) {\n\t\t\t// Overwrite previous progress updates in-place for a quieter UX.\n\t\t\twriteStream.cursorTo(0);\n\t\t\twriteStream.write(message);\n\t\t\twriteStream.clearLine(1);\n\n\t\t\tif (finalUpdate) {\n\t\t\t\twriteStream.write('\\n');\n\t\t\t}\n\t\t} else {\n\t\t\t// Fall back to writing one line per progress update\n\t\t\twriteStream.write(`${message}\\n`);\n\t\t}\n\t}\n}\n","import fs from 'fs';\nimport path from 'path';\nimport { logger } from '@php-wasm/logger';\nimport {\n\tdir as tmpDir,\n\tsetGracefulCleanup as tmpSetGracefulCleanup,\n} from 'tmp-promise';\n// NOTE: We use ps-man rather than more popular packages because there\n// is no native build required to install the package.\n// @ts-ignore -- There are no types for this package.\nimport ps from 'ps-man';\n\n/**\n * Create a temp dir for the Playground CLI.\n *\n * The temp dir is created in the system temp dir and is named\n * based on the Playground CLI binary name and the process ID.\n *\n * @param substrToIdentifyTempDirs The substring to identify the temp dir.\n * @param autoCleanup Whether to skip cleanup on process exit. Primarily used for unit testing.\n * @returns The path to the temp dir.\n */\nexport async function createPlaygroundCliTempDir(\n\tsubstrToIdentifyTempDirs: string,\n\t// Allow controlling auto-cleanup for test purposes.\n\tautoCleanup = true\n) {\n\tconst nodeBinaryName = path.basename(process.argv0);\n\n\t// We place the binary name before the playground-related fragment\n\t// so we can use the position of the fragment to parse the binary name.\n\t// Otherwise, we would have to parse the binary name from the full path.\n\tconst tempDirPrefix = `${nodeBinaryName}${substrToIdentifyTempDirs}${process.pid}-`;\n\n\tconst nativeDirPath = (\n\t\tawait tmpDir({\n\t\t\tprefix: tempDirPrefix,\n\t\t\t/*\n\t\t\t * Allow recursive cleanup on process exit.\n\t\t\t *\n\t\t\t * NOTE: I worried about whether this cleanup would follow symlinks\n\t\t\t * and delete target files instead of unlinking the symlink,\n\t\t\t * but this feature uses rimraf under the hood which respects symlinks:\n\t\t\t * https://github.com/raszi/node-tmp/blob/3d2fe387f3f91b13830b9182faa02c3231ea8258/lib/tmp.js#L318\n\t\t\t */\n\t\t\tunsafeCleanup: true,\n\t\t})\n\t).path;\n\n\tif (autoCleanup) {\n\t\t// Request graceful cleanup on process exit.\n\t\ttmpSetGracefulCleanup();\n\t}\n\n\treturn nativeDirPath;\n}\n\n/**\n * Cleanup stale Playground temp dirs.\n *\n * A temp dir is considered stale if it is older than the specified age\n * and the associated process no longer exists.\n *\n * @param substrToIdentifyTempDirs The substring to identify the temp dir.\n * @param staleAgeInMillis The age in milliseconds after which a temp dir is considered stale.\n * @param tempRootDir The root directory of the temp dirs.\n */\nexport async function cleanupStalePlaygroundTempDirs(\n\tsubstrToIdentifyTempDirs: string,\n\tstaleAgeInMillis: number,\n\ttempRootDir: string\n) {\n\tconst stalePlaygroundTempDirs = await findStalePlaygroundTempDirs(\n\t\tsubstrToIdentifyTempDirs,\n\t\tstaleAgeInMillis,\n\t\ttempRootDir\n\t);\n\tconst promisesToRemove = stalePlaygroundTempDirs.map(\n\t\t(stalePlaygroundTempDir) =>\n\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t// TODO: Non-blocking: Consider how to avoid conflicts with another CLI doing cleanup.\n\t\t\t\tfs.rm(stalePlaygroundTempDir, { recursive: true }, (err) => {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t`Failed to delete stale Playground temp dir: ${stalePlaygroundTempDir}`,\n\t\t\t\t\t\t\terr\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t\t`Deleted stale Playground temp dir: ${stalePlaygroundTempDir}`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t})\n\t);\n\tawait Promise.all(promisesToRemove);\n}\n\nasync function findStalePlaygroundTempDirs(\n\tsubstrToIdentifyTempDirs: string,\n\tstaleAgeInMillis: number,\n\ttempRootDir: string\n) {\n\ttry {\n\t\tconst tempPaths = fs\n\t\t\t.readdirSync(tempRootDir)\n\t\t\t.map((dirName) => path.join(tempRootDir, dirName));\n\n\t\tconst stalePlaygroundTempDirs = [];\n\t\tfor (const tempPath of tempPaths) {\n\t\t\tconst appearsToBeStale = await appearsToBeStalePlaygroundTempDir(\n\t\t\t\tsubstrToIdentifyTempDirs,\n\t\t\t\tstaleAgeInMillis,\n\t\t\t\ttempPath\n\t\t\t);\n\t\t\tif (appearsToBeStale) {\n\t\t\t\tstalePlaygroundTempDirs.push(tempPath);\n\t\t\t}\n\t\t}\n\t\treturn stalePlaygroundTempDirs;\n\t} catch (e) {\n\t\tlogger.warn(`Failed to find stale Playground temp dirs: ${e}`);\n\t\t// Failing to find stale temp dirs should not prevent the CLI from starting.\n\t\treturn [];\n\t}\n}\n\nasync function appearsToBeStalePlaygroundTempDir(\n\tsubstrToIdentifyTempDirs: string,\n\tstaleAgeInMillis: number,\n\tabsolutePath: string\n) {\n\tconst lstat = fs.lstatSync(absolutePath);\n\tif (!lstat.isDirectory()) {\n\t\t// A non-directory cannot be a Playground temp dir.\n\t\treturn false;\n\t}\n\n\tconst dirName = path.basename(absolutePath);\n\tif (!dirName.includes(substrToIdentifyTempDirs)) {\n\t\t// This doesn't look like one of our temp dirs.\n\t\treturn false;\n\t}\n\n\tconst match = dirName.match(\n\t\tnew RegExp(`^(.+)${substrToIdentifyTempDirs}(\\\\d+)-`)\n\t);\n\tif (!match) {\n\t\t// We cannot parse the temp dir name,\n\t\t// so there is nothing more to try.\n\t\treturn false;\n\t}\n\n\tconst info = {\n\t\tabsolutePath,\n\t\texecutableName: match[1],\n\t\tpid: match[2],\n\t};\n\n\tif (await doesProcessExist(info.pid, info.executableName)) {\n\t\t// It looks like the temp dir's process is still running.\n\t\treturn false;\n\t}\n\n\tconst STALE_DATE = Date.now() - staleAgeInMillis;\n\tconst dirStat = fs.statSync(absolutePath);\n\tif (dirStat.mtime.getTime() < STALE_DATE) {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nasync function doesProcessExist(pid: string, executableName: string) {\n\t// Define this type because there are no types for ps.list()\n\ttype ProcessInfo = {\n\t\tpid: string;\n\t\tcommand: string;\n\t};\n\t// Look for an existing process with the same PID and executable name.\n\tconst [existingProcess] = await new Promise<ProcessInfo[]>(\n\t\t(resolve, reject) => {\n\t\t\tps.list(\n\t\t\t\t{\n\t\t\t\t\tpid,\n\t\t\t\t\tname: executableName,\n\t\t\t\t\t// Remove path from executable name in the results.\n\t\t\t\t\tclean: true,\n\t\t\t\t},\n\t\t\t\t(err: any, processes: ProcessInfo[]) => {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresolve(processes);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t);\n\treturn (\n\t\t!!existingProcess &&\n\t\texistingProcess.pid === pid &&\n\t\texistingProcess.command === executableName\n\t);\n}\n","import { errorLogPath, logger, LogSeverity } from '@php-wasm/logger';\nimport type {\n\tPHPRequest,\n\tRemoteAPI,\n\tSupportedPHPVersion,\n} from '@php-wasm/universal';\nimport {\n\tPHPResponse,\n\texposeAPI,\n\texposeSyncAPI,\n\tprintDebugDetails,\n} from '@php-wasm/universal';\nimport type {\n\tBlueprintBundle,\n\tBlueprintV1Declaration,\n\tBlueprintV2Declaration,\n} from '@wp-playground/blueprints';\nimport { runBlueprintV1Steps } from '@wp-playground/blueprints';\nimport { RecommendedPHPVersion } from '@wp-playground/common';\nimport fs, { mkdirSync } from 'fs';\nimport type { Server } from 'http';\nimport { MessageChannel as NodeMessageChannel, Worker } from 'worker_threads';\n// @ts-ignore\nimport {\n\texpandAutoMounts,\n\tparseMountDirArguments,\n\tparseMountWithDelimiterArguments,\n} from './mounts';\nimport { startServer } from './start-server';\nimport type {\n\tMount,\n\tPlaygroundCliBlueprintV1Worker,\n} from './blueprints-v1/worker-thread-v1';\nimport type { PlaygroundCliBlueprintV2Worker } from './blueprints-v2/worker-thread-v2';\nimport { FileLockManagerForNode } from '@php-wasm/node';\nimport { LoadBalancer } from './load-balancer';\n/* eslint-disable no-console */\nimport { SupportedPHPVersions } from '@php-wasm/universal';\nimport { cpus } from 'os';\nimport { jspi } from 'wasm-feature-detect';\nimport type { MessagePort as NodeMessagePort } from 'worker_threads';\nimport yargs from 'yargs';\nimport { isValidWordPressSlug } from './is-valid-wordpress-slug';\nimport { resolveBlueprint } from './resolve-blueprint';\nimport { BlueprintsV2Handler } from './blueprints-v2/blueprints-v2-handler';\nimport { BlueprintsV1Handler } from './blueprints-v1/blueprints-v1-handler';\nimport { startBridge } from '@php-wasm/xdebug-bridge';\nimport path from 'path';\nimport os from 'os';\nimport {\n\tcleanupStalePlaygroundTempDirs,\n\tcreatePlaygroundCliTempDir,\n} from './temp-dir';\n\n// Inlined worker URLs for static analysis by downstream bundlers\n// These are replaced at build time by the Vite plugin in vite.config.ts\ndeclare const __WORKER_V1_URL__: string;\ndeclare const __WORKER_V2_URL__: string;\n\nexport const LogVerbosity = {\n\tQuiet: { name: 'quiet', severity: LogSeverity.Fatal },\n\tNormal: { name: 'normal', severity: LogSeverity.Info },\n\tDebug: { name: 'debug', severity: LogSeverity.Debug },\n} as const;\n\ntype LogVerbosity = (typeof LogVerbosity)[keyof typeof LogVerbosity]['name'];\n\nexport type WorkerType = 'v1' | 'v2';\n\nexport async function parseOptionsAndRunCLI() {\n\ttry {\n\t\t/**\n\t\t * @TODO This looks similar to Query API args https://wordpress.github.io/wordpress-playground/developers/apis/query-api/\n\t\t * Perhaps the two could be handled by the same code?\n\t\t */\n\t\tconst yargsObject = yargs(process.argv.slice(2))\n\t\t\t.usage('Usage: wp-playground <command> [options]')\n\t\t\t.positional('command', {\n\t\t\t\tdescribe: 'Command to run',\n\t\t\t\tchoices: ['server', 'run-blueprint', 'build-snapshot'] as const,\n\t\t\t\tdemandOption: true,\n\t\t\t})\n\t\t\t.option('outfile', {\n\t\t\t\tdescribe: 'When building, write to this output file.',\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: 'wordpress.zip',\n\t\t\t})\n\t\t\t.option('port', {\n\t\t\t\tdescribe: 'Port to listen on when serving.',\n\t\t\t\ttype: 'number',\n\t\t\t\tdefault: 9400,\n\t\t\t})\n\t\t\t.option('site-url', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Site URL to use for WordPress. Defaults to http://127.0.0.1:{port}',\n\t\t\t\ttype: 'string',\n\t\t\t})\n\t\t\t.option('php', {\n\t\t\t\tdescribe: 'PHP version to use.',\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: RecommendedPHPVersion,\n\t\t\t\tchoices: SupportedPHPVersions,\n\t\t\t})\n\t\t\t.option('wp', {\n\t\t\t\tdescribe: 'WordPress version to use.',\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: 'latest',\n\t\t\t})\n\t\t\t// @TODO: Support read-only mounts, e.g. via WORKERFS, a custom\n\t\t\t// ReadOnlyNODEFS, or by copying the files into MEMFS\n\t\t\t.option('mount', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Mount a directory to the PHP runtime (can be used multiple times). Format: /host/path:/vfs/path',\n\t\t\t\ttype: 'array',\n\t\t\t\tstring: true,\n\t\t\t\tcoerce: parseMountWithDelimiterArguments,\n\t\t\t})\n\t\t\t.option('mount-before-install', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Mount a directory to the PHP runtime before WordPress installation (can be used multiple times). Format: /host/path:/vfs/path',\n\t\t\t\ttype: 'array',\n\t\t\t\tstring: true,\n\t\t\t\tcoerce: parseMountWithDelimiterArguments,\n\t\t\t})\n\t\t\t.option('mount-dir', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Mount a directory to the PHP runtime (can be used multiple times). Format: \"/host/path\" \"/vfs/path\"',\n\t\t\t\ttype: 'array',\n\t\t\t\tnargs: 2,\n\t\t\t\tarray: true,\n\t\t\t\t// coerce: parseMountDirArguments,\n\t\t\t})\n\t\t\t.option('mount-dir-before-install', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Mount a directory before WordPress installation (can be used multiple times). Format: \"/host/path\" \"/vfs/path\"',\n\t\t\t\ttype: 'string',\n\t\t\t\tnargs: 2,\n\t\t\t\tarray: true,\n\t\t\t\tcoerce: parseMountDirArguments,\n\t\t\t})\n\t\t\t.option('login', {\n\t\t\t\tdescribe: 'Should log the user in',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('blueprint', {\n\t\t\t\tdescribe: 'Blueprint to execute.',\n\t\t\t\ttype: 'string',\n\t\t\t})\n\t\t\t.option('blueprint-may-read-adjacent-files', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Consent flag: Allow \"bundled\" resources in a local blueprint to read files in the same directory as the blueprint file.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('skip-wordpress-setup', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Do not download, unzip, and install WordPress. Useful for mounting a pre-configured WordPress directory at /wordpress.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('skip-sqlite-setup', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Skip the SQLite integration plugin setup to allow the WordPress site to use MySQL.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t// Hidden - Deprecated in favor of verbosity\n\t\t\t.option('quiet', {\n\t\t\t\tdescribe: 'Do not output logs and progress messages.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t\thidden: true,\n\t\t\t})\n\t\t\t.option('verbosity', {\n\t\t\t\tdescribe: 'Output logs and progress messages.',\n\t\t\t\ttype: 'string',\n\t\t\t\tchoices: Object.values(LogVerbosity).map(\n\t\t\t\t\t(verbosity) => verbosity.name\n\t\t\t\t),\n\t\t\t\tdefault: 'normal',\n\t\t\t})\n\t\t\t.option('debug', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Print PHP error log content if an error occurs during Playground boot.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('auto-mount', {\n\t\t\t\tdescribe: `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.`,\n\t\t\t\ttype: 'string',\n\t\t\t})\n\t\t\t.option('follow-symlinks', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Allow Playground to follow symlinks by automatically mounting symlinked directories and files encountered in mounted directories. \\nWarning: Following symlinks will expose files outside mounted directories to Playground and could be a security risk.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('experimental-trace', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Print detailed messages about system behavior to the console. Useful for troubleshooting.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t\t// Hide this option because we want to replace with a more general log-level flag.\n\t\t\t\thidden: true,\n\t\t\t})\n\t\t\t.option('internal-cookie-store', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Enable internal cookie handling. When enabled, Playground will manage cookies internally using ' +\n\t\t\t\t\t'an HttpCookieStore that persists cookies across requests. When disabled, cookies are handled ' +\n\t\t\t\t\t'externally (e.g., by a browser in Node.js environments).',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('xdebug', {\n\t\t\t\tdescribe: 'Enable Xdebug.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('experimental-devtools', {\n\t\t\t\tdescribe: 'Enable experimental browser development tools.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('experimental-multi-worker', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Enable experimental multi-worker support which requires ' +\n\t\t\t\t\t'a /wordpress directory backed by a real filesystem. ' +\n\t\t\t\t\t'Pass a positive number to specify the number of workers to use. ' +\n\t\t\t\t\t'Otherwise, default to the number of CPUs minus 1.',\n\t\t\t\ttype: 'number',\n\t\t\t\tcoerce: (value?: number) => value ?? cpus().length - 1,\n\t\t\t})\n\t\t\t.option('experimental-blueprints-v2-runner', {\n\t\t\t\tdescribe: 'Use the experimental Blueprint V2 runner.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t\t// Remove the \"hidden\" flag once Blueprint V2 is fully supported\n\t\t\t\thidden: true,\n\t\t\t})\n\t\t\t.option('mode', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Blueprints v2 runner mode to use. This option is required when using the --experimental-blueprints-v2-runner flag with a blueprint.',\n\t\t\t\ttype: 'string',\n\t\t\t\tchoices: ['create-new-site', 'apply-to-existing-site'],\n\t\t\t\t// Remove the \"hidden\" flag once Blueprint V2 is fully supported\n\t\t\t\thidden: true,\n\t\t\t})\n\t\t\t.showHelpOnFail(false)\n\t\t\t.strictOptions()\n\t\t\t.check(async (args) => {\n\t\t\t\t// Support multiple spellings of \"WordPress\"\n\t\t\t\tif (\n\t\t\t\t\targs['skip-wordpress-setup'] ||\n\t\t\t\t\targs['skipWordpressSetup']\n\t\t\t\t) {\n\t\t\t\t\targs['skipWordPressSetup'] = true;\n\t\t\t\t}\n\n\t\t\t\tif (args.wp !== undefined && !isValidWordPressSlug(args.wp)) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// Check if is valid URL\n\t\t\t\t\t\tnew URL(args.wp);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'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\"'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (args['site-url'] !== undefined && args['site-url'] !== '') {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnew URL(args['site-url']);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Invalid site-url \"${args['site-url']}\". Please provide a valid URL (e.g., http://localhost:8080 or https://example.com)`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (args['auto-mount']) {\n\t\t\t\t\tlet autoMountIsDir = false;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst autoMountStats = fs.statSync(args['auto-mount']);\n\t\t\t\t\t\tautoMountIsDir = autoMountStats.isDirectory();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tautoMountIsDir = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!autoMountIsDir) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`The specified --auto-mount path is not a directory: '${args['auto-mount']}'.`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (args['experimental-multi-worker'] !== undefined) {\n\t\t\t\t\tif (args['experimental-multi-worker'] <= 1) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'The --experimental-multi-worker flag must be a positive integer greater than 1.'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (args['experimental-blueprints-v2-runner'] === true) {\n\t\t\t\t\tif (args['mode'] !== undefined) {\n\t\t\t\t\t\tif ('skip-wordpress-setup' in args) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t'The --skipWordPressSetup option cannot be used with the --mode option. Use one or the other.'\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ('skip-sqlite-setup' in args) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t'The --skipSqliteSetup option is not supported in Blueprint V2 mode.'\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (args['auto-mount'] !== undefined) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t'The --mode option cannot be used with --auto-mount because --auto-mount automatically sets the mode.'\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Support the legacy v1 runner options\n\t\t\t\t\t\tif (args['skip-wordpress-setup'] === true) {\n\t\t\t\t\t\t\targs['mode'] = 'apply-to-existing-site';\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\targs['mode'] = 'create-new-site';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Support the legacy v1 runner options\n\t\t\t\t\tconst allow = (args['allow'] as string[]) || [];\n\n\t\t\t\t\tif (args['followSymlinks'] === true) {\n\t\t\t\t\t\tallow.push('follow-symlinks');\n\t\t\t\t\t}\n\n\t\t\t\t\tif (args['blueprint-may-read-adjacent-files'] === true) {\n\t\t\t\t\t\tallow.push('read-local-fs');\n\t\t\t\t\t}\n\n\t\t\t\t\targs['allow'] = allow;\n\t\t\t\t} else {\n\t\t\t\t\tif (args['mode'] !== undefined) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'The --mode option requires the --experimentalBlueprintsV2Runner flag.'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn true;\n\t\t\t});\n\n\t\tyargsObject.wrap(yargsObject.terminalWidth());\n\t\tconst args = await yargsObject.argv;\n\n\t\tconst command = args._[0] as string;\n\n\t\tif (!['run-blueprint', 'server', 'build-snapshot'].includes(command)) {\n\t\t\tyargsObject.showHelp();\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\tconst cliArgs = {\n\t\t\t...args,\n\t\t\tcommand,\n\t\t\tmount: [...(args.mount || []), ...(args['mount-dir'] || [])],\n\t\t\t'mount-before-install': [\n\t\t\t\t...(args['mount-before-install'] || []),\n\t\t\t\t...(args['mount-dir-before-install'] || []),\n\t\t\t],\n\t\t} as RunCLIArgs;\n\n\t\tawait runCLI(cliArgs);\n\t} catch (e) {\n\t\tif (!(e instanceof Error)) {\n\t\t\tthrow e;\n\t\t}\n\t\tconst debug = process.argv.includes('--debug');\n\t\tif (debug) {\n\t\t\tprintDebugDetails(e);\n\t\t} else {\n\t\t\tconst messageChain = [];\n\t\t\tlet currentError = e;\n\t\t\tdo {\n\t\t\t\tmessageChain.push(currentError.message);\n\t\t\t\tcurrentError = currentError.cause as Error;\n\t\t\t} while (currentError instanceof Error);\n\t\t\tconsole.error(\n\t\t\t\t'\\x1b[1m' + messageChain.join(' caused by ') + '\\x1b[0m'\n\t\t\t);\n\t\t}\n\t\tprocess.exit(1);\n\t}\n}\n\nexport interface RunCLIArgs {\n\tblueprint?:\n\t\t| BlueprintV1Declaration\n\t\t| BlueprintV2Declaration\n\t\t| BlueprintBundle;\n\tcommand: 'server' | 'run-blueprint' | 'build-snapshot';\n\tdebug?: boolean;\n\tlogin?: boolean;\n\tmount?: Mount[];\n\t'mount-before-install'?: Mount[];\n\toutfile?: string;\n\tphp?: SupportedPHPVersion;\n\tport?: number;\n\t'site-url'?: string;\n\tquiet?: boolean;\n\tverbosity?: LogVerbosity;\n\twp?: string;\n\tautoMount?: string;\n\texperimentalMultiWorker?: number;\n\texperimentalTrace?: boolean;\n\texitOnPrimaryWorkerCrash?: boolean;\n\tinternalCookieStore?: boolean;\n\t'additional-blueprint-steps'?: any[];\n\txdebug?: boolean;\n\texperimentalDevtools?: boolean;\n\t'experimental-blueprints-v2-runner'?: boolean;\n\n\t// --------- Blueprint V1 args -----------\n\tskipWordPressSetup?: boolean;\n\tskipSqliteSetup?: boolean;\n\tfollowSymlinks?: boolean;\n\t'blueprint-may-read-adjacent-files'?: boolean;\n\n\t// --------- Blueprint V2 args -----------\n\tmode?: 'mount-only' | 'create-new-site' | 'apply-to-existing-site';\n\n\t// --------- Blueprint V2 args (not available via CLI yet) -----------\n\t'db-engine'?: 'sqlite' | 'mysql';\n\t'db-host'?: string;\n\t'db-user'?: string;\n\t'db-pass'?: string;\n\t'db-name'?: string;\n\t'db-path'?: string;\n\t'truncate-new-site-directory'?: boolean;\n\tallow?: string;\n}\n\ntype PlaygroundCliWorker =\n\t| PlaygroundCliBlueprintV1Worker\n\t| PlaygroundCliBlueprintV2Worker;\n\nexport interface RunCLIServer extends AsyncDisposable {\n\tplayground: RemoteAPI<PlaygroundCliWorker>;\n\tserver: Server;\n\t[Symbol.asyncDispose](): Promise<void>;\n\t// Expose the number of worker threads to the test runner.\n\tworkerThreadCount: number;\n}\n\nexport async function runCLI(args: RunCLIArgs): Promise<RunCLIServer> {\n\tlet loadBalancer: LoadBalancer;\n\tlet playground: RemoteAPI<PlaygroundCliWorker>;\n\n\tconst playgroundsToCleanUp: {\n\t\tplayground: RemoteAPI<PlaygroundCliWorker>;\n\t\tworker: Worker;\n\t}[] = [];\n\n\t/**\n\t * Expand auto-mounts to include the necessary mounts and steps\n\t * when running in auto-mount mode.\n\t */\n\tif (args.autoMount !== undefined) {\n\t\tif (args.autoMount === '') {\n\t\t\t// No auto-mount path was provided, so use the current working directory.\n\t\t\t// Note: We default here instead of in the yargs declaration because\n\t\t\t// it allows us to test the default as part of the runCLI() unit tests.\n\t\t\targs = { ...args, autoMount: process.cwd() };\n\t\t}\n\t\targs = expandAutoMounts(args);\n\t}\n\n\t// Keeping 'quiet' option to preserve backward compatibility\n\tif (args.quiet) {\n\t\targs.verbosity = 'quiet';\n\t\tdelete args['quiet'];\n\t}\n\n\t// Promote \"debug\" flag to verbosity but keep args.debug around – the\n\t// program behavior may change in more ways than just logging verbosity\n\t// when debug mode is enabled, e.g. error objects may carry additional details.\n\tif (args.debug) {\n\t\targs.verbosity = 'debug';\n\t} else if (args.verbosity === 'debug') {\n\t\targs.debug = true;\n\t}\n\n\tif (args.verbosity) {\n\t\tconst severity = Object.values(LogVerbosity).find(\n\t\t\t(v) => v.name === args.verbosity\n\t\t)!.severity;\n\t\tlogger.setSeverityFilterLevel(severity);\n\t}\n\n\t// Declare file lock manager outside scope of startServer\n\t// so we can look at it when debugging request handling.\n\tconst nativeFlockSync =\n\t\tos.platform() === 'win32'\n\t\t\t? // @TODO: Enable fs-ext here when it works with Windows.\n\t\t\t undefined\n\t\t\t: await import('fs-ext')\n\t\t\t\t\t.then((m) => m.flockSync)\n\t\t\t\t\t.catch(() => {\n\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t'The fs-ext package is not installed. ' +\n\t\t\t\t\t\t\t\t'Internal file locking will not be integrated with ' +\n\t\t\t\t\t\t\t\t'host OS file locking.'\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t});\n\tconst fileLockManager = new FileLockManagerForNode(nativeFlockSync);\n\n\tlet wordPressReady = false;\n\tlet isFirstRequest = true;\n\n\tlogger.log('Starting a PHP server...');\n\n\treturn startServer({\n\t\tport: args['port'] as number,\n\t\tonBind: async (server: Server, port: number): Promise<RunCLIServer> => {\n\t\t\tconst serverUrl = `http://127.0.0.1:${port}`;\n\t\t\tconst siteUrl = args['site-url'] || serverUrl;\n\n\t\t\t// Create the blueprints handler\n\t\t\tconst totalWorkerCount = args.experimentalMultiWorker ?? 1;\n\t\t\tconst processIdSpaceLength = Math.floor(\n\t\t\t\tNumber.MAX_SAFE_INTEGER / totalWorkerCount\n\t\t\t);\n\n\t\t\t/*\n\t\t\t * Use a real temp dir as a target for the following Playground paths\n\t\t\t * so that multiple worker threads can share the same files.\n\t\t\t * - /internal\n\t\t\t * - /tmp\n\t\t\t * - /wordpress\n\t\t\t *\n\t\t\t * Sharing the same files leads to faster boot times and uses less memory\n\t\t\t * because we don't have to create or maintain multiple copies of the same files.\n\t\t\t */\n\t\t\tconst tempDirNameDelimiter = '-playground-cli-site-';\n\t\t\tconst nativeDirPath = await createPlaygroundCliTempDir(\n\t\t\t\ttempDirNameDelimiter\n\t\t\t);\n\n\t\t\t// We do not know the system temp dir,\n\t\t\t// but we can try to infer from the location of the current temp dir.\n\t\t\tconst tempDirRoot = path.dirname(nativeDirPath);\n\n\t\t\tconst twoDaysInMillis = 2 * 24 * 60 * 60 * 1000;\n\t\t\tconst tempDirStaleAgeInMillis = twoDaysInMillis;\n\n\t\t\t// NOTE: This is an async operation, but we do not care to block on it.\n\t\t\t// Let's let the cleanup happen as the main thread has time.\n\t\t\tcleanupStalePlaygroundTempDirs(\n\t\t\t\ttempDirNameDelimiter,\n\t\t\t\ttempDirStaleAgeInMillis,\n\t\t\t\ttempDirRoot\n\t\t\t);\n\n\t\t\t// NOTE: We do not add mount declarations for /internal here\n\t\t\t// because it will be mounted as part of php-wasm init.\n\t\t\tconst nativeInternalDirPath = path.join(nativeDirPath, 'internal');\n\t\t\tmkdirSync(nativeInternalDirPath);\n\n\t\t\tconst userProvidableNativeSubdirs = [\n\t\t\t\t'wordpress',\n\t\t\t\t// Note: These dirs are from Emscripten's \"default dirs\" list:\n\t\t\t\t// https://github.com/emscripten-core/emscripten/blob/f431ec220e472e1f8d3db6b52fe23fb377facf30/src/lib/libfs.js#L1400-L1402\n\t\t\t\t//\n\t\t\t\t// Any Playground process with multiple workers may assume\n\t\t\t\t// these are part of a shared filesystem, so let's recognize\n\t\t\t\t// them explicitly here.\n\t\t\t\t'tmp',\n\t\t\t\t'home',\n\t\t\t];\n\n\t\t\tfor (const subdirName of userProvidableNativeSubdirs) {\n\t\t\t\tconst isMountingSubdirName = (mount: Mount) =>\n\t\t\t\t\tmount.vfsPath === `/${subdirName}`;\n\t\t\t\tconst thisSubdirHasAMount =\n\t\t\t\t\targs['mount-before-install']?.some(isMountingSubdirName) ||\n\t\t\t\t\targs['mount']?.some(isMountingSubdirName);\n\t\t\t\tif (!thisSubdirHasAMount) {\n\t\t\t\t\t// The user hasn't requested mounting a different native dir for this path,\n\t\t\t\t\t// so let's create a mount from within our native temp dir.\n\t\t\t\t\tconst nativeSubdirPath = path.join(\n\t\t\t\t\t\tnativeDirPath,\n\t\t\t\t\t\tsubdirName\n\t\t\t\t\t);\n\t\t\t\t\tmkdirSync(nativeSubdirPath);\n\n\t\t\t\t\tif (args['mount-before-install'] === undefined) {\n\t\t\t\t\t\targs['mount-before-install'] = [];\n\t\t\t\t\t}\n\n\t\t\t\t\t// Make the real mount first so any further subdirs are mounted into it.\n\t\t\t\t\targs['mount-before-install'].unshift({\n\t\t\t\t\t\tvfsPath: `/${subdirName}`,\n\t\t\t\t\t\thostPath: nativeSubdirPath,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet handler: BlueprintsV1Handler | BlueprintsV2Handler;\n\t\t\tif (args['experimental-blueprints-v2-runner']) {\n\t\t\t\thandler = new BlueprintsV2Handler(args, {\n\t\t\t\t\tsiteUrl,\n\t\t\t\t\tprocessIdSpaceLength,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\thandler = new BlueprintsV1Handler(args, {\n\t\t\t\t\tsiteUrl,\n\t\t\t\t\tprocessIdSpaceLength,\n\t\t\t\t});\n\n\t\t\t\tif (typeof args.blueprint === 'string') {\n\t\t\t\t\targs.blueprint = await resolveBlueprint({\n\t\t\t\t\t\tsourceString: args.blueprint,\n\t\t\t\t\t\tblueprintMayReadAdjacentFiles:\n\t\t\t\t\t\t\targs['blueprint-may-read-adjacent-files'] === true,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Kick off worker threads now to save time later.\n\t\t\t// There is no need to wait for other async processes to complete.\n\t\t\tconst promisedWorkers = spawnWorkerThreads(\n\t\t\t\ttotalWorkerCount,\n\t\t\t\thandler.getWorkerType(),\n\t\t\t\t({ exitCode, isMain, workerIndex }) => {\n\t\t\t\t\tif (exitCode === 0) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlogger.error(\n\t\t\t\t\t\t`Worker ${workerIndex} exited with code ${exitCode}\\n`\n\t\t\t\t\t);\n\t\t\t\t\t// If the primary worker crashes, exit the entire process.\n\t\t\t\t\tif (!isMain) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (!args.exitOnPrimaryWorkerCrash) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tlogger.log(`Setting up WordPress ${args.wp}`);\n\n\t\t\ttry {\n\t\t\t\tconst [initialWorker, ...additionalWorkers] =\n\t\t\t\t\tawait promisedWorkers;\n\n\t\t\t\tconst fileLockManagerPort = await exposeFileLockManager(\n\t\t\t\t\tfileLockManager\n\t\t\t\t);\n\n\t\t\t\t// Boot the primary worker using the handler\n\t\t\t\tplayground = await handler.bootPrimaryWorker(\n\t\t\t\t\tinitialWorker.phpPort,\n\t\t\t\t\tfileLockManagerPort,\n\t\t\t\t\tnativeInternalDirPath\n\t\t\t\t);\n\t\t\t\tplaygroundsToCleanUp.push({\n\t\t\t\t\tplayground,\n\t\t\t\t\tworker: initialWorker.worker,\n\t\t\t\t});\n\n\t\t\t\tawait playground.isReady();\n\t\t\t\twordPressReady = true;\n\t\t\t\tlogger.log(`Booted!`);\n\n\t\t\t\tloadBalancer = new LoadBalancer(playground);\n\n\t\t\t\tif (!args['experimental-blueprints-v2-runner']) {\n\t\t\t\t\tconst compiledBlueprint = await (\n\t\t\t\t\t\thandler as BlueprintsV1Handler\n\t\t\t\t\t).compileInputBlueprint(\n\t\t\t\t\t\targs['additional-blueprint-steps'] || []\n\t\t\t\t\t);\n\n\t\t\t\t\tif (compiledBlueprint) {\n\t\t\t\t\t\tlogger.log(`Running the Blueprint...`);\n\t\t\t\t\t\tawait runBlueprintV1Steps(\n\t\t\t\t\t\t\tcompiledBlueprint,\n\t\t\t\t\t\t\tplayground\n\t\t\t\t\t\t);\n\t\t\t\t\t\tlogger.log(`Finished running the blueprint`);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (args.command === 'build-snapshot') {\n\t\t\t\t\tawait zipSite(playground, args.outfile as string);\n\t\t\t\t\tlogger.log(`WordPress exported to ${args.outfile}`);\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t} else if (args.command === 'run-blueprint') {\n\t\t\t\t\tlogger.log(`Blueprint executed`);\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\targs.experimentalMultiWorker &&\n\t\t\t\t\targs.experimentalMultiWorker > 1\n\t\t\t\t) {\n\t\t\t\t\tlogger.log(`Preparing additional workers...`);\n\n\t\t\t\t\t// Boot additional workers using the handler\n\t\t\t\t\tconst initialWorkerProcessIdSpace = processIdSpaceLength;\n\t\t\t\t\tawait Promise.all(\n\t\t\t\t\t\tadditionalWorkers.map(async (worker, index) => {\n\t\t\t\t\t\t\tconst firstProcessId =\n\t\t\t\t\t\t\t\tinitialWorkerProcessIdSpace +\n\t\t\t\t\t\t\t\tindex * processIdSpaceLength;\n\n\t\t\t\t\t\t\tconst fileLockManagerPort =\n\t\t\t\t\t\t\t\tawait exposeFileLockManager(fileLockManager);\n\n\t\t\t\t\t\t\tconst additionalPlayground =\n\t\t\t\t\t\t\t\tawait handler.bootSecondaryWorker({\n\t\t\t\t\t\t\t\t\tworker,\n\t\t\t\t\t\t\t\t\tfileLockManagerPort,\n\t\t\t\t\t\t\t\t\tfirstProcessId,\n\t\t\t\t\t\t\t\t\tnativeInternalDirPath,\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tplaygroundsToCleanUp.push({\n\t\t\t\t\t\t\t\tplayground: additionalPlayground,\n\t\t\t\t\t\t\t\tworker: worker.worker,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tloadBalancer.addWorker(additionalPlayground);\n\t\t\t\t\t\t})\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tlogger.log(\n\t\t\t\t\t`WordPress is running on ${serverUrl} with ${totalWorkerCount} worker(s)`\n\t\t\t\t);\n\n\t\t\t\tif (args.experimentalDevtools && args.xdebug) {\n\t\t\t\t\tconst bridge = await startBridge({\n\t\t\t\t\t\tgetPHPFile: async (path: string) =>\n\t\t\t\t\t\t\tawait playground!.readFileAsText(path),\n\t\t\t\t\t});\n\n\t\t\t\t\tbridge.start();\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tplayground,\n\t\t\t\t\tserver,\n\t\t\t\t\t[Symbol.asyncDispose]: async function disposeCLI() {\n\t\t\t\t\t\tawait Promise.all(\n\t\t\t\t\t\t\tplaygroundsToCleanUp.map(\n\t\t\t\t\t\t\t\tasync ({ playground, worker }) => {\n\t\t\t\t\t\t\t\t\tawait playground.dispose();\n\t\t\t\t\t\t\t\t\tawait worker.terminate();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t);\n\t\t\t\t\t\tawait new Promise((resolve) => server.close(resolve));\n\t\t\t\t\t},\n\t\t\t\t\tworkerThreadCount: totalWorkerCount,\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tif (!args.debug) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlet phpLogs = '';\n\t\t\t\tif (await playground?.fileExists(errorLogPath)) {\n\t\t\t\t\tphpLogs = await playground.readFileAsText(errorLogPath);\n\t\t\t\t}\n\t\t\t\tthrow new Error(phpLogs, { cause: error });\n\t\t\t}\n\t\t},\n\t\tasync handleRequest(request: PHPRequest) {\n\t\t\tif (!wordPressReady) {\n\t\t\t\treturn PHPResponse.forHttpCode(\n\t\t\t\t\t502,\n\t\t\t\t\t'WordPress is not ready yet'\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Clear the playground_auto_login_already_happened cookie on the first request.\n\t\t\t// Otherwise the first Playground CLI server started on the machine will set it,\n\t\t\t// all the subsequent runs will get the stale cookie, and the auto-login will\n\t\t\t// assume they don't have to auto-login again.\n\t\t\tif (isFirstRequest) {\n\t\t\t\tisFirstRequest = false;\n\t\t\t\tconst headers: Record<string, string[]> = {\n\t\t\t\t\t'Content-Type': ['text/plain'],\n\t\t\t\t\t'Content-Length': ['0'],\n\t\t\t\t\tLocation: ['/'],\n\t\t\t\t};\n\t\t\t\tif (\n\t\t\t\t\trequest.headers?.['cookie']?.includes(\n\t\t\t\t\t\t'playground_auto_login_already_happened'\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\theaders['Set-Cookie'] = [\n\t\t\t\t\t\t'playground_auto_login_already_happened=1; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/',\n\t\t\t\t\t];\n\t\t\t\t}\n\t\t\t\treturn new PHPResponse(302, headers, new Uint8Array());\n\t\t\t}\n\t\t\treturn await loadBalancer.handleRequest(request);\n\t\t},\n\t});\n}\n\nexport type SpawnedWorker = {\n\tworker: Worker;\n\tphpPort: NodeMessagePort;\n};\nasync function spawnWorkerThreads(\n\tcount: number,\n\tworkerType: WorkerType,\n\tonWorkerExit: (options: {\n\t\texitCode: number;\n\t\tisMain: boolean;\n\t\tworkerIndex: number;\n\t}) => void\n): Promise<SpawnedWorker[]> {\n\tconst promises = [];\n\tfor (let i = 0; i < count; i++) {\n\t\tconst worker = await spawnWorkerThread(workerType);\n\t\tconst onExit: (code: number) => void = (code: number) => {\n\t\t\tonWorkerExit({\n\t\t\t\texitCode: code,\n\t\t\t\tisMain: i === 0,\n\t\t\t\tworkerIndex: i,\n\t\t\t});\n\t\t};\n\t\tpromises.push(\n\t\t\tnew Promise<{ worker: Worker; phpPort: NodeMessagePort }>(\n\t\t\t\t(resolve, reject) => {\n\t\t\t\t\tworker.once('message', function (message: any) {\n\t\t\t\t\t\t// Let the worker confirm it has initialized.\n\t\t\t\t\t\t// We could use the 'online' event to detect start of JS execution,\n\t\t\t\t\t\t// but that would miss initialization errors.\n\t\t\t\t\t\tif (message.command === 'worker-script-initialized') {\n\t\t\t\t\t\t\tresolve({ worker, phpPort: message.phpPort });\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tworker.once('error', function (e: Error) {\n\t\t\t\t\t\tconsole.error(e);\n\t\t\t\t\t\tconst error = new Error(\n\t\t\t\t\t\t\t`Worker failed to load worker. ${\n\t\t\t\t\t\t\t\te.message ? `Original error: ${e.message}` : ''\n\t\t\t\t\t\t\t}`\n\t\t\t\t\t\t);\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t});\n\t\t\t\t\tworker.once('exit', onExit);\n\t\t\t\t}\n\t\t\t)\n\t\t);\n\t}\n\treturn Promise.all(promises);\n}\n\n/**\n * A statically analyzable function that spawns a worker thread of a given type.\n *\n * **Important:** This function builds to code that has the worker URL hardcoded\n * inline, e.g. `new Worker(new URL('./worker-thread-v1.js', import.meta.url))`.\n * This allows the downstream consumers to statically analyze the code, recognize\n * it uses workers, create new entrypoints, and rewrite the new Worker() calls.\n *\n * @param workerType\n * @returns\n */\nasync function spawnWorkerThread(workerType: 'v1' | 'v2') {\n\t/**\n\t * When running the CLI from source via `node cli.ts`, the Vite-provided\n\t * __WORKER_V1_URL__ and __WORKER_V2_URL__ are undefined. Let's set them to\n\t * the correct paths.\n\t */\n\tif (typeof __WORKER_V1_URL__ === 'undefined') {\n\t\t// @ts-expect-error\n\t\tglobalThis['__WORKER_V1_URL__'] = './blueprints-v1/worker-thread-v1.ts';\n\t}\n\tif (typeof __WORKER_V2_URL__ === 'undefined') {\n\t\t// @ts-expect-error\n\t\tglobalThis['__WORKER_V2_URL__'] = './blueprints-v2/worker-thread-v2.ts';\n\t}\n\tif (workerType === 'v1') {\n\t\treturn new Worker(new URL(__WORKER_V1_URL__, import.meta.url));\n\t} else {\n\t\treturn new Worker(new URL(__WORKER_V2_URL__, import.meta.url));\n\t}\n}\n\n/**\n * Expose the file lock manager API on a MessagePort and return it.\n *\n * @see comlink-sync.ts\n * @see phpwasm-emscripten-library-file-locking-for-node.js\n */\nasync function exposeFileLockManager(fileLockManager: FileLockManagerForNode) {\n\tconst { port1, port2 } = new NodeMessageChannel();\n\tif (await jspi()) {\n\t\t/**\n\t\t * When JSPI is available, the worker thread expects an asynchronous API.\n\t\t *\n\t\t * @see worker-thread.ts\n\t\t * @see comlink-sync.ts\n\t\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t\t */\n\t\texposeAPI(fileLockManager, null, port1);\n\t} else {\n\t\t/**\n\t\t * When JSPI is not available, the worker thread expects a synchronous API.\n\t\t *\n\t\t * @see worker-thread.ts\n\t\t * @see comlink-sync.ts\n\t\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t\t */\n\t\tawait exposeSyncAPI(fileLockManager, port1);\n\t}\n\treturn port2;\n}\n\nasync function zipSite(\n\tplayground: RemoteAPI<PlaygroundCliWorker>,\n\toutfile: string\n) {\n\tawait playground.run({\n\t\tcode: `<?php\n\t\t$zip = new ZipArchive();\n\t\tif(false === $zip->open('/tmp/build.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {\n\t\t\tthrow new Exception('Failed to create ZIP');\n\t\t}\n\t\t$files = new RecursiveIteratorIterator(\n\t\t\tnew RecursiveDirectoryIterator('/wordpress')\n\t\t);\n\t\tforeach ($files as $file) {\n\t\t\techo $file . PHP_EOL;\n\t\t\tif (!$file->isFile()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t$zip->addFile($file->getPathname(), $file->getPathname());\n\t\t}\n\t\t$zip->close();\n\n\t`,\n\t});\n\tconst zip = await playground.readFileAsBuffer('/tmp/build.zip');\n\tfs.writeFileSync(outfile, zip);\n}\n"],"names":["startServer","options","app","express","server","resolve","reject","address","req","res","phpResponse","parseHeaders","bufferRequestBody","key","port","body","chunk","requestHeaders","i","LoadBalancer","initialWorker","worker","request","smallestWorkerLoad","workerLoad","promiseForResponse","isValidWordPressSlug","version","resolveBlueprint","sourceString","blueprintMayReadAdjacentFiles","resolveRemoteBlueprint","blueprintPath","path","fs","stat","extension","ZipFilesystem","blueprintText","contextPath","nodeJsFilesystem","NodeJsFilesystem","OverlayFilesystem","InMemoryFilesystem","BlueprintsV2Handler","args","phpPort","fileLockManagerPort","nativeInternalDirPath","playground","consumeAPI","workerBootArgs","firstProcessId","writeStream","message","finalUpdate","CACHE_FOLDER","os","fetchSqliteIntegration","monitor","cachedDownload","remoteUrl","cacheKey","artifactPath","downloadTo","readAsFile","localPath","reader","tmpPath","writer","done","value","err","fileName","basename","BlueprintsV1Handler","wpDetails","EmscriptenDownloadMonitor","progressReached100","e","loaded","total","percentProgress","resolveWordPressRelease","logger","preinstalledWpContentPath","wordPressZip","sqliteIntegrationPluginZip","followSymlinks","trace","mountsBeforeWpInstall","mountsAfterWpInstall","runtimeConfiguration","resolveRuntimeConfiguration","zipDirectory","additionalPlayground","additionalBlueprintSteps","blueprint","tracker","ProgressTracker","lastCaption","progressInteger","compileBlueprintV1","resolvedBlueprint","isBlueprintBundle","RecommendedPHPVersion","LogVerbosity","createPlaygroundCliTempDir","substrToIdentifyTempDirs","autoCleanup","tempDirPrefix","nativeDirPath","tmpDir","tmpSetGracefulCleanup","cleanupStalePlaygroundTempDirs","staleAgeInMillis","tempRootDir","promisesToRemove","findStalePlaygroundTempDirs","stalePlaygroundTempDir","tempPaths","dirName","stalePlaygroundTempDirs","tempPath","appearsToBeStalePlaygroundTempDir","absolutePath","match","info","doesProcessExist","STALE_DATE","pid","executableName","existingProcess","ps","processes","LogSeverity","parseOptionsAndRunCLI","yargsObject","yargs","SupportedPHPVersions","parseMountWithDelimiterArguments","parseMountDirArguments","verbosity","cpus","autoMountIsDir","allow","command","cliArgs","runCLI","printDebugDetails","messageChain","currentError","loadBalancer","playgroundsToCleanUp","expandAutoMounts","severity","v","nativeFlockSync","m","fileLockManager","FileLockManagerForNode","wordPressReady","isFirstRequest","serverUrl","siteUrl","totalWorkerCount","processIdSpaceLength","tempDirNameDelimiter","tempDirRoot","tempDirStaleAgeInMillis","mkdirSync","userProvidableNativeSubdirs","subdirName","isMountingSubdirName","mount","nativeSubdirPath","handler","promisedWorkers","spawnWorkerThreads","exitCode","isMain","workerIndex","additionalWorkers","exposeFileLockManager","compiledBlueprint","runBlueprintV1Steps","zipSite","initialWorkerProcessIdSpace","index","startBridge","error","phpLogs","errorLogPath","PHPResponse","headers","count","workerType","onWorkerExit","promises","spawnWorkerThread","onExit","code","Worker","_documentCurrentScript","port1","port2","NodeMessageChannel","jspi","exposeAPI","exposeSyncAPI","outfile","zip"],"mappings":"ulCAaA,eAAsBA,GACrBC,EACwB,CACxB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