@wp-playground/cli 1.1.2 → 1.1.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/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./run-cli-BSw9FKSW.cjs");exports.runCLI=e.runCLI;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./run-cli-s3Rtz7Gj.cjs");exports.runCLI=e.runCLI;
2
2
  //# sourceMappingURL=index.cjs.map
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { r as a } from "./run-cli-_8y4VW5F.js";
1
+ import { r as a } from "./run-cli-CznLz9jO.js";
2
2
  export {
3
3
  a as runCLI
4
4
  };
@@ -0,0 +1,13 @@
1
+ import type { PHPRequest, PHPResponse, RemoteAPI } from '@php-wasm/universal';
2
+ import type { PlaygroundCliWorker } from './worker-thread';
3
+ type WorkerLoad = {
4
+ worker: RemoteAPI<PlaygroundCliWorker>;
5
+ activeRequests: Set<Promise<PHPResponse>>;
6
+ };
7
+ export declare class LoadBalancer {
8
+ workerLoads: WorkerLoad[];
9
+ constructor(initialWorker: RemoteAPI<PlaygroundCliWorker>);
10
+ addWorker(worker: RemoteAPI<PlaygroundCliWorker>): void;
11
+ handleRequest(request: PHPRequest): Promise<PHPResponse>;
12
+ }
13
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wp-playground/cli",
3
- "version": "1.1.2",
3
+ "version": "1.1.4",
4
4
  "description": "WordPress Playground CLI",
