@wp-playground/cli 3.0.41 → 3.0.42
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 +3 -3
- package/blueprints-v2/blueprints-v2-handler.d.ts +3 -3
- package/cli-output.d.ts +114 -0
- package/cli.cjs +1 -1
- package/cli.js +1 -1
- package/index.cjs +1 -1
- package/index.js +1 -1
- package/package.json +13 -13
- package/run-cli-B8Dv6R-o.cjs +64 -0
- package/run-cli-B8Dv6R-o.cjs.map +1 -0
- package/{run-cli-vem_UKTF.js → run-cli-NcKUE5gJ.js} +688 -532
- package/run-cli-NcKUE5gJ.js.map +1 -0
- package/worker-thread-v1.cjs +1 -1
- package/worker-thread-v1.js +1 -1
- package/worker-thread-v2.cjs +1 -1
- package/worker-thread-v2.js +1 -1
- package/run-cli-DJNPNQa1.cjs +0 -53
- package/run-cli-DJNPNQa1.cjs.map +0 -1
- package/run-cli-vem_UKTF.js.map +0 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
|
-
/// <reference types="node" />
|
|
3
2
|
import type { PlaygroundCliBlueprintV1Worker } from './worker-thread-v1';
|
|
4
3
|
import type { MessagePort as NodeMessagePort } from 'worker_threads';
|
|
5
4
|
import { type RunCLIArgs, type SpawnedWorker, type WorkerType } from '../run-cli';
|
|
5
|
+
import type { CLIOutput } from '../cli-output';
|
|
6
6
|
/**
|
|
7
7
|
* Boots Playground CLI workers using Blueprint version 1.
|
|
8
8
|
*
|
|
@@ -10,13 +10,14 @@ import { type RunCLIArgs, type SpawnedWorker, type WorkerType } from '../run-cli
|
|
|
10
10
|
* implemented in TypeScript and orchestrated by this class.
|
|
11
11
|
*/
|
|
12
12
|
export declare class BlueprintsV1Handler {
|
|
13
|
-
private lastProgressMessage;
|
|
14
13
|
private siteUrl;
|
|
15
14
|
private processIdSpaceLength;
|
|
16
15
|
private args;
|
|
16
|
+
private cliOutput;
|
|
17
17
|
constructor(args: RunCLIArgs, options: {
|
|
18
18
|
siteUrl: string;
|
|
19
19
|
processIdSpaceLength: number;
|
|
20
|
+
cliOutput: CLIOutput;
|
|
20
21
|
});
|
|
21
22
|
getWorkerType(): WorkerType;
|
|
22
23
|
bootAndSetUpInitialPlayground(phpPort: NodeMessagePort, fileLockManagerPort: NodeMessagePort, nativeInternalDirPath: string): Promise<import("@php-wasm/universal").RemoteAPI<PlaygroundCliBlueprintV1Worker>>;
|
|
@@ -28,5 +29,4 @@ export declare class BlueprintsV1Handler {
|
|
|
28
29
|
}): Promise<import("@php-wasm/universal").RemoteAPI<PlaygroundCliBlueprintV1Worker>>;
|
|
29
30
|
compileInputBlueprint(additionalBlueprintSteps: any[]): Promise<import("@wp-playground/blueprints").CompiledBlueprintV1>;
|
|
30
31
|
private getEffectiveBlueprint;
|
|
31
|
-
writeProgressUpdate(writeStream: NodeJS.WriteStream, message: string, finalUpdate: boolean): void;
|
|
32
32
|
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
|
-
/// <reference types="node" />
|
|
3
2
|
import type { RemoteAPI } from '@php-wasm/universal';
|
|
4
3
|
import type { PlaygroundCliBlueprintV2Worker } from './worker-thread-v2';
|
|
5
4
|
import type { MessagePort as NodeMessagePort } from 'worker_threads';
|
|
6
5
|
import type { RunCLIArgs, SpawnedWorker, WorkerType } from '../run-cli';
|
|
6
|
+
import type { CLIOutput } from '../cli-output';
|
|
7
7
|
/**
|
|
8
8
|
* Boots Playground CLI workers using Blueprint version 2.
|
|
9
9
|
*
|
|
@@ -12,13 +12,14 @@ import type { RunCLIArgs, SpawnedWorker, WorkerType } from '../run-cli';
|
|
|
12
12
|
*/
|
|
13
13
|
export declare class BlueprintsV2Handler {
|
|
14
14
|
private phpVersion;
|
|
15
|
-
private lastProgressMessage;
|
|
16
15
|
private siteUrl;
|
|
17
16
|
private processIdSpaceLength;
|
|
18
17
|
private args;
|
|
18
|
+
private cliOutput;
|
|
19
19
|
constructor(args: RunCLIArgs, options: {
|
|
20
20
|
siteUrl: string;
|
|
21
21
|
processIdSpaceLength: number;
|
|
22
|
+
cliOutput: CLIOutput;
|
|
22
23
|
});
|
|
23
24
|
getWorkerType(): WorkerType;
|
|
24
25
|
bootAndSetUpInitialPlayground(phpPort: NodeMessagePort, fileLockManagerPort: NodeMessagePort, nativeInternalDirPath: string): Promise<RemoteAPI<PlaygroundCliBlueprintV2Worker>>;
|
|
@@ -28,5 +29,4 @@ export declare class BlueprintsV2Handler {
|
|
|
28
29
|
firstProcessId: number;
|
|
29
30
|
nativeInternalDirPath: string;
|
|
30
31
|
}): Promise<RemoteAPI<PlaygroundCliBlueprintV2Worker>>;
|
|
31
|
-
writeProgressUpdate(writeStream: NodeJS.WriteStream, message: string, finalUpdate: boolean): void;
|
|
32
32
|
}
|
package/cli-output.d.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Manages formatted terminal output for the WordPress Playground CLI.
|
|
3
|
+
*
|
|
4
|
+
* This class handles two distinct output modes:
|
|
5
|
+
* - TTY (terminal): Uses ANSI escape codes for colors and in-place progress updates
|
|
6
|
+
* - Non-TTY (pipes/logs): Skips progress updates entirely, outputs plain text only
|
|
7
|
+
*
|
|
8
|
+
* Progress updates rewrite the same line in TTY mode to create smooth animations.
|
|
9
|
+
* When output is piped or redirected, progress is suppressed to avoid cluttering
|
|
10
|
+
* logs with intermediate states - only the final "Ready!" message appears.
|
|
11
|
+
*/
|
|
12
|
+
/// <reference types="node" />
|
|
13
|
+
import type { Mount } from '@php-wasm/cli-util';
|
|
14
|
+
export interface CLIOutputOptions {
|
|
15
|
+
/** Verbosity level: 'quiet', 'normal', or 'debug' */
|
|
16
|
+
verbosity: string;
|
|
17
|
+
/** Output stream to write to. Defaults to process.stdout */
|
|
18
|
+
writeStream?: NodeJS.WriteStream;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Configuration details displayed at CLI startup.
|
|
22
|
+
*/
|
|
23
|
+
export interface ConfigSummary {
|
|
24
|
+
phpVersion: string;
|
|
25
|
+
wpVersion: string;
|
|
26
|
+
port: number;
|
|
27
|
+
xdebug: boolean;
|
|
28
|
+
intl: boolean;
|
|
29
|
+
/** All mounts (both manual and auto-detected). Auto-mounts have autoMounted: true */
|
|
30
|
+
mounts: Mount[];
|
|
31
|
+
blueprint?: string;
|
|
32
|
+
}
|
|
33
|
+
export declare class CLIOutput {
|
|
34
|
+
private verbosity;
|
|
35
|
+
private writeStream;
|
|
36
|
+
private lastProgressLine;
|
|
37
|
+
private progressActive;
|
|
38
|
+
constructor(options: CLIOutputOptions);
|
|
39
|
+
get isTTY(): boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Determines if progress updates should be rendered.
|
|
42
|
+
*
|
|
43
|
+
* Returns false when output is piped, redirected, or in CI environments.
|
|
44
|
+
* This prevents progress spam in logs - users only see the final outcome.
|
|
45
|
+
*/
|
|
46
|
+
get shouldRender(): boolean;
|
|
47
|
+
get isQuiet(): boolean;
|
|
48
|
+
/**
|
|
49
|
+
* ANSI formatting helpers.
|
|
50
|
+
*
|
|
51
|
+
* These only apply color codes when outputting to a terminal (TTY).
|
|
52
|
+
* When piped to files or non-TTY streams, they return plain text to
|
|
53
|
+
* avoid polluting logs with escape sequences.
|
|
54
|
+
*/
|
|
55
|
+
private bold;
|
|
56
|
+
private dim;
|
|
57
|
+
private green;
|
|
58
|
+
private cyan;
|
|
59
|
+
private yellow;
|
|
60
|
+
private red;
|
|
61
|
+
printBanner(): void;
|
|
62
|
+
/**
|
|
63
|
+
* Prints the configuration summary before starting the server.
|
|
64
|
+
*
|
|
65
|
+
* Displays PHP/WordPress versions, enabled extensions, all mounts
|
|
66
|
+
* (with auto-mounts labeled), and any loaded blueprint. This gives
|
|
67
|
+
* users a clear view of what's configured before the server boots.
|
|
68
|
+
*/
|
|
69
|
+
printConfig(config: ConfigSummary): void;
|
|
70
|
+
/**
|
|
71
|
+
* Starts a progress indicator that updates in-place.
|
|
72
|
+
*
|
|
73
|
+
* Subsequent updateProgress() calls rewrite the same line in TTY mode.
|
|
74
|
+
* When output is piped or redirected, progress is completely skipped.
|
|
75
|
+
*/
|
|
76
|
+
startProgress(message: string): void;
|
|
77
|
+
/**
|
|
78
|
+
* Updates the current progress message and optional percentage.
|
|
79
|
+
*
|
|
80
|
+
* Rewrites the current line using ANSI cursor control in TTY mode.
|
|
81
|
+
* Identical messages are skipped to prevent flickering. When piped,
|
|
82
|
+
* this method does nothing (early return via shouldRender check).
|
|
83
|
+
*/
|
|
84
|
+
updateProgress(message: string, percent?: number): void;
|
|
85
|
+
/**
|
|
86
|
+
* Completes the progress indicator and moves to a new line.
|
|
87
|
+
*
|
|
88
|
+
* Optionally displays a final message before finishing. In TTY mode,
|
|
89
|
+
* this ensures the cursor moves to the next line after the progress.
|
|
90
|
+
*/
|
|
91
|
+
finishProgress(finalMessage?: string): void;
|
|
92
|
+
/**
|
|
93
|
+
* Prints a status message, interrupting any active progress.
|
|
94
|
+
*
|
|
95
|
+
* Unlike progress updates, status messages are always printed on their
|
|
96
|
+
* own line. Any active progress indicator is cleared before the message.
|
|
97
|
+
*/
|
|
98
|
+
printStatus(message: string): void;
|
|
99
|
+
/**
|
|
100
|
+
* Prints an error message.
|
|
101
|
+
*
|
|
102
|
+
* Errors are always shown, even in quiet mode, and interrupt any
|
|
103
|
+
* active progress display to ensure visibility.
|
|
104
|
+
*/
|
|
105
|
+
printError(message: string): void;
|
|
106
|
+
/**
|
|
107
|
+
* Prints the final "server ready" message with the URL.
|
|
108
|
+
*
|
|
109
|
+
* Note: The exact wording "WordPress is running on" is checked by
|
|
110
|
+
* CI tests, so changes to this string will break test assertions.
|
|
111
|
+
*/
|
|
112
|
+
printReady(url: string, workerCount: number): void;
|
|
113
|
+
printWarning(message: string): void;
|
|
114
|
+
}
|
package/cli.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";const s=require("./run-cli-
|
|
1
|
+
"use strict";const s=require("./run-cli-B8Dv6R-o.cjs"),r=process.argv.slice(2);s.parseOptionsAndRunCLI(r);
|
|
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-B8Dv6R-o.cjs");exports.LogVerbosity=e.LogVerbosity;exports.internalsKeyForTesting=e.internalsKeyForTesting;exports.parseOptionsAndRunCLI=e.parseOptionsAndRunCLI;exports.runCLI=e.runCLI;exports.spawnWorkerThread=e.spawnWorkerThread;
|
|
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.42",
|
|
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": "5f92a69369203e2926e08c3a690c7d3baafd2744",
|
|
38
38
|
"dependencies": {
|
|
39
39
|
"@zip.js/zip.js": "2.7.57",
|
|
40
40
|
"ajv": "8.12.0",
|
|
@@ -62,17 +62,17 @@
|
|
|
62
62
|
"ws": "8.18.3",
|
|
63
63
|
"xml2js": "0.6.2",
|
|
64
64
|
"yargs": "17.7.2",
|
|
65
|
-
"@php-wasm/logger": "3.0.
|
|
66
|
-
"@php-wasm/progress": "3.0.
|
|
67
|
-
"@php-wasm/universal": "3.0.
|
|
68
|
-
"@wp-playground/blueprints": "3.0.
|
|
69
|
-
"@wp-playground/common": "3.0.
|
|
70
|
-
"@wp-playground/wordpress": "3.0.
|
|
71
|
-
"@php-wasm/node": "3.0.
|
|
72
|
-
"@php-wasm/util": "3.0.
|
|
73
|
-
"@php-wasm/cli-util": "3.0.
|
|
74
|
-
"@wp-playground/storage": "3.0.
|
|
75
|
-
"@php-wasm/xdebug-bridge": "3.0.
|
|
65
|
+
"@php-wasm/logger": "3.0.42",
|
|
66
|
+
"@php-wasm/progress": "3.0.42",
|
|
67
|
+
"@php-wasm/universal": "3.0.42",
|
|
68
|
+
"@wp-playground/blueprints": "3.0.42",
|
|
69
|
+
"@wp-playground/common": "3.0.42",
|
|
70
|
+
"@wp-playground/wordpress": "3.0.42",
|
|
71
|
+
"@php-wasm/node": "3.0.42",
|
|
72
|
+
"@php-wasm/util": "3.0.42",
|
|
73
|
+
"@php-wasm/cli-util": "3.0.42",
|
|
74
|
+
"@wp-playground/storage": "3.0.42",
|
|
75
|
+
"@php-wasm/xdebug-bridge": "3.0.42"
|
|
76
76
|
},
|
|
77
77
|
"packageManager": "npm@10.9.2",
|
|
78
78
|
"overrides": {
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"use strict";var ve=Object.create;var te=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var xe=Object.getOwnPropertyNames;var ke=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var $e=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of xe(t))!Ie.call(e,o)&&o!==r&&te(e,o,{get:()=>t[o],enumerable:!(s=Se(t,o))||s.enumerable});return e};var Te=(e,t,r)=>(r=e!=null?ve(ke(e)):{},$e(t||!e||!e.__esModule?te(r,"default",{value:e,enumerable:!0}):r,e));const f=require("@php-wasm/logger"),y=require("@php-wasm/universal"),B=require("@wp-playground/blueprints"),M=require("@wp-playground/common"),u=require("fs"),Q=require("worker_threads"),ue=require("@php-wasm/node"),c=require("path"),Le=require("express"),D=require("os"),Re=require("wasm-feature-detect"),Be=require("yargs"),H=require("@wp-playground/storage"),re=require("@php-wasm/progress"),Ce=require("@wp-playground/wordpress"),C=require("fs-extra"),Ee=require("@php-wasm/xdebug-bridge"),We=require("child_process"),oe=require("tmp-promise"),Me=require("ps-man"),V=require("@php-wasm/cli-util"),De=require("crypto");var L=typeof document<"u"?document.currentScript:null;function Y(e){const t=[];for(const r of e){const s=r.split(":");if(s.length!==2)throw new Error(`Invalid mount format: ${r}.
|
|
2
|
+
Expected format: /host/path:/vfs/path.
|
|
3
|
+
If your path contains a colon, e.g. C:\\myplugin, use the --mount-dir option instead.
|
|
4
|
+
Example: --mount-dir C:\\my-plugin /wordpress/wp-content/plugins/my-plugin`);const[o,i]=s;if(!u.existsSync(o))throw new Error(`Host path does not exist: ${o}`);t.push({hostPath:o,vfsPath:i})}return t}function se(e){if(e.length%2!==0)throw new Error("Invalid mount format. Expected: /host/path /vfs/path");const t=[];for(let r=0;r<e.length;r+=2){const s=e[r],o=e[r+1];if(!u.existsSync(s))throw new Error(`Host path does not exist: ${s}`);t.push({hostPath:c.resolve(process.cwd(),s),vfsPath:o})}return t}async function Ae(e,t){for(const r of t)await e.mount(r.vfsPath,ue.createNodeFsMountHandler(r.hostPath))}const ie={step:"runPHP",code:{filename:"activate-theme.php",content:`<?php
|
|
5
|
+
$docroot = getenv('DOCROOT') ? getenv('DOCROOT') : '/wordpress';
|
|
6
|
+
require_once "$docroot/wp-load.php";
|
|
7
|
+
$theme = wp_get_theme();
|
|
8
|
+
if (!$theme->exists()) {
|
|
9
|
+
$themes = wp_get_themes();
|
|
10
|
+
if (count($themes) > 0) {
|
|
11
|
+
$themeName = array_keys($themes)[0];
|
|
12
|
+
switch_theme($themeName);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
`}};function de(e){const t=e.autoMount,r=[...e.mount||[]],s=[...e["mount-before-install"]||[]],o={...e,mount:r,"mount-before-install":s,"additional-blueprint-steps":[...e["additional-blueprint-steps"]||[]]};if(qe(t)){const n=`/wordpress/wp-content/plugins/${c.basename(t)}`;r.push({hostPath:t,vfsPath:n,autoMounted:!0}),o["additional-blueprint-steps"].push({step:"activatePlugin",pluginPath:`/wordpress/wp-content/plugins/${c.basename(t)}`})}else if(Oe(t)){const i=c.basename(t),n=`/wordpress/wp-content/themes/${i}`;r.push({hostPath:t,vfsPath:n,autoMounted:!0}),o["additional-blueprint-steps"].push(e["experimental-blueprints-v2-runner"]?{step:"activateTheme",themeDirectoryName:i}:{step:"activateTheme",themeFolderName:i})}else if(Fe(t)){const i=u.readdirSync(t);for(const n of i)n!=="index.php"&&r.push({hostPath:`${t}/${n}`,vfsPath:`/wordpress/wp-content/${n}`,autoMounted:!0});o["additional-blueprint-steps"].push(ie)}else Ue(t)&&(s.push({hostPath:t,vfsPath:"/wordpress",autoMounted:!0}),o.mode="apply-to-existing-site",o["additional-blueprint-steps"].push(ie),o.wordpressInstallMode||(o.wordpressInstallMode="install-from-existing-files-if-needed"));return o}function Ue(e){const t=u.readdirSync(e);return t.includes("wp-admin")&&t.includes("wp-includes")&&t.includes("wp-content")}function Fe(e){const t=u.readdirSync(e);return t.includes("themes")||t.includes("plugins")||t.includes("mu-plugins")||t.includes("uploads")}function Oe(e){if(!u.readdirSync(e).includes("style.css"))return!1;const r=u.readFileSync(c.join(e,"style.css"),"utf8");return!!/^(?:[ \t]*<\?php)?[ \t/*#@]*Theme Name:(.*)$/im.exec(r)}function qe(e){const t=u.readdirSync(e),r=/^(?:[ \t]*<\?php)?[ \t/*#@]*Plugin Name:(.*)$/im;return!!t.filter(o=>o.endsWith(".php")).find(o=>{const i=u.readFileSync(c.join(e,o),"utf8");return!!r.exec(i)})}async function He(e){const t=Le(),r=await new Promise((i,n)=>{const l=t.listen(e.port,()=>{const d=l.address();d===null||typeof d=="string"?n(new Error("Server address is not available")):i(l)})});t.use("/",async(i,n)=>{let l;try{l=await e.handleRequest({url:i.url,headers:_e(i),method:i.method,body:await Ve(i)})}catch(d){f.logger.error(d),l=y.PHPResponse.forHttpCode(500)}n.statusCode=l.httpStatusCode;for(const d in l.headers)n.setHeader(d,l.headers[d]);n.end(l.bytes)});const o=r.address().port;return await e.onBind(r,o)}const Ve=async e=>await new Promise(t=>{const r=[];e.on("data",s=>{r.push(s)}),e.on("end",()=>{t(new Uint8Array(Buffer.concat(r)))})}),_e=e=>{const t={};if(e.rawHeaders&&e.rawHeaders.length)for(let r=0;r<e.rawHeaders.length;r+=2)t[e.rawHeaders[r].toLowerCase()]=e.rawHeaders[r+1];return t};class Ne{constructor(t){this.workerLoads=[],this.addWorker(t)}addWorker(t){this.workerLoads.push({worker:t,activeRequests:new Set})}async removeWorker(t){const r=this.workerLoads.findIndex(o=>o.worker===t);if(r===-1)return;const[s]=this.workerLoads.splice(r,1);await Promise.allSettled(s.activeRequests)}async handleRequest(t){let r=this.workerLoads[0];for(let o=1;o<this.workerLoads.length;o++){const i=this.workerLoads[o];i.activeRequests.size<r.activeRequests.size&&(r=i)}const s=r.worker.request(t);return r.activeRequests.add(s),s.url=t.url,s.finally(()=>{r.activeRequests.delete(s)})}}function je(e){return/^latest$|^trunk$|^nightly$|^(?:(\d+)\.(\d+)(?:\.(\d+))?)((?:-beta(?:\d+)?)|(?:-RC(?:\d+)?))?$/.test(e)}async function Ye({sourceString:e,blueprintMayReadAdjacentFiles:t}){if(!e)return;if(e.startsWith("http://")||e.startsWith("https://"))return await B.resolveRemoteBlueprint(e);let r=c.resolve(process.cwd(),e);if(!u.existsSync(r))throw new Error(`Blueprint file does not exist: ${r}`);const s=u.statSync(r);if(s.isDirectory()&&(r=c.join(r,"blueprint.json")),!s.isFile()&&s.isSymbolicLink())throw new Error(`Blueprint path is neither a file nor a directory: ${r}`);const o=c.extname(r);switch(o){case".zip":return H.ZipFilesystem.fromArrayBuffer(u.readFileSync(r).buffer);case".json":{const i=u.readFileSync(r,"utf-8");try{JSON.parse(i)}catch{throw new Error(`Blueprint file at ${r} is not a valid JSON file`)}const n=c.dirname(r),l=new H.NodeJsFilesystem(n);return new H.OverlayFilesystem([new H.InMemoryFilesystem({"blueprint.json":i}),{read(d){if(!t)throw new Error(`Error: Blueprint contained tried to read a local file at path "${d}" (via a resource of type "bundled"). Playground restricts access to local resources by default as a security measure.
|
|
16
|
+
|
|
17
|
+
You can allow this Blueprint to read files from the same parent directory by explicitly adding the --blueprint-may-read-adjacent-files option to your command.`);return l.read(d)}}])}default:throw new Error(`Unsupported blueprint file extension: ${o}. Only .zip and .json files are supported.`)}}class ze{constructor(t,r){this.args=t,this.siteUrl=r.siteUrl,this.processIdSpaceLength=r.processIdSpaceLength,this.phpVersion=t.php,this.cliOutput=r.cliOutput}getWorkerType(){return"v2"}async bootAndSetUpInitialPlayground(t,r,s){const o=y.consumeAPI(t);await o.useFileLockManager(r);const i={...this.args,phpVersion:this.phpVersion,siteUrl:this.siteUrl,firstProcessId:1,processIdSpaceLength:this.processIdSpaceLength,trace:this.args.verbosity==="debug",blueprint:this.args.blueprint,withIntl:this.args.intl,withXdebug:!1,xdebug:void 0,nativeInternalDirPath:s,mountsBeforeWpInstall:this.args["mount-before-install"]||[],mountsAfterWpInstall:this.args.mount||[]};return await o.bootAndSetUpInitialWorker(i),o}async bootPlayground({worker:t,fileLockManagerPort:r,firstProcessId:s,nativeInternalDirPath:o}){const i=y.consumeAPI(t.phpPort);await i.useFileLockManager(r);const n={...this.args,phpVersion:this.phpVersion,siteUrl:this.siteUrl,firstProcessId:s,processIdSpaceLength:this.processIdSpaceLength,trace:this.args.verbosity==="debug",withIntl:this.args.intl,withXdebug:!!this.args.xdebug,nativeInternalDirPath:o,mountsBeforeWpInstall:this.args["mount-before-install"]||[],mountsAfterWpInstall:this.args.mount||[]};return await i.bootWorker(n),i}}const X=c.join(D.homedir(),".wordpress-playground");async function Qe(e){return await ce("https://github.com/WordPress/sqlite-database-integration/archive/refs/heads/develop.zip","sqlite.zip",e)}async function ce(e,t,r){const s=c.join(X,t);return C.existsSync(s)||(C.ensureDirSync(X),await Xe(e,s,r)),pe(s)}async function Xe(e,t,r){const o=(await r.monitorFetch(fetch(e))).body.getReader(),i=`${t}.partial`,n=C.createWriteStream(i);for(;;){const{done:l,value:d}=await o.read();if(d&&n.write(d),l)break}n.close(),n.closed||await new Promise((l,d)=>{n.on("finish",()=>{C.renameSync(i,t),l(null)}),n.on("error",P=>{C.removeSync(i),d(P)})})}function pe(e,t){return new File([C.readFileSync(e)],c.basename(e))}class Ze{constructor(t,r){this.args=t,this.siteUrl=r.siteUrl,this.processIdSpaceLength=r.processIdSpaceLength,this.cliOutput=r.cliOutput}getWorkerType(){return"v1"}async bootAndSetUpInitialPlayground(t,r,s){let o,i,n;const l=new re.EmscriptenDownloadMonitor;if(this.args.wordpressInstallMode==="download-and-install"){let E=!1;l.addEventListener("progress",I=>{if(E)return;const{loaded:A,total:G}=I.detail,U=Math.floor(Math.min(100,100*A/G));E=U===100,this.cliOutput.updateProgress("Downloading WordPress",U)}),o=await Ce.resolveWordPressRelease(this.args.wp),n=c.join(X,`prebuilt-wp-content-for-wp-${o.version}.zip`),i=u.existsSync(n)?pe(n):await ce(o.releaseUrl,`${o.version}.zip`,l),f.logger.debug(`Resolved WordPress release URL: ${o?.releaseUrl}`)}let d;this.args.skipSqliteSetup?(f.logger.debug("Skipping SQLite integration plugin setup..."),d=void 0):(this.cliOutput.updateProgress("Preparing SQLite database"),d=await Qe(l));const P=this.args.followSymlinks===!0,v=this.args.experimentalTrace===!0,a=this.args["mount-before-install"]||[],w=this.args.mount||[],h=y.consumeAPI(t);await h.isConnected(),this.cliOutput.updateProgress("Booting WordPress");const x=await B.resolveRuntimeConfiguration(this.getEffectiveBlueprint());return await h.useFileLockManager(r),await h.bootAndSetUpInitialWorker({phpVersion:x.phpVersion,wpVersion:x.wpVersion,siteUrl:this.siteUrl,mountsBeforeWpInstall:a,mountsAfterWpInstall:w,wordpressInstallMode:this.args.wordpressInstallMode||"download-and-install",wordPressZip:i&&await i.arrayBuffer(),sqliteIntegrationPluginZip:await d?.arrayBuffer(),firstProcessId:0,processIdSpaceLength:this.processIdSpaceLength,followSymlinks:P,trace:v,internalCookieStore:this.args.internalCookieStore,withIntl:this.args.intl,withXdebug:!1,nativeInternalDirPath:s}),n&&!this.args["mount-before-install"]&&!u.existsSync(n)&&(this.cliOutput.updateProgress("Caching WordPress for next boot"),u.writeFileSync(n,await M.zipDirectory(h,"/wordpress"))),h}async bootPlayground({worker:t,fileLockManagerPort:r,firstProcessId:s,nativeInternalDirPath:o}){const i=y.consumeAPI(t.phpPort);await i.isConnected();const n=await B.resolveRuntimeConfiguration(this.getEffectiveBlueprint());return await i.useFileLockManager(r),await i.bootWorker({phpVersion:n.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,withIntl:this.args.intl,withXdebug:!!this.args.xdebug,nativeInternalDirPath:o}),await i.isReady(),i}async compileInputBlueprint(t){const r=this.getEffectiveBlueprint(),s=new re.ProgressTracker;let o="",i=!1;return s.addEventListener("progress",n=>{if(i)return;i=n.detail.progress===100;const l=Math.floor(n.detail.progress);o=n.detail.caption||o||"Running Blueprint",this.cliOutput.updateProgress(o.trim(),l)}),await B.compileBlueprintV1(r,{progress:s,additionalSteps:t})}getEffectiveBlueprint(){const t=this.args.blueprint;return B.isBlueprintBundle(t)?t:{login:this.args.login,...t||{},preferredVersions:{php:this.args.php??t?.preferredVersions?.php??M.RecommendedPHPVersion,wp:this.args.wp??t?.preferredVersions?.wp??"latest",...t?.preferredVersions||{}}}}}async function Ge(e,t=!0){const s=`${c.basename(process.argv0)}${e}${process.pid}-`,o=await oe.dir({prefix:s,unsafeCleanup:!0});return t&&oe.setGracefulCleanup(),o}async function Je(e,t,r){const o=(await Ke(e,t,r)).map(i=>new Promise(n=>{u.rm(i,{recursive:!0},l=>{l?f.logger.warn(`Failed to delete stale Playground temp dir: ${i}`,l):f.logger.info(`Deleted stale Playground temp dir: ${i}`),n()})}));await Promise.all(o)}async function Ke(e,t,r){try{const s=u.readdirSync(r).map(i=>c.join(r,i)),o=[];for(const i of s)await et(e,t,i)&&o.push(i);return o}catch(s){return f.logger.warn(`Failed to find stale Playground temp dirs: ${s}`),[]}}async function et(e,t,r){if(!u.lstatSync(r).isDirectory())return!1;const o=c.basename(r);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 tt(n.pid,n.executableName))return!1;const l=Date.now()-t;return u.statSync(r).mtime.getTime()<l}async function tt(e,t){const[r]=await new Promise((s,o)=>{Me.list({pid:e,name:t,clean:!0},(i,n)=>{i?o(i):s(n)})});return!!r&&r.pid===e&&r.command===t}function he(e){return process.env.CI==="true"||process.env.CI==="1"||process.env.GITHUB_ACTIONS==="true"||process.env.GITHUB_ACTIONS==="1"||(process.env.TERM||"").toLowerCase()==="dumb"?!1:e?!!e.isTTY:process.stdout.isTTY}class rt{constructor(t){this.lastProgressLine="",this.progressActive=!1,this.verbosity=t.verbosity,this.writeStream=t.writeStream||process.stdout}get isTTY(){return!!this.writeStream.isTTY}get shouldRender(){return he(this.writeStream)}get isQuiet(){return this.verbosity==="quiet"}bold(t){return this.isTTY?`\x1B[1m${t}\x1B[0m`:t}dim(t){return this.isTTY?`\x1B[2m${t}\x1B[0m`:t}green(t){return this.isTTY?`\x1B[32m${t}\x1B[0m`:t}cyan(t){return this.isTTY?`\x1B[36m${t}\x1B[0m`:t}yellow(t){return this.isTTY?`\x1B[33m${t}\x1B[0m`:t}red(t){return this.isTTY?`\x1B[31m${t}\x1B[0m`:t}printBanner(){if(this.isQuiet)return;const t=this.bold("WordPress Playground CLI");this.writeStream.write(`
|
|
18
|
+
${t}
|
|
19
|
+
|
|
20
|
+
`)}printConfig(t){if(this.isQuiet)return;const r=[];r.push(`${this.dim("PHP")} ${this.cyan(t.phpVersion)} ${this.dim("WordPress")} ${this.cyan(t.wpVersion)}`);const s=[];if(t.intl&&s.push("intl"),t.xdebug&&s.push(this.yellow("xdebug")),s.length>0&&r.push(`${this.dim("Extensions")} ${s.join(", ")}`),t.mounts.length>0)for(const o of t.mounts){const i=o.autoMounted?` ${this.dim("(auto-mount)")}`:"";r.push(`${this.dim("Mount")} ${o.hostPath} ${this.dim("→")} ${o.vfsPath}${i}`)}t.blueprint&&r.push(`${this.dim("Blueprint")} ${t.blueprint}`),this.writeStream.write(r.join(`
|
|
21
|
+
`)+`
|
|
22
|
+
|
|
23
|
+
`)}startProgress(t){this.isQuiet||this.shouldRender&&(this.progressActive=!0,this.updateProgress(t))}updateProgress(t,r){if(this.isQuiet||!this.shouldRender)return;this.progressActive||(this.progressActive=!0);let s=`${t}`;r!==void 0&&(s=`${t} ${this.dim(`${r}%`)}`),s!==this.lastProgressLine&&(this.lastProgressLine=s,this.isTTY?(this.writeStream.cursorTo(0),this.writeStream.write(s),this.writeStream.clearLine(1)):this.writeStream.write(`${s}
|
|
24
|
+
`))}finishProgress(t){this.isQuiet||this.shouldRender&&(t&&(this.isTTY?(this.writeStream.cursorTo(0),this.writeStream.write(`${t}`),this.writeStream.clearLine(1)):this.writeStream.write(`${t}
|
|
25
|
+
`)),this.isTTY&&this.writeStream.write(`
|
|
26
|
+
`),this.progressActive=!1,this.lastProgressLine="")}printStatus(t){this.isQuiet||(this.progressActive&&this.isTTY&&(this.writeStream.cursorTo(0),this.writeStream.clearLine(0)),this.writeStream.write(`${t}
|
|
27
|
+
`),this.progressActive=!1,this.lastProgressLine="")}printError(t){this.progressActive&&this.isTTY&&(this.writeStream.cursorTo(0),this.writeStream.clearLine(0),this.progressActive=!1),this.writeStream.write(`${this.red("Error:")} ${t}
|
|
28
|
+
`)}printReady(t,r){if(this.isQuiet)return;const s=r===1?"worker":"workers";this.writeStream.write(`
|
|
29
|
+
${this.green("Ready!")} WordPress is running on ${this.bold(t)} ${this.dim(`(${r} ${s})`)}
|
|
30
|
+
|
|
31
|
+
`)}printWarning(t){this.isQuiet||this.writeStream.write(`${this.yellow("Warning:")} ${t}
|
|
32
|
+
`)}}const Z={Quiet:{name:"quiet",severity:f.LogSeverity.Fatal},Normal:{name:"normal",severity:f.LogSeverity.Info},Debug:{name:"debug",severity:f.LogSeverity.Debug}};async function ot(e){try{const t={"site-url":{describe:"Site URL to use for WordPress. Defaults to http://127.0.0.1:{port}",type:"string"},php:{describe:"PHP version to use.",type:"string",default:M.RecommendedPHPVersion,choices:y.SupportedPHPVersions},wp:{describe:"WordPress version to use.",type:"string",default:"latest"},mount:{describe:"Mount a directory to the PHP runtime (can be used multiple times). Format: /host/path:/vfs/path",type:"array",string:!0,coerce:Y},"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:Y},"mount-dir":{describe:'Mount a directory to the PHP runtime (can be used multiple times). Format: "/host/path" "/vfs/path"',type:"array",nargs:2,array:!0,coerce:se},"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:se},login:{describe:"Should log the user in",type:"boolean",default:!1},blueprint:{describe:"Blueprint to execute.",type:"string"},"blueprint-may-read-adjacent-files":{describe:'Consent flag: Allow "bundled" resources in a local blueprint to read files in the same directory as the blueprint file.',type:"boolean",default:!1},"wordpress-install-mode":{describe:"Control how Playground prepares WordPress before booting.",type:"string",default:"download-and-install",choices:["download-and-install","install-from-existing-files","install-from-existing-files-if-needed","do-not-attempt-installing"]},"skip-wordpress-install":{describe:"[Deprecated] Use --wordpress-install-mode instead.",type:"boolean",hidden:!0},"skip-sqlite-setup":{describe:"Skip the SQLite integration plugin setup to allow the WordPress site to use MySQL.",type:"boolean",default:!1},quiet:{describe:"Do not output logs and progress messages.",type:"boolean",default:!1,hidden:!0},verbosity:{describe:"Output logs and progress messages.",type:"string",choices:Object.values(Z).map(a=>a.name),default:"normal"},debug:{describe:"Print PHP error log content if an error occurs during Playground boot.",type:"boolean",default:!1,hidden:!0},"auto-mount":{describe:"Automatically mount the specified directory. If no path is provided, mount the current working directory. You can mount a WordPress directory, a plugin directory, a theme directory, a wp-content directory, or any directory containing PHP and HTML files.",type:"string"},"follow-symlinks":{describe:`Allow Playground to follow symlinks by automatically mounting symlinked directories and files encountered in mounted directories.
|
|
33
|
+
Warning: Following symlinks will expose files outside mounted directories to Playground and could be a security risk.`,type:"boolean",default:!1},"experimental-trace":{describe:"Print detailed messages about system behavior to the console. Useful for troubleshooting.",type:"boolean",default:!1,hidden:!0},"internal-cookie-store":{describe:"Enable internal cookie handling. When enabled, Playground will manage cookies internally using an HttpCookieStore that persists cookies across requests. When disabled, cookies are handled externally (e.g., by a browser in Node.js environments).",type:"boolean",default:!1},intl:{describe:"Enable Intl.",type:"boolean",default:!0},xdebug:{describe:"Enable Xdebug.",type:"boolean",default:!1},"experimental-unsafe-ide-integration":{describe:"Enable experimental IDE development tools. This option edits IDE config files to set Xdebug path mappings and web server details. CAUTION: If there are bugs, this feature may break your IDE config files. Please consider backing up your IDE configs before using this feature.",type:"string",choices:["","vscode","phpstorm"],coerce:a=>a===""?["vscode","phpstorm"]:[a]},"experimental-blueprints-v2-runner":{describe:"Use the experimental Blueprint V2 runner.",type:"boolean",default:!1,hidden:!0},mode:{describe:"Blueprints v2 runner mode to use. This option is required when using the --experimental-blueprints-v2-runner flag with a blueprint.",type:"string",choices:["create-new-site","apply-to-existing-site"],hidden:!0}},r={port:{describe:"Port to listen on when serving.",type:"number",default:9400},"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:a=>a??D.cpus().length-1},"experimental-devtools":{describe:"Enable experimental browser development tools.",type:"boolean"}},s={path:{describe:"Path to the project directory. Playground will auto-detect if this is a plugin, theme, wp-content, or WordPress directory.",type:"string",default:process.cwd()},php:{describe:"PHP version to use.",type:"string",default:M.RecommendedPHPVersion,choices:y.SupportedPHPVersions},wp:{describe:"WordPress version to use.",type:"string",default:"latest"},port:{describe:"Port to listen on.",type:"number",default:9400},blueprint:{describe:"Path to a Blueprint JSON file to execute on startup.",type:"string"},login:{describe:"Auto-login as the admin user.",type:"boolean",default:!0},xdebug:{describe:"Enable Xdebug for debugging.",type:"boolean",default:!1},"experimental-unsafe-ide-integration":t["experimental-unsafe-ide-integration"],"skip-browser":{describe:"Do not open the site in your default browser on startup.",type:"boolean",default:!1},quiet:{describe:"Suppress non-essential output.",type:"boolean",default:!1},"site-url":{describe:"Override the site URL. By default, derived from the port (http://127.0.0.1:<port>).",type:"string"},mount:{describe:"Mount a directory to the PHP runtime (can be used multiple times). Format: /host/path:/vfs/path. Use this for additional mounts beyond auto-detection.",type:"array",string:!0,coerce:Y},reset:{describe:"Deletes the stored site directory and starts a new site from scratch.",type:"boolean",default:!1},"no-auto-mount":{describe:"Disable automatic project type detection. Use --mount to manually specify mounts instead.",type:"boolean",default:!1}},o={outfile:{describe:"When building, write to this output file.",type:"string",default:"wordpress.zip"}},i=Be(e).usage("Usage: wp-playground <command> [options]").command("start","Start a local WordPress server with automatic project detection (recommended)",a=>a.usage(`Usage: wp-playground start [options]
|
|
34
|
+
|
|
35
|
+
The easiest way to run WordPress locally. Automatically detects
|
|
36
|
+
if your directory contains a plugin, theme, wp-content, or
|
|
37
|
+
WordPress installation and configures everything for you.
|
|
38
|
+
|
|
39
|
+
Examples:
|
|
40
|
+
wp-playground start # Start in current directory
|
|
41
|
+
wp-playground start --path=./my-plugin # Start with a specific path
|
|
42
|
+
wp-playground start --wp=6.7 --php=8.3 # Use specific versions
|
|
43
|
+
wp-playground start --skip-browser # Skip opening browser
|
|
44
|
+
wp-playground start --no-auto-mount # Disable auto-detection`).options(s)).command("server","Start a local WordPress server (advanced, low-level)",a=>a.options({...t,...r})).command("run-blueprint","Execute a Blueprint without starting a server",a=>a.options({...t})).command("build-snapshot","Build a ZIP snapshot of a WordPress site based on a Blueprint",a=>a.options({...t,...o})).demandCommand(1,"Please specify a command").strictCommands().conflicts("experimental-unsafe-ide-integration","experimental-devtools").showHelpOnFail(!1).fail((a,w,h)=>{if(w)throw w;a&&a.includes("Please specify a command")&&(h.showHelp(),console.error(`
|
|
45
|
+
`+a),process.exit(1)),console.error(a),process.exit(1)}).strictOptions().check(async a=>{if(a["skip-wordpress-install"]===!0&&(a["wordpress-install-mode"]="do-not-attempt-installing",a.wordpressInstallMode="do-not-attempt-installing"),a.wp!==void 0&&typeof a.wp=="string"&&!je(a.wp))try{new URL(a.wp)}catch{throw new Error('Unrecognized WordPress version. Please use "latest", a URL, or a numeric version such as "6.2", "6.0.1", "6.2-beta1", or "6.2-RC1"')}const w=a["site-url"];if(typeof w=="string"&&w.trim()!=="")try{new URL(w)}catch{throw new Error(`Invalid site-url "${w}". Please provide a valid URL (e.g., http://localhost:8080 or https://example.com)`)}if(a["auto-mount"]){let h=!1;try{h=u.statSync(a["auto-mount"]).isDirectory()}catch{h=!1}if(!h)throw new Error(`The specified --auto-mount path is not a directory: '${a["auto-mount"]}'.`)}if(a["experimental-multi-worker"]!==void 0){if(a._[0]!=="server")throw new Error("The --experimental-multi-worker flag is only supported when running the server command.");if(a["experimental-multi-worker"]!==void 0&&typeof a["experimental-multi-worker"]=="number"&&a["experimental-multi-worker"]<=1)throw new Error("The --experimental-multi-worker flag must be a positive integer greater than 1.")}if(a["experimental-blueprints-v2-runner"]===!0){if(a.mode!==void 0){if(a["wordpress-install-mode"]!==void 0)throw new Error("The --wordpress-install-mode option cannot be used with the --mode option. Use one or the other.");if("skip-sqlite-setup"in a)throw new Error("The --skipSqliteSetup option is not supported in Blueprint V2 mode.");if(a["auto-mount"]!==void 0)throw new Error("The --mode option cannot be used with --auto-mount because --auto-mount automatically sets the mode.")}else a["wordpress-install-mode"]==="do-not-attempt-installing"?a.mode="apply-to-existing-site":a.mode="create-new-site";const h=a.allow||[];a.followSymlinks===!0&&h.push("follow-symlinks"),a["blueprint-may-read-adjacent-files"]===!0&&h.push("read-local-fs"),a.allow=h}else if(a.mode!==void 0)throw new Error("The --mode option requires the --experimentalBlueprintsV2Runner flag.");return!0});i.wrap(i.terminalWidth());const n=await i.argv,l=n._[0];["start","run-blueprint","server","build-snapshot"].includes(l)||(i.showHelp(),process.exit(1));const d={...n,command:l,mount:[...n.mount||[],...n["mount-dir"]||[]],"mount-before-install":[...n["mount-before-install"]||[],...n["mount-dir-before-install"]||[]]},P=await fe(d);P===void 0&&process.exit(0);const v=(()=>{let a;return async()=>{a!==void 0&&(a=P[Symbol.asyncDispose]()),await a,process.exit(0)}})();process.on("SIGINT",v),process.on("SIGTERM",v)}catch(t){if(console.error(t),!(t instanceof Error))throw t;if(process.argv.includes("--debug"))y.printDebugDetails(t);else{const s=[];let o=t;do s.push(o.message),o=o.cause;while(o instanceof Error);console.error("\x1B[1m"+s.join(" caused by: ")+"\x1B[0m")}process.exit(1)}}function ne(e,t){return e.find(r=>r.vfsPath.replace(/\/$/,"")===t.replace(/\/$/,""))}const me=Symbol("playground-cli-testing"),R=e=>process.stdout.isTTY?"\x1B[1m"+e+"\x1B[0m":e,st=e=>process.stdout.isTTY?"\x1B[31m"+e+"\x1B[0m":e,it=e=>process.stdout.isTTY?`\x1B[2m${e}\x1B[0m`:e,z=e=>process.stdout.isTTY?`\x1B[3m${e}\x1B[0m`:e,ae=e=>process.stdout.isTTY?`\x1B[33m${e}\x1B[0m`:e;async function fe(e){let t,r;const s=new Map;if(e.command==="start"&&(e=nt(e)),e.autoMount!==void 0&&(e.autoMount===""&&(e={...e,autoMount:process.cwd()}),e=de(e)),e.wordpressInstallMode===void 0&&(e.wordpressInstallMode="download-and-install"),e.quiet&&(e.verbosity="quiet",delete e.quiet),e.debug&&(e.verbosity="debug",delete e.debug),e.verbosity){const a=Object.values(Z).find(w=>w.name===e.verbosity).severity;f.logger.setSeverityFilterLevel(a)}e.intl||(e.intl=!0);const o=new rt({verbosity:e.verbosity||"normal"});e.command==="server"&&(o.printBanner(),o.printConfig({phpVersion:e.php||M.RecommendedPHPVersion,wpVersion:e.wp||"latest",port:e.port||9400,xdebug:!!e.xdebug,intl:!!e.intl,mounts:[...e.mount||[],...e["mount-before-install"]||[]],blueprint:typeof e.blueprint=="string"?e.blueprint:void 0}));const i=e.command==="server"?e.port??9400:0,n=D.platform()==="win32"?void 0:await import("fs-ext").then(a=>a.flockSync).catch(()=>{f.logger.debug("The fs-ext package is not installed. Internal file locking will not be integrated with host OS file locking.")}),l=new ue.FileLockManagerForNode(n);let d=!1,P=!0;const v=await He({port:i,onBind:async(a,w)=>{const h="127.0.0.1",x=`http://${h}:${w}`,E=e["site-url"]||x,I=e.command==="server"?e.experimentalMultiWorker??1:1,A=e.command==="server"?I+1:I,U=2**31-1,W=Math.floor(U/A),J="-playground-cli-site-",$=await Ge(J);f.logger.debug(`Native temp dir for VFS root: ${$.path}`);const F="WP Playground CLI - Listen for Xdebug",K=".playground-xdebug-root",ee=c.join(process.cwd(),K);if(await V.removeTempDirSymlink(ee),e.xdebug&&e.experimentalUnsafeIdeIntegration){await V.createTempDirSymlink($.path,ee,process.platform);const p={hostPath:c.join(".",c.sep,K),vfsPath:"/"};try{await V.clearXdebugIDEConfig(F,process.cwd());const g=typeof e.xdebug=="object"?e.xdebug:void 0,S=await V.addXdebugIDEConfig({name:F,host:h,port:w,ides:e.experimentalUnsafeIdeIntegration,cwd:process.cwd(),mounts:[p,...e["mount-before-install"]||[],...e.mount||[]],ideKey:g?.ideKey}),m=e.experimentalUnsafeIdeIntegration,b=m.includes("vscode"),k=m.includes("phpstorm"),q=Object.values(S);console.log(""),q.length>0?(console.log(R("Xdebug configured successfully")),console.log(ae("Updated IDE config: ")+q.join(" ")),console.log(ae("Playground source root: ")+".playground-xdebug-root"+z(it(" – you can set breakpoints and preview Playground's VFS structure in there.")))):(console.log(R("Xdebug configuration failed.")),console.log("No IDE-specific project settings directory was found in the current working directory.")),console.log(""),b&&S.vscode&&(console.log(R("VS Code / Cursor instructions:")),console.log(" 1. Ensure you have installed an IDE extension for PHP Debugging"),console.log(` (The ${R("PHP Debug")} extension by ${R("Xdebug")} has been a solid option)`),console.log(" 2. Open the Run and Debug panel on the left sidebar"),console.log(` 3. Select "${z(F)}" from the dropdown`),console.log(' 3. Click "start debugging"'),console.log(" 5. Set a breakpoint. For example, in .playground-xdebug-root/wordpress/index.php"),console.log(" 6. Visit Playground in your browser to hit the breakpoint"),k&&console.log("")),k&&S.phpstorm&&(console.log(R("PhpStorm instructions:")),console.log(` 1. Choose "${z(F)}" debug configuration in the toolbar`),console.log(" 2. Click the debug button (bug icon)`"),console.log(" 3. Set a breakpoint. For example, in .playground-xdebug-root/wordpress/index.php"),console.log(" 4. Visit Playground in your browser to hit the breakpoint")),console.log("")}catch(g){throw new Error("Could not configure Xdebug",{cause:g})}}const ge=c.dirname($.path),ye=2*24*60*60*1e3;Je(J,ye,ge);const _=c.join($.path,"internal");u.mkdirSync(_);const be=["wordpress","tmp","home"];for(const p of be){const g=m=>m.vfsPath===`/${p}`;if(!(e["mount-before-install"]?.some(g)||e.mount?.some(g))){const m=c.join($.path,p);u.mkdirSync(m),e["mount-before-install"]===void 0&&(e["mount-before-install"]=[]),e["mount-before-install"].unshift({vfsPath:`/${p}`,hostPath:m})}}if(e["mount-before-install"])for(const p of e["mount-before-install"])f.logger.debug(`Mount before WP install: ${p.vfsPath} -> ${p.hostPath}`);if(e.mount)for(const p of e.mount)f.logger.debug(`Mount after WP install: ${p.vfsPath} -> ${p.hostPath}`);let T;e["experimental-blueprints-v2-runner"]?T=new ze(e,{siteUrl:E,processIdSpaceLength:W,cliOutput:o}):(T=new Ze(e,{siteUrl:E,processIdSpaceLength:W,cliOutput:o}),typeof e.blueprint=="string"&&(e.blueprint=await Ye({sourceString:e.blueprint,blueprintMayReadAdjacentFiles:e["blueprint-may-read-adjacent-files"]===!0})));let N=!1;const O=async function(){N||(N=!0,await Promise.all([...s].map(async([g,S])=>{await S.dispose(),await g.terminate()})),a&&await new Promise(g=>a.close(g)),await $.cleanup())},Pe=at(A,T.getWorkerType(),({exitCode:p,workerIndex:g})=>{N||p===0&&f.logger.error(`Worker ${g} exited with code ${p}
|
|
46
|
+
`)});o.startProgress("Starting...");try{const p=await Pe,g=await le(l);{const m=p.shift(),b=await T.bootAndSetUpInitialPlayground(m.phpPort,g,_);if(s.set(m.worker,b),await b.isReady(),d=!0,t=new Ne(b),!e["experimental-blueprints-v2-runner"]){const k=await T.compileInputBlueprint(e["additional-blueprint-steps"]||[]);k&&await B.runBlueprintV1Steps(k,b)}if(e.command==="build-snapshot"){await ut(r,e.outfile),o.printStatus(`Exported to ${e.outfile}`),await O();return}else if(e.command==="run-blueprint"){o.finishProgress("Done"),await O();return}await t.removeWorker(b),await b.dispose(),await m.worker.terminate(),s.delete(m.worker)}const S=W;return[r]=await Promise.all(p.map(async(m,b)=>{const k=S+b*W,q=await le(l),j=await T.bootPlayground({worker:m,fileLockManagerPort:q,firstProcessId:k,nativeInternalDirPath:_});return s.set(m.worker,j),t.addWorker(j),j})),o.finishProgress(),o.printReady(x,I),e.xdebug&&e.experimentalDevtools&&(await Ee.startBridge({phpInstance:r,phpRoot:"/wordpress"})).start(),{playground:r,server:a,serverUrl:x,[Symbol.asyncDispose]:O,[me]:{workerThreadCount:I,getWorkerNumberFromProcessId:m=>Math.floor(m/W)}}}catch(p){if(e.verbosity!=="debug")throw p;let g="";throw await r?.fileExists(f.errorLogPath)&&(g=await r.readFileAsText(f.errorLogPath)),await O(),new Error(g,{cause:p})}},async handleRequest(a){if(!d)return y.PHPResponse.forHttpCode(502,"WordPress is not ready yet");if(P){P=!1;const w={"Content-Type":["text/plain"],"Content-Length":["0"],Location:[a.url]};return a.headers?.cookie?.includes("playground_auto_login_already_happened")&&(w["Set-Cookie"]=["playground_auto_login_already_happened=1; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/"]),new y.PHPResponse(302,w,new Uint8Array)}return await t.handleRequest(a)}});return v&&e.command==="start"&&!e.skipBrowser&<(v.serverUrl),v}function nt(e){let t={...e,command:"server"};e.noAutoMount||(t.autoMount=c.resolve(process.cwd(),t.path??""),t=de(t),delete t.autoMount);const r=ne(t["mount-before-install"]||[],"/wordpress")||ne(t.mount||[],"/wordpress");if(r)console.log("Site files stored at:",r?.hostPath),e.reset&&(console.log(""),console.log(st("This site is not managed by Playground CLI and cannot be reset.")),console.log("(It's not stored in the ~/.wordpress-playground/sites/<site-id> directory.)"),console.log(""),console.log("You may still remove the site's directory manually if you wish."),process.exit(1));else{const s=t.autoMount||process.cwd(),o=De.createHash("sha256").update(s).digest("hex"),i=D.homedir(),n=c.join(i,".wordpress-playground/sites",o);console.log("Site files stored at:",n),u.existsSync(n)&&e.reset&&(console.log("Resetting site..."),u.rmdirSync(n,{recursive:!0})),u.mkdirSync(n,{recursive:!0}),t["mount-before-install"]=[...t["mount-before-install"]||[],{vfsPath:"/wordpress",hostPath:n}],t.wordpressInstallMode=u.readdirSync(n).length===0?"download-and-install":"install-from-existing-files-if-needed"}return t}async function at(e,t,r){const s=[];for(let o=0;o<e;o++){const n=we(t,{onExit:l=>{r({exitCode:l,workerIndex:o})}});s.push(n)}return Promise.all(s)}function we(e,{onExit:t}={}){let r;return e==="v1"?r=new Q.Worker(new URL("./worker-thread-v1.cjs",typeof document>"u"?require("url").pathToFileURL(__filename).href:L&&L.tagName.toUpperCase()==="SCRIPT"&&L.src||new URL("run-cli-B8Dv6R-o.cjs",document.baseURI).href)):r=new Q.Worker(new URL("./worker-thread-v2.cjs",typeof document>"u"?require("url").pathToFileURL(__filename).href:L&&L.tagName.toUpperCase()==="SCRIPT"&&L.src||new URL("run-cli-B8Dv6R-o.cjs",document.baseURI).href)),new Promise((s,o)=>{r.once("message",function(n){n.command==="worker-script-initialized"&&s({worker:r,phpPort:n.phpPort})}),r.once("error",function(n){console.error(n);const l=new Error(`Worker failed to load worker. ${n.message?`Original error: ${n.message}`:""}`);o(l)});let i=!1;r.once("spawn",()=>{i=!0}),r.once("exit",n=>{i||o(new Error(`Worker exited before spawning: ${n}`)),t?.(n)})})}async function le(e){const{port1:t,port2:r}=new Q.MessageChannel;return await Re.jspi()?y.exposeAPI(e,null,t):await y.exposeSyncAPI(e,t),r}function lt(e){const t=D.platform();let r;switch(t){case"darwin":r=`open "${e}"`;break;case"win32":r=`start "" "${e}"`;break;default:r=`xdg-open "${e}"`;break}We.exec(r,s=>{s&&f.logger.debug(`Could not open browser: ${s.message}`)})}async function ut(e,t){await e.run({code:`<?php
|
|
47
|
+
$zip = new ZipArchive();
|
|
48
|
+
if(false === $zip->open('/tmp/build.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
|
|
49
|
+
throw new Exception('Failed to create ZIP');
|
|
50
|
+
}
|
|
51
|
+
$files = new RecursiveIteratorIterator(
|
|
52
|
+
new RecursiveDirectoryIterator('/wordpress')
|
|
53
|
+
);
|
|
54
|
+
foreach ($files as $file) {
|
|
55
|
+
echo $file . PHP_EOL;
|
|
56
|
+
if (!$file->isFile()) {
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
$zip->addFile($file->getPathname(), $file->getPathname());
|
|
60
|
+
}
|
|
61
|
+
$zip->close();
|
|
62
|
+
|
|
63
|
+
`});const r=await e.readFileAsBuffer("/tmp/build.zip");u.writeFileSync(t,r)}exports.LogVerbosity=Z;exports.internalsKeyForTesting=me;exports.mountResources=Ae;exports.parseOptionsAndRunCLI=ot;exports.runCLI=fe;exports.shouldRenderProgress=he;exports.spawnWorkerThread=we;
|
|
64
|
+
//# sourceMappingURL=run-cli-B8Dv6R-o.cjs.map
|