5
5
  "repository": {
6
6
  "type": "git",
@@ -32,16 +32,17 @@
32
32
  "module": "./index.js",
33
33
  "types": "index.d.ts",
34
34
  "bin": "wp-playground.js",
35
- "gitHead": "59c2db1ec41efa10ffa01e6e1ea7ac6e78bc693e",
35
+ "gitHead": "ed646326d99ba84bad911d65b6634265f508f073",
36
36
  "dependencies": {
37
37
  "@zip.js/zip.js": "2.7.57",
38
38
  "ajv": "8.12.0",
39
39
  "async-lock": "1.4.1",
40
40
  "clean-git-ref": "2.0.1",
41
- "comlink": "^4.4.1",
41
+ "comlink": "^4.4.2",
42
42
  "crc-32": "1.2.2",
43
43
  "diff3": "0.0.4",
44
44
  "express": "4.21.2",
45
+ "fs-ext": "2.1.1",
45
46
  "fs-extra": "11.1.1",
46
47
  "ignore": "5.3.2",
47
48
  "ini": "4.1.2",
@@ -55,14 +56,15 @@
55
56
  "wasm-feature-detect": "1.8.0",
56
57
  "ws": "8.18.1",
57
58
  "yargs": "17.7.2",
58
- "@wp-playground/blueprints": "1.1.2",
59
- "@php-wasm/universal": "1.1.2",
60
- "@wp-playground/common": "1.1.2",
61
- "@php-wasm/progress": "1.1.2",
62
- "@php-wasm/node": "1.1.2",
63
- "@php-wasm/logger": "1.1.2",
64
- "@wp-playground/storage": "1.1.2",
65
- "@wp-playground/wordpress": "1.1.2"
59
+ "@wp-playground/blueprints": "1.1.4",
60
+ "@php-wasm/universal": "1.1.4",
61
+ "@wp-playground/common": "1.1.4",
62
+ "@php-wasm/progress": "1.1.4",
63
+ "@php-wasm/node": "1.1.4",
64
+ "@php-wasm/logger": "1.1.4",
65
+ "@wp-playground/storage": "1.1.4",
66
+ "@wp-playground/wordpress": "1.1.4",
67
+ "@php-wasm/util": "1.1.4"
66
68
  },
67
69
  "overrides": {
68
70
  "rollup": "^4.34.6",
@@ -0,0 +1,420 @@
1
+ import { logger as d, errorLogPath as K } from "@php-wasm/logger";
2
+ import { ProgressTracker as ee, EmscriptenDownloadMonitor as te } from "@php-wasm/progress";
3
+ import { PHPResponse as re, consumeAPI as Z, exposeAPI as D } from "@php-wasm/universal";
4
+ import { isBlueprintBundle as ne, compileBlueprint as oe, runBlueprintSteps as se } from "@wp-playground/blueprints";
5
+ import { RecommendedPHPVersion as ie, zipDirectory as _, unzipFile as ae } from "@wp-playground/common";
6
+ import w from "fs";
7
+ import C, { basename as I, join as q } from "path";
8
+ import { Worker as le } from "worker_threads";
9
+ import k from "fs-extra";
10
+ import pe from "os";
11
+ import ce from "express";
12
+ import { resolveWordPressRelease as de } from "@wp-playground/wordpress";
13
+ import { FileLockManagerForNode as ue } from "@php-wasm/node";
14
+ const fe = "" + new URL("worker-thread-BQ8BezvJ.js", import.meta.url).href;
15
+ function we(e) {
16
+ const t = process.cwd(), r = [...e.mount || []], n = [...e.mountBeforeInstall || []];
17
+ if (O(t)) {
18
+ const s = I(t);
19
+ r.push({
20
+ hostPath: t,
21
+ vfsPath: `/wordpress/wp-content/plugins/${s}`
22
+ });
23
+ } else if (j(t)) {
24
+ const s = I(t);
25
+ r.push({
26
+ hostPath: t,
27
+ vfsPath: `/wordpress/wp-content/themes/${s}`
28
+ });
29
+ } else if (V(t))
30
+ r.push(...U(t));
31
+ else if (F(t)) {
32
+ const s = w.readdirSync(t), p = [];
33
+ for (const c of s)
34
+ c.startsWith("wp-content") || p.push({
35
+ hostPath: `${t}/${c}`,
36
+ vfsPath: `/wordpress/${c}`
37
+ });
38
+ n.push(
39
+ ...p,
40
+ ...U(q(t, "wp-content"))
41
+ );
42
+ } else
43
+ r.push({ hostPath: t, vfsPath: "/wordpress" });
44
+ const l = e.blueprint || {};
45
+ l.steps = [...l.steps || [], ...me(t)];
46
+ const i = e.skipWordPressSetup || F(t);
47
+ return {
48
+ ...e,
49
+ blueprint: l,
50
+ mount: r,
51
+ mountBeforeInstall: n,
52
+ skipWordPressSetup: i
53
+ };
54
+ }
55
+ function F(e) {
56
+ const t = w.readdirSync(e);
57
+ return t.includes("wp-admin") && t.includes("wp-includes") && t.includes("wp-content");
58
+ }
59
+ function V(e) {
60
+ const t = w.readdirSync(e);
61
+ return t.includes("themes") || t.includes("plugins") || t.includes("mu-plugins") || t.includes("uploads");
62
+ }
63
+ function j(e) {
64
+ if (!w.readdirSync(e).includes("style.css"))
65
+ return !1;
66
+ const r = w.readFileSync(q(e, "style.css"), "utf8");
67
+ return !!/^(?:[ \t]*<\?php)?[ \t/*#@]*Theme Name:(.*)$/im.exec(r);
68
+ }
69
+ function O(e) {
70
+ const t = w.readdirSync(e), r = /^(?:[ \t]*<\?php)?[ \t/*#@]*Plugin Name:(.*)$/im;
71
+ return !!t.filter((l) => l.endsWith(".php")).find((l) => {
72
+ const i = w.readFileSync(q(e, l), "utf8");
73
+ return !!r.exec(i);
74
+ });
75
+ }
76
+ function U(e) {
77
+ return w.readdirSync(e).filter((r) => !r.startsWith("index.php")).map((r) => ({
78
+ hostPath: `${e}/${r}`,
79
+ vfsPath: `/wordpress/wp-content/${r}`
80
+ }));
81
+ }
82
+ function me(e) {
83
+ return O(e) ? [
84
+ {
85
+ step: "activatePlugin",
86
+ pluginPath: `/wordpress/wp-content/plugins/${I(e)}`
87
+ }
88
+ ] : j(e) ? [
89
+ {
90
+ step: "activateTheme",
91
+ themeFolderName: I(e)
92
+ }
93
+ ] : V(e) || F(e) ? [
94
+ {
95
+ step: "runPHP",
96
+ code: `<?php
97
+ require_once '/wordpress/wp-load.php';
98
+ $theme = wp_get_theme();
99
+ if (!$theme->exists()) {
100
+ $themes = wp_get_themes();
101
+ if (count($themes) > 0) {
102
+ $themeName = array_keys($themes)[0];
103
+ switch_theme($themeName);
104
+ }
105
+ }
106
+ `
107
+ }
108
+ ] : [];
109
+ }
110
+ const z = C.join(pe.homedir(), ".wordpress-playground");
111
+ async function he(e) {
112
+ return await Q(
113
+ "https://github.com/WordPress/sqlite-database-integration/archive/refs/heads/develop.zip",
114
+ "sqlite.zip",
115
+ e
116
+ );
117
+ }
118
+ async function Q(e, t, r) {
119
+ const n = C.join(z, t);
120
+ return k.existsSync(n) || (k.ensureDirSync(z), await Pe(e, n, r)), G(n);
121
+ }
122
+ async function Pe(e, t, r) {
123
+ const l = (await r.monitorFetch(fetch(e))).body.getReader(), i = `${t}.partial`, s = k.createWriteStream(i);
124
+ for (; ; ) {
125
+ const { done: p, value: c } = await l.read();
126
+ if (c && s.write(c), p)
127
+ break;
128
+ }
129
+ s.close(), s.closed || await new Promise((p, c) => {
130
+ s.on("finish", () => {
131
+ k.renameSync(i, t), p(null);
132
+ }), s.on("error", (x) => {
133
+ k.removeSync(i), c(x);
134
+ });
135
+ });
136
+ }
137
+ function G(e, t) {
138
+ return new File([k.readFileSync(e)], I(e));
139
+ }
140
+ async function ye(e) {
141
+ const t = ce(), r = await new Promise((i, s) => {
142
+ const p = t.listen(e.port, () => {
143
+ const c = p.address();
144
+ c === null || typeof c == "string" ? s(new Error("Server address is not available")) : i(p);
145
+ });
146
+ });
147
+ t.use("/", async (i, s) => {
148
+ const p = await e.handleRequest({
149
+ url: i.url,
150
+ headers: $e(i),
151
+ method: i.method,
152
+ body: await ge(i)
153
+ });
154
+ s.statusCode = p.httpStatusCode;
155
+ for (const c in p.headers)
156
+ s.setHeader(c, p.headers[c]);
157
+ s.end(p.bytes);
158
+ });
159
+ const l = r.address().port;
160
+ return await e.onBind(r, l);
161
+ }
162
+ const ge = async (e) => await new Promise((t) => {
163
+ const r = [];
164
+ e.on("data", (n) => {
165
+ r.push(n);
166
+ }), e.on("end", () => {
167
+ t(new Uint8Array(Buffer.concat(r)));
168
+ });
169
+ }), $e = (e) => {
170
+ const t = {};
171
+ if (e.rawHeaders && e.rawHeaders.length)
172
+ for (let r = 0; r < e.rawHeaders.length; r += 2)
173
+ t[e.rawHeaders[r].toLowerCase()] = e.rawHeaders[r + 1];
174
+ return t;
175
+ };
176
+ class ve {
177
+ constructor(t) {
178
+ this.workerLoads = [], this.addWorker(t);
179
+ }
180
+ addWorker(t) {
181
+ this.workerLoads.push({
182
+ worker: t,
183
+ activeRequests: /* @__PURE__ */ new Set()
184
+ });
185
+ }
186
+ async handleRequest(t) {
187
+ let r = this.workerLoads[0];
188
+ for (let l = 1; l < this.workerLoads.length; l++) {
189
+ const i = this.workerLoads[l];
190
+ i.activeRequests.size < r.activeRequests.size && (r = i);
191
+ }
192
+ const n = r.worker.request(t);
193
+ return r.activeRequests.add(n), n.url = t.url, n.finally(() => {
194
+ r.activeRequests.delete(n);
195
+ });
196
+ }
197
+ }
198
+ async function Ee(e) {
199
+ let t, r;
200
+ const n = [];
201
+ e.autoMount && (e = we(e));
202
+ async function l(o) {
203
+ await r.run({
204
+ code: `<?php
205
+ $zip = new ZipArchive();
206
+ if(false === $zip->open('/tmp/build.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
207
+ throw new Exception('Failed to create ZIP');
208
+ }
209
+ $files = new RecursiveIteratorIterator(
210
+ new RecursiveDirectoryIterator('/wordpress')
211
+ );
212
+ foreach ($files as $file) {
213
+ echo $file . PHP_EOL;
214
+ if (!$file->isFile()) {
215
+ continue;
216
+ }
217
+ $zip->addFile($file->getPathname(), $file->getPathname());
218
+ }
219
+ $zip->close();
220
+
221
+ `
222
+ });
223
+ const a = await r.readFileAsBuffer("/tmp/build.zip");
224
+ w.writeFileSync(o, a);
225
+ }
226
+ async function i() {
227
+ const o = ne(e.blueprint) ? e.blueprint : {
228
+ login: e.login,
229
+ ...e.blueprint,
230
+ preferredVersions: {
231
+ php: e.php ?? e?.blueprint?.preferredVersions?.php ?? ie,
232
+ wp: e.wp ?? e?.blueprint?.preferredVersions?.wp ?? "latest",
233
+ ...e.blueprint?.preferredVersions || {}
234
+ }
235
+ }, a = new ee();
236
+ let u = "", m = !1;
237
+ return a.addEventListener("progress", (y) => {
238
+ if (m)
239
+ return;
240
+ m = y.detail.progress === 100;
241
+ const f = Math.floor(y.detail.progress);
242
+ u = y.detail.caption || u || "Running the Blueprint";
243
+ const h = `${u.trim()} – ${f}%`;
244
+ e.quiet || p(
245
+ process.stdout,
246
+ h,
247
+ m
248
+ );
249
+ }), await oe(o, {
250
+ progress: a
251
+ });
252
+ }
253
+ let s = "";
254
+ function p(o, a, u) {
255
+ a !== s && (s = a, o.isTTY ? (o.cursorTo(0), o.write(a), o.clearLine(1), u && o.write(`
256
+ `)) : o.write(`${a}
257
+ `));
258
+ }
259
+ async function c(o) {
260
+ const a = new le(o);
261
+ return new Promise((u, m) => {
262
+ function y(h) {
263
+ h === "worker-script-initialized" && (u(a), a.off("message", y));
264
+ }
265
+ function f(h) {
266
+ const $ = new Error(
267
+ `Worker failed to load at ${o}. ${h.message ? `Original error: ${h.message}` : ""}`
268
+ );
269
+ $.filename = o, m($), a.off("error", f);
270
+ }
271
+ a.on("message", y), a.on("error", f);
272
+ });
273
+ }
274
+ function x(o) {
275
+ const a = new URL(
276
+ fe,
277
+ import.meta.url
278
+ ), u = [];
279
+ for (let m = 0; m < o; m++)
280
+ u.push(c(a));
281
+ return Promise.all(u);
282
+ }
283
+ e.quiet && (d.handlers = []);
284
+ const R = await i(), E = new ue();
285
+ let M = !1;
286
+ return d.log("Starting a PHP server..."), ye({
287
+ port: e.port,
288
+ onBind: async (o, a) => {
289
+ const u = `http://127.0.0.1:${a}`, m = e.experimentalMultiWorker ?? 1, y = x(m);
290
+ d.log(`Setting up WordPress ${e.wp}`);
291
+ let f;
292
+ const h = new te();
293
+ if (!e.skipWordPressSetup) {
294
+ let P = !1;
295
+ h.addEventListener("progress", (W) => {
296
+ if (P)
297
+ return;
298
+ const { loaded: S, total: L } = W.detail, v = Math.floor(
299
+ Math.min(100, 100 * S / L)
300
+ );
301
+ P = v === 100, e.quiet || p(
302
+ process.stdout,
303
+ `Downloading WordPress ${v}%...`,
304
+ P
305
+ );
306
+ }), f = await de(e.wp), d.log(
307
+ `Resolved WordPress release URL: ${f?.releaseUrl}`
308
+ );
309
+ }
310
+ const $ = f && C.join(
311
+ z,
312
+ `prebuilt-wp-content-for-wp-${f.version}.zip`
313
+ ), H = f ? w.existsSync($) ? G($) : await Q(
314
+ f.releaseUrl,
315
+ `${f.version}.zip`,
316
+ h
317
+ ) : void 0;
318
+ d.log("Fetching SQLite integration plugin...");
319
+ const J = e.skipSqliteSetup ? void 0 : await he(h), N = e.followSymlinks === !0, T = e.experimentalTrace === !0;
320
+ try {
321
+ const P = e.mountBeforeInstall || [], W = e.mount || [], [S, ...L] = await y;
322
+ r = Z(S), n.push({
323
+ playground: r,
324
+ worker: S
325
+ }), await r.isConnected(), D(E, void 0, S), d.log("Booting WordPress...");
326
+ const v = Math.floor(
327
+ Number.MAX_SAFE_INTEGER / m
328
+ );
329
+ if (await r.boot({
330
+ phpVersion: R.versions.php,
331
+ wpVersion: R.versions.wp,
332
+ absoluteUrl: u,
333
+ mountsBeforeWpInstall: P,
334
+ mountsAfterWpInstall: W,
335
+ wordPressZip: H && await H.arrayBuffer(),
336
+ sqliteIntegrationPluginZip: await J.arrayBuffer(),
337
+ firstProcessId: 0,
338
+ processIdSpaceLength: v,
339
+ followSymlinks: N,
340
+ trace: T
341
+ }), f && !e.mountBeforeInstall && !w.existsSync($) && (d.log(
342
+ "Caching preinstalled WordPress for the next boot..."
343
+ ), w.writeFileSync(
344
+ $,
345
+ await _(r, "/wordpress")
346
+ ), d.log("Cached!")), t = new ve(r), await r.isReady(), M = !0, d.log("Booted!"), R && (d.log("Running the Blueprint..."), await se(R, r), d.log("Finished running the blueprint")), e.command === "build-snapshot" ? (await l(e.outfile), d.log(`WordPress exported to ${e.outfile}`), process.exit(0)) : e.command === "run-blueprint" && (d.log("Blueprint executed"), process.exit(0)), e.experimentalMultiWorker && e.experimentalMultiWorker > 1) {
347
+ d.log("Preparing additional workers...");
348
+ const A = await _(
349
+ r,
350
+ "/internal"
351
+ ), b = v;
352
+ await Promise.all(
353
+ L.map(async (B, X) => {
354
+ const g = Z(B);
355
+ n.push({
356
+ playground: g,
357
+ worker: B
358
+ }), await g.isConnected(), D(E, void 0, B);
359
+ const Y = b + X * v;
360
+ await g.boot({
361
+ phpVersion: R.versions.php,
362
+ absoluteUrl: u,
363
+ mountsBeforeWpInstall: P,
364
+ mountsAfterWpInstall: W,
365
+ // Skip WordPress zip because we share the /wordpress directory
366
+ // populated by the initial worker.
367
+ wordPressZip: void 0,
368
+ // Skip SQLite integration plugin for now because we
369
+ // will copy it from primary's `/internal` directory.
370
+ sqliteIntegrationPluginZip: void 0,
371
+ dataSqlPath: "/wordpress/wp-content/database/.ht.sqlite",
372
+ firstProcessId: Y,
373
+ processIdSpaceLength: v,
374
+ followSymlinks: N,
375
+ trace: T
376
+ }), await g.isReady(), await g.writeFile(
377
+ "/tmp/internal.zip",
378
+ A
379
+ ), await ae(
380
+ g,
381
+ "/tmp/internal.zip",
382
+ "/internal"
383
+ ), await g.unlink(
384
+ "/tmp/internal.zip"
385
+ ), t.addWorker(g);
386
+ })
387
+ ), d.log("Ready!");
388
+ }
389
+ return d.log(`WordPress is running on ${u}`), {
390
+ playground: r,
391
+ server: o,
392
+ [Symbol.asyncDispose]: async function() {
393
+ await Promise.all(
394
+ n.map(
395
+ async ({ playground: b, worker: B }) => {
396
+ await b.dispose(), await B.terminate();
397
+ }
398
+ )
399
+ ), await new Promise((b) => o.close(b));
400
+ }
401
+ };
402
+ } catch (P) {
403
+ if (!e.debug)
404
+ throw P;
405
+ const W = await r.readFileAsText(K);
406
+ throw new Error(W, { cause: P });
407
+ }
408
+ },
409
+ async handleRequest(o) {
410
+ return M ? await t.handleRequest(o) : re.forHttpCode(
411
+ 502,
412
+ "WordPress is not ready yet"
413
+ );
414
+ }
415
+ });
416
+ }
417
+ export {
418
+ Ee as r
419
+ };
420
+ //# sourceMappingURL=run-cli-CznLz9jO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-cli-CznLz9jO.js","sources":["../../../../packages/playground/cli/src/cli-auto-mount.ts","../../../../packages/playground/cli/src/download.ts","../../../../packages/playground/cli/src/server.ts","../../../../packages/playground/cli/src/load-balancer.ts","../../../../packages/playground/cli/src/run-cli.ts"],"sourcesContent":["import { basename, join } from 'path';\nimport type {\n\tBlueprintDeclaration,\n\tStepDefinition,\n} from '@wp-playground/blueprints';\nimport fs from 'fs';\nimport type { RunCLIArgs } from './run-cli';\nimport type { Mount } from './mount';\n\nexport function expandAutoMounts(args: RunCLIArgs): RunCLIArgs {\n\tconst path = process.cwd();\n\n\tconst mount = [...(args.mount || [])];\n\tconst mountBeforeInstall = [...(args.mountBeforeInstall || [])];\n\n\tif (isPluginDirectory(path)) {\n\t\tconst pluginName = basename(path);\n\t\tmount.push({\n\t\t\thostPath: path,\n\t\t\tvfsPath: `/wordpress/wp-content/plugins/${pluginName}`,\n\t\t});\n\t} else if (isThemeDirectory(path)) {\n\t\tconst themeName = basename(path);\n\t\tmount.push({\n\t\t\thostPath: path,\n\t\t\tvfsPath: `/wordpress/wp-content/themes/${themeName}`,\n\t\t});\n\t} else if (containsWpContentDirectories(path)) {\n\t\tmount.push(...wpContentMounts(path));\n\t} else if (containsFullWordPressInstallation(path)) {\n\t\t/**\n\t\t * We don't want Playground and WordPress to modify the OS filesystem on their own\n\t\t * by creating files like wp-config.php or wp-content/db.php.\n\t\t * To ensure WordPress can write to the /wordpress/ and /wordpress/wp-content/ directories,\n\t\t * we leave these directories as MEMFS nodes and mount individual files\n\t\t * and directories into them instead of mounting the entire directory as a NODEFS node.\n\t\t */\n\t\tconst files = fs.readdirSync(path);\n\t\tconst mounts: Mount[] = [];\n\t\tfor (const file of files) {\n\t\t\tif (file.startsWith('wp-content')) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmounts.push({\n\t\t\t\thostPath: `${path}/${file}`,\n\t\t\t\tvfsPath: `/wordpress/${file}`,\n\t\t\t});\n\t\t}\n\t\tmountBeforeInstall.push(\n\t\t\t...mounts,\n\t\t\t...wpContentMounts(join(path, 'wp-content'))\n\t\t);\n\t} else {\n\t\t/**\n\t\t * By default, mount the current working directory as the Playground root.\n\t\t * This allows users to run and PHP or HTML files using the Playground CLI.\n\t\t */\n\t\tmount.push({ hostPath: path, vfsPath: '/wordpress' });\n\t}\n\n\tconst blueprint = (args.blueprint as BlueprintDeclaration) || {};\n\tblueprint.steps = [...(blueprint.steps || []), ...getSteps(path)];\n\n\t/**\n\t * If Playground is mounting a full WordPress directory,\n\t * it doesn't need to setup WordPress.\n\t */\n\tconst skipWordPressSetup =\n\t\targs.skipWordPressSetup || containsFullWordPressInstallation(path);\n\n\treturn {\n\t\t...args,\n\t\tblueprint,\n\t\tmount,\n\t\tmountBeforeInstall,\n\t\tskipWordPressSetup,\n\t} as RunCLIArgs;\n}\n\nexport function containsFullWordPressInstallation(path: string): boolean {\n\tconst files = fs.readdirSync(path);\n\treturn (\n\t\tfiles.includes('wp-admin') &&\n\t\tfiles.includes('wp-includes') &&\n\t\tfiles.includes('wp-content')\n\t);\n}\n\nexport function containsWpContentDirectories(path: string): boolean {\n\tconst files = fs.readdirSync(path);\n\treturn (\n\t\tfiles.includes('themes') ||\n\t\tfiles.includes('plugins') ||\n\t\tfiles.includes('mu-plugins') ||\n\t\tfiles.includes('uploads')\n\t);\n}\n\nexport function isThemeDirectory(path: string): boolean {\n\tconst files = fs.readdirSync(path);\n\tif (!files.includes('style.css')) {\n\t\treturn false;\n\t}\n\tconst styleCssContent = fs.readFileSync(join(path, 'style.css'), 'utf8');\n\tconst themeNameRegex = /^(?:[ \\t]*<\\?php)?[ \\t/*#@]*Theme Name:(.*)$/im;\n\treturn !!themeNameRegex.exec(styleCssContent);\n}\n\nexport function isPluginDirectory(path: string): boolean {\n\tconst files = fs.readdirSync(path);\n\tconst pluginNameRegex = /^(?:[ \\t]*<\\?php)?[ \\t/*#@]*Plugin Name:(.*)$/im;\n\tconst pluginNameMatch = files\n\t\t.filter((file) => file.endsWith('.php'))\n\t\t.find((file) => {\n\t\t\tconst fileContent = fs.readFileSync(join(path, file), 'utf8');\n\t\t\treturn !!pluginNameRegex.exec(fileContent);\n\t\t});\n\treturn !!pluginNameMatch;\n}\n\n/**\n * Returns a list of files and directories in the wp-content directory\n * to be mounted individually.\n *\n * This is needed because WordPress needs to be able to write to the\n * wp-content directory without Playground modifying the OS filesystem.\n *\n * See expandAutoMounts for more details.\n */\nexport function wpContentMounts(wpContentDir: string): Mount[] {\n\tconst files = fs.readdirSync(wpContentDir);\n\treturn (\n\t\tfiles\n\t\t\t/**\n\t\t\t * index.php is added by WordPress automatically and\n\t\t\t * can't be mounted from the current working directory\n\t\t\t * because it already exists.\n\t\t\t *\n\t\t\t * Because index.php should be empty, it's safe to not include it.\n\t\t\t */\n\t\t\t.filter((file) => !file.startsWith('index.php'))\n\t\t\t.map((file) => ({\n\t\t\t\thostPath: `${wpContentDir}/${file}`,\n\t\t\t\tvfsPath: `/wordpress/wp-content/${file}`,\n\t\t\t}))\n\t);\n}\n\nexport function getSteps(path: string): StepDefinition[] {\n\tif (isPluginDirectory(path)) {\n\t\treturn [\n\t\t\t{\n\t\t\t\tstep: 'activatePlugin',\n\t\t\t\tpluginPath: `/wordpress/wp-content/plugins/${basename(path)}`,\n\t\t\t},\n\t\t];\n\t} else if (isThemeDirectory(path)) {\n\t\treturn [\n\t\t\t{\n\t\t\t\tstep: 'activateTheme',\n\t\t\t\tthemeFolderName: basename(path),\n\t\t\t},\n\t\t];\n\t} else if (\n\t\tcontainsWpContentDirectories(path) ||\n\t\tcontainsFullWordPressInstallation(path)\n\t) {\n\t\t/**\n\t\t * Playground needs to ensure there is an active theme.\n\t\t * Otherwise when WordPress loads it will show a white screen.\n\t\t */\n\t\treturn [\n\t\t\t{\n\t\t\t\tstep: 'runPHP',\n\t\t\t\tcode: `<?php\n\t\t\t\t\trequire_once '/wordpress/wp-load.php';\n\t\t\t\t\t$theme = wp_get_theme();\n\t\t\t\t\tif (!$theme->exists()) {\n\t\t\t\t\t\t$themes = wp_get_themes();\n\t\t\t\t\t\tif (count($themes) > 0) {\n\t\t\t\t\t\t\t$themeName = array_keys($themes)[0];\n\t\t\t\t\t\t\tswitch_theme($themeName);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t`,\n\t\t\t},\n\t\t];\n\t}\n\treturn [];\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 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 { PlaygroundCliWorker } from './worker-thread';\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","import { errorLogPath, logger } from '@php-wasm/logger';\nimport { EmscriptenDownloadMonitor, ProgressTracker } from '@php-wasm/progress';\nimport type {\n\tPHPRequest,\n\tRemoteAPI,\n\tSupportedPHPVersion,\n} from '@php-wasm/universal';\nimport { consumeAPI, exposeAPI, PHPResponse } from '@php-wasm/universal';\nimport type {\n\tBlueprintDeclaration,\n\tBlueprintBundle,\n} from '@wp-playground/blueprints';\nimport {\n\tcompileBlueprint,\n\trunBlueprintSteps,\n\tisBlueprintBundle,\n} from '@wp-playground/blueprints';\nimport {\n\tRecommendedPHPVersion,\n\tunzipFile,\n\tzipDirectory,\n} from '@wp-playground/common';\nimport fs from 'fs';\nimport type { Server } from 'http';\nimport path from 'path';\nimport { Worker } from 'worker_threads';\n// @ts-ignore\nimport importedWorkerUrlString from './worker-thread?worker&url';\nimport { expandAutoMounts } from './cli-auto-mount';\nimport {\n\tCACHE_FOLDER,\n\tcachedDownload,\n\tfetchSqliteIntegration,\n\treadAsFile,\n} from './download';\nimport { startServer } from './server';\nimport { resolveWordPressRelease } from '@wp-playground/wordpress';\nimport type { PlaygroundCliWorker, Mount } from './worker-thread';\n// @ts-ignore\nimport { FileLockManagerForNode } from '@php-wasm/node';\nimport { LoadBalancer } from './load-balancer';\n\nexport interface RunCLIArgs {\n\tblueprint?: BlueprintDeclaration | BlueprintBundle;\n\tcommand: 'server' | 'run-blueprint' | 'build-snapshot';\n\tdebug?: boolean;\n\tlogin?: boolean;\n\tmount?: Mount[];\n\tmountBeforeInstall?: Mount[];\n\toutfile?: string;\n\tphp?: SupportedPHPVersion;\n\tport?: number;\n\tquiet?: boolean;\n\tskipWordPressSetup?: boolean;\n\tskipSqliteSetup?: boolean;\n\twp?: string;\n\tautoMount?: boolean;\n\tfollowSymlinks?: boolean;\n\texperimentalMultiWorker?: number;\n\texperimentalTrace?: boolean;\n}\n\nexport interface RunCLIServer extends AsyncDisposable {\n\tplayground: RemoteAPI<PlaygroundCliWorker>;\n\tserver: Server;\n\t[Symbol.asyncDispose](): Promise<void>;\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) {\n\t\targs = expandAutoMounts(args);\n\t}\n\n\t/**\n\t * TODO: This exact feature will be provided in the PHP Blueprints library.\n\t * Let's use it when it ships. Let's also use it in the web Playground\n\t * app.\n\t */\n\tasync function zipSite(outfile: string) {\n\t\tawait playground.run({\n\t\t\tcode: `<?php\n\t\t\t$zip = new ZipArchive();\n\t\t\tif(false === $zip->open('/tmp/build.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {\n\t\t\t\tthrow new Exception('Failed to create ZIP');\n\t\t\t}\n\t\t\t$files = new RecursiveIteratorIterator(\n\t\t\t\tnew RecursiveDirectoryIterator('/wordpress')\n\t\t\t);\n\t\t\tforeach ($files as $file) {\n\t\t\t\techo $file . PHP_EOL;\n\t\t\t\tif (!$file->isFile()) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t$zip->addFile($file->getPathname(), $file->getPathname());\n\t\t\t}\n\t\t\t$zip->close();\n\n\t\t`,\n\t\t});\n\t\tconst zip = await playground.readFileAsBuffer('/tmp/build.zip');\n\t\tfs.writeFileSync(outfile, zip);\n\t}\n\n\tasync function compileInputBlueprint() {\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\tconst blueprint: BlueprintDeclaration | BlueprintBundle =\n\t\t\tisBlueprintBundle(args.blueprint)\n\t\t\t\t? args.blueprint\n\t\t\t\t: {\n\t\t\t\t\t\tlogin: args.login,\n\t\t\t\t\t\t...args.blueprint,\n\t\t\t\t\t\tpreferredVersions: {\n\t\t\t\t\t\t\tphp:\n\t\t\t\t\t\t\t\targs.php ??\n\t\t\t\t\t\t\t\targs?.blueprint?.preferredVersions?.php ??\n\t\t\t\t\t\t\t\tRecommendedPHPVersion,\n\t\t\t\t\t\t\twp:\n\t\t\t\t\t\t\t\targs.wp ??\n\t\t\t\t\t\t\t\targs?.blueprint?.preferredVersions?.wp ??\n\t\t\t\t\t\t\t\t'latest',\n\t\t\t\t\t\t\t...(args.blueprint?.preferredVersions || {}),\n\t\t\t\t\t\t},\n\t\t\t\t };\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\tif (!args.quiet) {\n\t\t\t\twriteProgressUpdate(\n\t\t\t\t\tprocess.stdout,\n\t\t\t\t\tmessage,\n\t\t\t\t\tprogressReached100\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t\treturn await compileBlueprint(blueprint as BlueprintDeclaration, {\n\t\t\tprogress: tracker,\n\t\t});\n\t}\n\n\tlet lastProgressMessage = '';\n\tfunction writeProgressUpdate(\n\t\twriteStream: NodeJS.WriteStream,\n\t\tmessage: string,\n\t\tfinalUpdate: boolean\n\t) {\n\t\tif (message === lastProgressMessage) {\n\t\t\t// Avoid repeating the same message\n\t\t\treturn;\n\t\t}\n\t\tlastProgressMessage = 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\t/**\n\t * Spawns a new Worker Thread.\n\t *\n\t * @param workerUrl The absolute URL of the worker script.\n\t * @returns The spawned Worker Thread.\n\t */\n\tasync function spawnPHPWorkerThread(workerUrl: URL) {\n\t\tconst worker = new Worker(workerUrl);\n\n\t\treturn new Promise<Worker>((resolve, reject) => {\n\t\t\tfunction onMessage(event: string) {\n\t\t\t\t// Let the worker confirm it has initialized.\n\t\t\t\t// We could use the 'online' event to detect start of JS execution,\n\t\t\t\t// but that would miss initialization errors.\n\t\t\t\tif (event === 'worker-script-initialized') {\n\t\t\t\t\tresolve(worker);\n\t\t\t\t\tworker.off('message', onMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfunction onError(e: Error) {\n\t\t\t\tconst error = new Error(\n\t\t\t\t\t`Worker failed to load at ${workerUrl}. ${\n\t\t\t\t\t\te.message ? `Original error: ${e.message}` : ''\n\t\t\t\t\t}`\n\t\t\t\t);\n\t\t\t\t(error as any).filename = workerUrl;\n\t\t\t\treject(error);\n\t\t\t\tworker.off('error', onError);\n\t\t\t}\n\t\t\tworker.on('message', onMessage);\n\t\t\tworker.on('error', onError);\n\t\t});\n\t}\n\n\tfunction spawnWorkerThreads(count: number): Promise<Worker[]> {\n\t\tconst moduleWorkerUrl = new URL(\n\t\t\timportedWorkerUrlString,\n\t\t\timport.meta.url\n\t\t);\n\n\t\tconst promises = [];\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tpromises.push(spawnPHPWorkerThread(moduleWorkerUrl));\n\t\t}\n\t\treturn Promise.all(promises);\n\t}\n\n\tif (args.quiet) {\n\t\t// @ts-ignore\n\t\tlogger.handlers = [];\n\t}\n\n\tconst compiledBlueprint = await compileInputBlueprint();\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 fileLockManager = new FileLockManagerForNode();\n\n\tlet wordPressReady = false;\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 absoluteUrl = `http://127.0.0.1:${port}`;\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 totalWorkerCount = args.experimentalMultiWorker ?? 1;\n\t\t\tconst promisedWorkers = spawnWorkerThreads(totalWorkerCount);\n\n\t\t\tlogger.log(`Setting up WordPress ${args.wp}`);\n\t\t\tlet wpDetails: any = undefined;\n\t\t\t// @TODO: Rename to FetchProgressMonitor. There's nothing Emscripten\n\t\t\t// about that class anymore.\n\t\t\tconst monitor = new EmscriptenDownloadMonitor();\n\t\t\tif (!args.skipWordPressSetup) {\n\t\t\t\tlet progressReached100 = false;\n\t\t\t\tmonitor.addEventListener('progress', ((\n\t\t\t\t\te: CustomEvent<ProgressEvent & { finished: boolean }>\n\t\t\t\t) => {\n\t\t\t\t\tif (progressReached100) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// @TODO Every progress bar will want percentages. The\n\t\t\t\t\t// download monitor should just provide that.\n\t\t\t\t\tconst { loaded, total } = e.detail;\n\t\t\t\t\t// Use floor() so we don't report 100% until truly there.\n\t\t\t\t\tconst percentProgress = Math.floor(\n\t\t\t\t\t\tMath.min(100, (100 * loaded) / total)\n\t\t\t\t\t);\n\t\t\t\t\tprogressReached100 = percentProgress === 100;\n\n\t\t\t\t\tif (!args.quiet) {\n\t\t\t\t\t\twriteProgressUpdate(\n\t\t\t\t\t\t\tprocess.stdout,\n\t\t\t\t\t\t\t`Downloading WordPress ${percentProgress}%...`,\n\t\t\t\t\t\t\tprogressReached100\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}) as any);\n\n\t\t\t\twpDetails = await resolveWordPressRelease(args.wp);\n\t\t\t\tlogger.log(\n\t\t\t\t\t`Resolved WordPress release URL: ${wpDetails?.releaseUrl}`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst preinstalledWpContentPath =\n\t\t\t\twpDetails &&\n\t\t\t\tpath.join(\n\t\t\t\t\tCACHE_FOLDER,\n\t\t\t\t\t`prebuilt-wp-content-for-wp-${wpDetails.version}.zip`\n\t\t\t\t);\n\t\t\tconst wordPressZip = !wpDetails\n\t\t\t\t? undefined\n\t\t\t\t: fs.existsSync(preinstalledWpContentPath)\n\t\t\t\t? readAsFile(preinstalledWpContentPath)\n\t\t\t\t: await cachedDownload(\n\t\t\t\t\t\twpDetails.releaseUrl,\n\t\t\t\t\t\t`${wpDetails.version}.zip`,\n\t\t\t\t\t\tmonitor\n\t\t\t\t );\n\n\t\t\tlogger.log(`Fetching SQLite integration plugin...`);\n\t\t\tconst sqliteIntegrationPluginZip = args.skipSqliteSetup\n\t\t\t\t? undefined\n\t\t\t\t: await fetchSqliteIntegration(monitor);\n\n\t\t\tconst followSymlinks = args.followSymlinks === true;\n\t\t\tconst trace = args.experimentalTrace === true;\n\t\t\ttry {\n\t\t\t\tconst mountsBeforeWpInstall = args.mountBeforeInstall || [];\n\t\t\t\tconst mountsAfterWpInstall = args.mount || [];\n\n\t\t\t\tconst [initialWorker, ...additionalWorkers] =\n\t\t\t\t\tawait promisedWorkers;\n\n\t\t\t\tplayground = consumeAPI<PlaygroundCliWorker>(initialWorker);\n\t\t\t\tplaygroundsToCleanUp.push({\n\t\t\t\t\tplayground,\n\t\t\t\t\tworker: initialWorker,\n\t\t\t\t});\n\n\t\t\t\tawait playground.isConnected();\n\n\t\t\t\texposeAPI(fileLockManager, undefined, initialWorker);\n\n\t\t\t\tlogger.log(`Booting WordPress...`);\n\n\t\t\t\t// Each additional worker needs a separate process ID space\n\t\t\t\t// for file locking to work properly because locks are associated\n\t\t\t\t// with individual processes. To accommodate this, we split the safe\n\t\t\t\t// integers into a range for each worker.\n\t\t\t\tconst processIdSpaceLength = Math.floor(\n\t\t\t\t\tNumber.MAX_SAFE_INTEGER / totalWorkerCount\n\t\t\t\t);\n\n\t\t\t\tawait playground.boot({\n\t\t\t\t\tphpVersion: compiledBlueprint.versions.php,\n\t\t\t\t\twpVersion: compiledBlueprint.versions.wp,\n\t\t\t\t\tabsoluteUrl,\n\t\t\t\t\tmountsBeforeWpInstall,\n\t\t\t\t\tmountsAfterWpInstall,\n\t\t\t\t\twordPressZip:\n\t\t\t\t\t\twordPressZip && (await wordPressZip!.arrayBuffer()),\n\t\t\t\t\tsqliteIntegrationPluginZip:\n\t\t\t\t\t\tawait sqliteIntegrationPluginZip!.arrayBuffer(),\n\t\t\t\t\tfirstProcessId: 0,\n\t\t\t\t\tprocessIdSpaceLength,\n\t\t\t\t\tfollowSymlinks,\n\t\t\t\t\ttrace,\n\t\t\t\t});\n\n\t\t\t\tif (\n\t\t\t\t\twpDetails &&\n\t\t\t\t\t!args.mountBeforeInstall &&\n\t\t\t\t\t!fs.existsSync(preinstalledWpContentPath)\n\t\t\t\t) {\n\t\t\t\t\tlogger.log(\n\t\t\t\t\t\t`Caching preinstalled WordPress for the next boot...`\n\t\t\t\t\t);\n\t\t\t\t\tfs.writeFileSync(\n\t\t\t\t\t\tpreinstalledWpContentPath,\n\t\t\t\t\t\tawait zipDirectory(playground, '/wordpress')\n\t\t\t\t\t);\n\t\t\t\t\tlogger.log(`Cached!`);\n\t\t\t\t}\n\n\t\t\t\tloadBalancer = new LoadBalancer(playground);\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\tif (compiledBlueprint) {\n\t\t\t\t\tlogger.log(`Running the Blueprint...`);\n\t\t\t\t\tawait runBlueprintSteps(compiledBlueprint, playground);\n\t\t\t\t\tlogger.log(`Finished running the blueprint`);\n\t\t\t\t}\n\n\t\t\t\tif (args.command === 'build-snapshot') {\n\t\t\t\t\tawait zipSite(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// Save /internal directory from initial worker so we can replicate it\n\t\t\t\t\t// in each additional worker.\n\t\t\t\t\tconst internalZip = await zipDirectory(\n\t\t\t\t\t\tplayground,\n\t\t\t\t\t\t'/internal'\n\t\t\t\t\t);\n\n\t\t\t\t\t// Boot additional workers\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 additionalPlayground =\n\t\t\t\t\t\t\t\tconsumeAPI<PlaygroundCliWorker>(worker);\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,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tawait additionalPlayground.isConnected();\n\t\t\t\t\t\t\texposeAPI(fileLockManager, undefined, worker);\n\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\tawait additionalPlayground.boot({\n\t\t\t\t\t\t\t\tphpVersion: compiledBlueprint.versions.php,\n\t\t\t\t\t\t\t\tabsoluteUrl,\n\t\t\t\t\t\t\t\tmountsBeforeWpInstall,\n\t\t\t\t\t\t\t\tmountsAfterWpInstall,\n\t\t\t\t\t\t\t\t// Skip WordPress zip because we share the /wordpress directory\n\t\t\t\t\t\t\t\t// populated by the initial worker.\n\t\t\t\t\t\t\t\twordPressZip: undefined,\n\t\t\t\t\t\t\t\t// Skip SQLite integration plugin for now because we\n\t\t\t\t\t\t\t\t// will copy it from primary's `/internal` directory.\n\t\t\t\t\t\t\t\tsqliteIntegrationPluginZip: undefined,\n\t\t\t\t\t\t\t\tdataSqlPath:\n\t\t\t\t\t\t\t\t\t'/wordpress/wp-content/database/.ht.sqlite',\n\t\t\t\t\t\t\t\tfirstProcessId,\n\t\t\t\t\t\t\t\tprocessIdSpaceLength,\n\t\t\t\t\t\t\t\tfollowSymlinks,\n\t\t\t\t\t\t\t\ttrace,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tawait additionalPlayground.isReady();\n\n\t\t\t\t\t\t\t// Replicate the Blueprint-initialized /internal directory\n\t\t\t\t\t\t\tawait additionalPlayground.writeFile(\n\t\t\t\t\t\t\t\t'/tmp/internal.zip',\n\t\t\t\t\t\t\t\tinternalZip\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tawait unzipFile(\n\t\t\t\t\t\t\t\tadditionalPlayground,\n\t\t\t\t\t\t\t\t'/tmp/internal.zip',\n\t\t\t\t\t\t\t\t'/internal'\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tawait additionalPlayground.unlink(\n\t\t\t\t\t\t\t\t'/tmp/internal.zip'\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\n\t\t\t\t\tlogger.log(`Ready!`);\n\t\t\t\t}\n\n\t\t\t\tlogger.log(`WordPress is running on ${absoluteUrl}`);\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};\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\tconst phpLogs = await playground.readFileAsText(errorLogPath);\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\treturn await loadBalancer.handleRequest(request);\n\t\t},\n\t});\n}\n"],"names":["expandAutoMounts","args","path","mount","mountBeforeInstall","isPluginDirectory","pluginName","basename","isThemeDirectory","themeName","containsWpContentDirectories","wpContentMounts","containsFullWordPressInstallation","files","fs","mounts","file","join","blueprint","getSteps","skipWordPressSetup","styleCssContent","pluginNameRegex","fileContent","wpContentDir","CACHE_FOLDER","os","fetchSqliteIntegration","monitor","cachedDownload","remoteUrl","cacheKey","artifactPath","downloadTo","readAsFile","localPath","reader","tmpPath","writer","done","value","resolve","reject","err","fileName","startServer","options","app","express","server","address","req","res","phpResponse","parseHeaders","bufferRequestBody","key","port","body","chunk","requestHeaders","i","LoadBalancer","initialWorker","worker","request","smallestWorkerLoad","workerLoad","promiseForResponse","runCLI","loadBalancer","playground","playgroundsToCleanUp","zipSite","outfile","zip","compileInputBlueprint","isBlueprintBundle","RecommendedPHPVersion","tracker","ProgressTracker","lastCaption","progressReached100","e","progressInteger","message","writeProgressUpdate","compileBlueprint","lastProgressMessage","writeStream","finalUpdate","spawnPHPWorkerThread","workerUrl","Worker","onMessage","event","onError","error","spawnWorkerThreads","count","moduleWorkerUrl","importedWorkerUrlString","promises","logger","compiledBlueprint","fileLockManager","FileLockManagerForNode","wordPressReady","absoluteUrl","totalWorkerCount","promisedWorkers","wpDetails","EmscriptenDownloadMonitor","loaded","total","percentProgress","resolveWordPressRelease","preinstalledWpContentPath","wordPressZip","sqliteIntegrationPluginZip","followSymlinks","trace","mountsBeforeWpInstall","mountsAfterWpInstall","additionalWorkers","consumeAPI","exposeAPI","processIdSpaceLength","zipDirectory","runBlueprintSteps","internalZip","initialWorkerProcessIdSpace","index","additionalPlayground","firstProcessId","unzipFile","phpLogs","errorLogPath","PHPResponse"],"mappings":";;;;;;;;;;;;;;AASO,SAASA,GAAiBC,GAA8B;AACxD,QAAAC,IAAO,QAAQ,IAAI,GAEnBC,IAAQ,CAAC,GAAIF,EAAK,SAAS,CAAA,CAAG,GAC9BG,IAAqB,CAAC,GAAIH,EAAK,sBAAsB,CAAA,CAAG;AAE1D,MAAAI,EAAkBH,CAAI,GAAG;AACtB,UAAAI,IAAaC,EAASL,CAAI;AAChC,IAAAC,EAAM,KAAK;AAAA,MACV,UAAUD;AAAA,MACV,SAAS,iCAAiCI,CAAU;AAAA,IAAA,CACpD;AAAA,EAAA,WACSE,EAAiBN,CAAI,GAAG;AAC5B,UAAAO,IAAYF,EAASL,CAAI;AAC/B,IAAAC,EAAM,KAAK;AAAA,MACV,UAAUD;AAAA,MACV,SAAS,gCAAgCO,CAAS;AAAA,IAAA,CAClD;AAAA,EAAA,WACSC,EAA6BR,CAAI;AAC3C,IAAAC,EAAM,KAA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uC,IAAU,MAAMjE,EAAW,eAAekE,CAAY;AAC5D,cAAM,IAAI,MAAMD,GAAS,EAAE,OAAOvC,GAAO;AAAA,MAAA;AAAA,IAE3C;AAAA,IACA,MAAM,cAAchC,GAAqB;AACxC,aAAK0C,IAME,MAAMrC,EAAa,cAAcL,CAAO,IALvCyE,GAAY;AAAA,QAClB;AAAA,QACA;AAAA,MACD;AAAA,IAE8C;AAAA,EAChD,CACA;AACF;"}
@@ -0,0 +1,31 @@
1
+ "use strict";const p=require("@php-wasm/logger"),Z=require("@php-wasm/progress"),B=require("@php-wasm/universal"),x=require("@wp-playground/blueprints"),L=require("@wp-playground/common"),h=require("fs"),m=require("path"),K=require("worker_threads"),W=require("fs-extra"),ee=require("os"),te=require("express"),re=require("@wp-playground/wordpress"),ne=require("@php-wasm/node");var z=typeof document<"u"?document.currentScript:null;const oe=""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/worker-thread-BQ8BezvJ.js").href:new URL("worker-thread-BQ8BezvJ.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href);function se(e){const t=process.cwd(),r=[...e.mount||[]],n=[...e.mountBeforeInstall||[]];if(O(t)){const s=m.basename(t);r.push({hostPath:t,vfsPath:`/wordpress/wp-content/plugins/${s}`})}else if(V(t)){const s=m.basename(t);r.push({hostPath:t,vfsPath:`/wordpress/wp-content/themes/${s}`})}else if(j(t))r.push(...D(t));else if(T(t)){const s=h.readdirSync(t),c=[];for(const u of s)u.startsWith("wp-content")||c.push({hostPath:`${t}/${u}`,vfsPath:`/wordpress/${u}`});n.push(...c,...D(m.join(t,"wp-content")))}else r.push({hostPath:t,vfsPath:"/wordpress"});const l=e.blueprint||{};l.steps=[...l.steps||[],...ie(t)];const i=e.skipWordPressSetup||T(t);return{...e,blueprint:l,mount:r,mountBeforeInstall:n,skipWordPressSetup:i}}function T(e){const t=h.readdirSync(e);return t.includes("wp-admin")&&t.includes("wp-includes")&&t.includes("wp-content")}function j(e){const t=h.readdirSync(e);return t.includes("themes")||t.includes("plugins")||t.includes("mu-plugins")||t.includes("uploads")}function V(e){if(!h.readdirSync(e).includes("style.css"))return!1;const r=h.readFileSync(m.join(e,"style.css"),"utf8");return!!/^(?:[ \t]*<\?php)?[ \t/*#@]*Theme Name:(.*)$/im.exec(r)}function O(e){const t=h.readdirSync(e),r=/^(?:[ \t]*<\?php)?[ \t/*#@]*Plugin Name:(.*)$/im;return!!t.filter(l=>l.endsWith(".php")).find(l=>{const i=h.readFileSync(m.join(e,l),"utf8");return!!r.exec(i)})}function D(e){return h.readdirSync(e).filter(r=>!r.startsWith("index.php")).map(r=>({hostPath:`${e}/${r}`,vfsPath:`/wordpress/wp-content/${r}`}))}function ie(e){return O(e)?[{step:"activatePlugin",pluginPath:`/wordpress/wp-content/plugins/${m.basename(e)}`}]:V(e)?[{step:"activateTheme",themeFolderName:m.basename(e)}]:j(e)||T(e)?[{step:"runPHP",code:`<?php
2
+ require_once '/wordpress/wp-load.php';
3
+ $theme = wp_get_theme();
4
+ if (!$theme->exists()) {
5
+ $themes = wp_get_themes();
6
+ if (count($themes) > 0) {
7
+ $themeName = array_keys($themes)[0];
8
+ switch_theme($themeName);
9
+ }
10
+ }
11
+ `}]:[]}const E=m.join(ee.homedir(),".wordpress-playground");async function ae(e){return await Q("https://github.com/WordPress/sqlite-database-integration/archive/refs/heads/develop.zip","sqlite.zip",e)}async function Q(e,t,r){const n=m.join(E,t);return W.existsSync(n)||(W.ensureDirSync(E),await le(e,n,r)),J(n)}async function le(e,t,r){const l=(await r.monitorFetch(fetch(e))).body.getReader(),i=`${t}.partial`,s=W.createWriteStream(i);for(;;){const{done:c,value:u}=await l.read();if(u&&s.write(u),c)break}s.close(),s.closed||await new Promise((c,u)=>{s.on("finish",()=>{W.renameSync(i,t),c(null)}),s.on("error",C=>{W.removeSync(i),u(C)})})}function J(e,t){return new File([W.readFileSync(e)],m.basename(e))}async function ce(e){const t=te(),r=await new Promise((i,s)=>{const c=t.listen(e.port,()=>{const u=c.address();u===null||typeof u=="string"?s(new Error("Server address is not available")):i(c)})});t.use("/",async(i,s)=>{const c=await e.handleRequest({url:i.url,headers:ue(i),method:i.method,body:await pe(i)});s.statusCode=c.httpStatusCode;for(const u in c.headers)s.setHeader(u,c.headers[u]);s.end(c.bytes)});const l=r.address().port;return await e.onBind(r,l)}const pe=async e=>await new Promise(t=>{const r=[];e.on("data",n=>{r.push(n)}),e.on("end",()=>{t(new Uint8Array(Buffer.concat(r)))})}),ue=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 de{constructor(t){this.workerLoads=[],this.addWorker(t)}addWorker(t){this.workerLoads.push({worker:t,activeRequests:new Set})}async handleRequest(t){let r=this.workerLoads[0];for(let l=1;l<this.workerLoads.length;l++){const i=this.workerLoads[l];i.activeRequests.size<r.activeRequests.size&&(r=i)}const n=r.worker.request(t);return r.activeRequests.add(n),n.url=t.url,n.finally(()=>{r.activeRequests.delete(n)})}}async function fe(e){let t,r;const n=[];e.autoMount&&(e=se(e));async function l(o){await r.run({code:`<?php
12
+ $zip = new ZipArchive();
13
+ if(false === $zip->open('/tmp/build.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
14
+ throw new Exception('Failed to create ZIP');
15
+ }
16
+ $files = new RecursiveIteratorIterator(
17
+ new RecursiveDirectoryIterator('/wordpress')
18
+ );
19
+ foreach ($files as $file) {
20
+ echo $file . PHP_EOL;
21
+ if (!$file->isFile()) {
22
+ continue;
23
+ }
24
+ $zip->addFile($file->getPathname(), $file->getPathname());
25
+ }
26
+ $zip->close();
27
+
28
+ `});const a=await r.readFileAsBuffer("/tmp/build.zip");h.writeFileSync(o,a)}async function i(){const o=x.isBlueprintBundle(e.blueprint)?e.blueprint:{login:e.login,...e.blueprint,preferredVersions:{php:e.php??e?.blueprint?.preferredVersions?.php??L.RecommendedPHPVersion,wp:e.wp??e?.blueprint?.preferredVersions?.wp??"latest",...e.blueprint?.preferredVersions||{}}},a=new Z.ProgressTracker;let d="",w=!1;return a.addEventListener("progress",y=>{if(w)return;w=y.detail.progress===100;const f=Math.floor(y.detail.progress);d=y.detail.caption||d||"Running the Blueprint";const g=`${d.trim()} – ${f}%`;e.quiet||c(process.stdout,g,w)}),await x.compileBlueprint(o,{progress:a})}let s="";function c(o,a,d){a!==s&&(s=a,o.isTTY?(o.cursorTo(0),o.write(a),o.clearLine(1),d&&o.write(`
29
+ `)):o.write(`${a}
30
+ `))}async function u(o){const a=new K.Worker(o);return new Promise((d,w)=>{function y(g){g==="worker-script-initialized"&&(d(a),a.off("message",y))}function f(g){const R=new Error(`Worker failed to load at ${o}. ${g.message?`Original error: ${g.message}`:""}`);R.filename=o,w(R),a.off("error",f)}a.on("message",y),a.on("error",f)})}function C(o){const a=new URL(oe,typeof document>"u"?require("url").pathToFileURL(__filename).href:z&&z.tagName.toUpperCase()==="SCRIPT"&&z.src||new URL("run-cli-s3Rtz7Gj.cjs",document.baseURI).href),d=[];for(let w=0;w<o;w++)d.push(u(a));return Promise.all(d)}e.quiet&&(p.logger.handlers=[]);const b=await i(),M=new ne.FileLockManagerForNode;let N=!1;return p.logger.log("Starting a PHP server..."),ce({port:e.port,onBind:async(o,a)=>{const d=`http://127.0.0.1:${a}`,w=e.experimentalMultiWorker??1,y=C(w);p.logger.log(`Setting up WordPress ${e.wp}`);let f;const g=new Z.EmscriptenDownloadMonitor;if(!e.skipWordPressSetup){let P=!1;g.addEventListener("progress",k=>{if(P)return;const{loaded:$,total:F}=k.detail,S=Math.floor(Math.min(100,100*$/F));P=S===100,e.quiet||c(process.stdout,`Downloading WordPress ${S}%...`,P)}),f=await re.resolveWordPressRelease(e.wp),p.logger.log(`Resolved WordPress release URL: ${f?.releaseUrl}`)}const R=f&&m.join(E,`prebuilt-wp-content-for-wp-${f.version}.zip`),A=f?h.existsSync(R)?J(R):await Q(f.releaseUrl,`${f.version}.zip`,g):void 0;p.logger.log("Fetching SQLite integration plugin...");const G=e.skipSqliteSetup?void 0:await ae(g),_=e.followSymlinks===!0,H=e.experimentalTrace===!0;try{const P=e.mountBeforeInstall||[],k=e.mount||[],[$,...F]=await y;r=B.consumeAPI($),n.push({playground:r,worker:$}),await r.isConnected(),B.exposeAPI(M,void 0,$),p.logger.log("Booting WordPress...");const S=Math.floor(Number.MAX_SAFE_INTEGER/w);if(await r.boot({phpVersion:b.versions.php,wpVersion:b.versions.wp,absoluteUrl:d,mountsBeforeWpInstall:P,mountsAfterWpInstall:k,wordPressZip:A&&await A.arrayBuffer(),sqliteIntegrationPluginZip:await G.arrayBuffer(),firstProcessId:0,processIdSpaceLength:S,followSymlinks:_,trace:H}),f&&!e.mountBeforeInstall&&!h.existsSync(R)&&(p.logger.log("Caching preinstalled WordPress for the next boot..."),h.writeFileSync(R,await L.zipDirectory(r,"/wordpress")),p.logger.log("Cached!")),t=new de(r),await r.isReady(),N=!0,p.logger.log("Booted!"),b&&(p.logger.log("Running the Blueprint..."),await x.runBlueprintSteps(b,r),p.logger.log("Finished running the blueprint")),e.command==="build-snapshot"?(await l(e.outfile),p.logger.log(`WordPress exported to ${e.outfile}`),process.exit(0)):e.command==="run-blueprint"&&(p.logger.log("Blueprint executed"),process.exit(0)),e.experimentalMultiWorker&&e.experimentalMultiWorker>1){p.logger.log("Preparing additional workers...");const U=await L.zipDirectory(r,"/internal"),I=S;await Promise.all(F.map(async(q,X)=>{const v=B.consumeAPI(q);n.push({playground:v,worker:q}),await v.isConnected(),B.exposeAPI(M,void 0,q);const Y=I+X*S;await v.boot({phpVersion:b.versions.php,absoluteUrl:d,mountsBeforeWpInstall:P,mountsAfterWpInstall:k,wordPressZip:void 0,sqliteIntegrationPluginZip:void 0,dataSqlPath:"/wordpress/wp-content/database/.ht.sqlite",firstProcessId:Y,processIdSpaceLength:S,followSymlinks:_,trace:H}),await v.isReady(),await v.writeFile("/tmp/internal.zip",U),await L.unzipFile(v,"/tmp/internal.zip","/internal"),await v.unlink("/tmp/internal.zip"),t.addWorker(v)})),p.logger.log("Ready!")}return p.logger.log(`WordPress is running on ${d}`),{playground:r,server:o,[Symbol.asyncDispose]:async function(){await Promise.all(n.map(async({playground:I,worker:q})=>{await I.dispose(),await q.terminate()})),await new Promise(I=>o.close(I))}}}catch(P){if(!e.debug)throw P;const k=await r.readFileAsText(p.errorLogPath);throw new Error(k,{cause:P})}},async handleRequest(o){return N?await t.handleRequest(o):B.PHPResponse.forHttpCode(502,"WordPress is not ready yet")}})}exports.runCLI=fe;
31
+ //# sourceMappingURL=run-cli-s3Rtz7Gj.cjs.map