@wp-playground/cli 3.0.43 → 3.0.44
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/worker-thread-v1.d.ts +5 -0
- package/blueprints-v2/blueprints-v2-handler.d.ts +1 -1
- package/blueprints-v2/worker-thread-v2.d.ts +5 -0
- package/cli.cjs +1 -1
- package/cli.js +1 -1
- package/defines.d.ts +53 -0
- package/index.cjs +1 -1
- package/index.js +6 -5
- package/package.json +13 -13
- package/{run-cli-NcKUE5gJ.js → run-cli-DOpShCrT.js} +497 -391
- package/run-cli-DOpShCrT.js.map +1 -0
- package/run-cli-le2xCSBZ.cjs +64 -0
- package/run-cli-le2xCSBZ.cjs.map +1 -0
- package/run-cli.d.ts +16 -1
- package/worker-thread-v1.cjs +2 -2
- package/worker-thread-v1.cjs.map +1 -1
- package/worker-thread-v1.js +32 -34
- package/worker-thread-v1.js.map +1 -1
- package/worker-thread-v2.cjs +4 -4
- package/worker-thread-v2.cjs.map +1 -1
- package/worker-thread-v2.js +34 -36
- package/worker-thread-v2.js.map +1 -1
- package/run-cli-B8Dv6R-o.cjs +0 -64
- package/run-cli-B8Dv6R-o.cjs.map +0 -1
- package/run-cli-NcKUE5gJ.js.map +0 -1
package/worker-thread-v2.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-thread-v2.js","sources":["../../../../packages/playground/cli/src/blueprints-v2/worker-thread-v2.ts"],"sourcesContent":["import { errorLogPath, logger } from '@php-wasm/logger';\nimport type { FileLockManager } from '@php-wasm/node';\nimport { createNodeFsMountHandler, loadNodeRuntime } from '@php-wasm/node';\nimport { EmscriptenDownloadMonitor } from '@php-wasm/progress';\nimport type {\n\tPHP,\n\tFileTree,\n\tRemoteAPI,\n\tSupportedPHPVersion,\n\tSpawnHandler,\n} from '@php-wasm/universal';\nimport {\n\tPHPExecutionFailureError,\n\tPHPResponse,\n\tPHPWorker,\n\tconsumeAPI,\n\tconsumeAPISync,\n\texposeAPI,\n\tsandboxedSpawnHandlerFactory,\n} from '@php-wasm/universal';\nimport { sprintf } from '@php-wasm/util';\nimport {\n\ttype BlueprintMessage,\n\trunBlueprintV2,\n\ttype BlueprintV1Declaration,\n} from '@wp-playground/blueprints';\nimport {\n\ttype ParsedBlueprintV2String,\n\ttype RawBlueprintV2Data,\n} from '@wp-playground/blueprints';\nimport { bootRequestHandler } from '@wp-playground/wordpress';\nimport { existsSync } from 'fs';\nimport path from 'path';\nimport { rootCertificates } from 'tls';\nimport { MessageChannel, type MessagePort, parentPort } from 'worker_threads';\nimport { jspi } from 'wasm-feature-detect';\nimport { spawnWorkerThread, type RunCLIArgs } from '../run-cli';\nimport type {\n\tPhpIniOptions,\n\tPHPInstanceCreatedHook,\n} from '@wp-playground/wordpress';\nimport { shouldRenderProgress } from '../utils/progress';\nimport type { Mount } from '@php-wasm/cli-util';\n\nasync function mountResources(php: PHP, mounts: Mount[]) {\n\tfor (const mount of mounts) {\n\t\ttry {\n\t\t\tphp.mkdir(mount.vfsPath);\n\t\t\tawait php.mount(\n\t\t\t\tmount.vfsPath,\n\t\t\t\tcreateNodeFsMountHandler(mount.hostPath)\n\t\t\t);\n\t\t} catch {\n\t\t\toutput.stderr(\n\t\t\t\t`\\x1b[31m\\x1b[1mError mounting path ${mount.hostPath} at ${mount.vfsPath}\\x1b[0m\\n`\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\t}\n}\n\n/**\n * Print trace messages from PHP-WASM.\n *\n * @param {number} processId - The process ID.\n * @param {string} format - The format string.\n * @param {...any} args - The arguments.\n */\nfunction tracePhpWasm(processId: number, format: string, ...args: any[]) {\n\t// eslint-disable-next-line no-console\n\tconsole.log(\n\t\tperformance.now().toFixed(6).padStart(15, '0'),\n\t\tprocessId.toString().padStart(16, '0'),\n\t\tsprintf(format, ...args)\n\t);\n}\n\n/**\n * Force TTY status to preserve ANSI control codes in the output\n * when the environment is interactive.\n *\n * This script is spawned as `new Worker()` and process.stdout and process.stderr are\n * WritableWorkerStdio objects. By default, they strip ANSI control codes from the output\n * causing every progress bar update to be printed in a new line instead of updating the\n * same line.\n */\nObject.defineProperty(process.stdout, 'isTTY', { value: true });\nObject.defineProperty(process.stderr, 'isTTY', { value: true });\n\n/**\n * Output writer that ensures that progress bars are not printed on the same line as other output.\n */\nconst output = {\n\tlastWriteWasProgress: false,\n\tprogress(data: string) {\n\t\tif (!shouldRenderProgress(process.stdout)) {\n\t\t\treturn;\n\t\t}\n\t\tif (!process.stdout.isTTY) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.log(data);\n\t\t} else {\n\t\t\tif (!output.lastWriteWasProgress) {\n\t\t\t\tprocess.stdout.write('\\n');\n\t\t\t}\n\t\t\tprocess.stdout.write('\\r\\x1b[K' + data);\n\t\t\toutput.lastWriteWasProgress = true;\n\t\t}\n\t},\n\tstdout(data: string) {\n\t\tprocess.stdout.write('\\n\\n\\n');\n\t\tif (output.lastWriteWasProgress) {\n\t\t\toutput.lastWriteWasProgress = false;\n\t\t}\n\t\tprocess.stdout.write(data);\n\t},\n\tstderr(data: string) {\n\t\tprocess.stdout.write('\\n\\n\\n');\n\t\tif (output.lastWriteWasProgress) {\n\t\t\toutput.lastWriteWasProgress = false;\n\t\t}\n\t\tprocess.stderr.write(data);\n\t},\n};\n\nexport type PrimaryWorkerBootArgs = Omit<\n\tRunCLIArgs,\n\t'mount-before-install' | 'mount'\n> & {\n\tphpVersion: SupportedPHPVersion;\n\tsiteUrl: string;\n\tfirstProcessId: number;\n\tprocessIdSpaceLength: number;\n\ttrace: boolean;\n\tblueprint:\n\t\t| RawBlueprintV2Data\n\t\t| ParsedBlueprintV2String\n\t\t| BlueprintV1Declaration;\n\tnativeInternalDirPath: string;\n\tmountsBeforeWpInstall?: Array<Mount>;\n\tmountsAfterWpInstall?: Array<Mount>;\n};\n\ntype WorkerRunBlueprintArgs = Omit<\n\tRunCLIArgs,\n\t'mount-before-install' | 'mount'\n> & {\n\tsiteUrl: string;\n\tblueprint:\n\t\t| RawBlueprintV2Data\n\t\t| ParsedBlueprintV2String\n\t\t| BlueprintV1Declaration;\n\tmountsAfterWpInstall?: Array<Mount>;\n};\n\nexport type SecondaryWorkerBootArgs = {\n\tsiteUrl: string;\n\tallow?: string;\n\tphpVersion: SupportedPHPVersion;\n\tphpIniEntries?: PhpIniOptions;\n\tconstants?: Record<string, string | number | boolean | null>;\n\tcreateFiles?: FileTree;\n\tfirstProcessId: number;\n\tprocessIdSpaceLength: number;\n\ttrace: boolean;\n\tnativeInternalDirPath: string;\n\twithIntl?: boolean;\n\twithXdebug?: boolean;\n\tmountsBeforeWpInstall?: Array<Mount>;\n\tmountsAfterWpInstall?: Array<Mount>;\n};\n\nexport type WorkerBootRequestHandlerOptions = Omit<\n\tSecondaryWorkerBootArgs,\n\t'mountsBeforeWpInstall' | 'mountsAfterWpInstall'\n> & {\n\tonPHPInstanceCreated: PHPInstanceCreatedHook;\n\tspawnHandler: () => SpawnHandler;\n};\n\nexport class PlaygroundCliBlueprintV2Worker extends PHPWorker {\n\tbooted = false;\n\tblueprintTargetResolved = false;\n\tphpInstancesThatNeedMountsAfterTargetResolved = new Set<PHP>();\n\tfileLockManager: RemoteAPI<FileLockManager> | FileLockManager | undefined;\n\n\tconstructor(monitor: EmscriptenDownloadMonitor) {\n\t\tsuper(undefined, monitor);\n\t}\n\n\t/**\n\t * Call this method before boot() to use file locking.\n\t *\n\t * This method is separate from boot() to simplify the related Comlink.transferHandlers\n\t * setup – if an argument is a MessagePort, we're transferring it, not copying it.\n\t *\n\t * @see comlink-sync.ts\n\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t */\n\tasync useFileLockManager(port: MessagePort) {\n\t\tif (await jspi()) {\n\t\t\t/**\n\t\t\t * If JSPI is available, php.js supports both synchronous and asynchronous locking syscalls.\n\t\t\t * Web browsers, however, only support asynchronous message passing so let's use the\n\t\t\t * asynchronous API. Every method call will return a promise.\n\t\t\t *\n\t\t\t * @see comlink-sync.ts\n\t\t\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t\t\t */\n\t\t\tthis.fileLockManager = consumeAPI<FileLockManager>(port);\n\t\t} else {\n\t\t\t/**\n\t\t\t * If JSPI is not available, php.js only supports synchronous locking syscalls.\n\t\t\t * Let's use the synchronous API. Every method call will block this thread\n\t\t\t * until the result is available.\n\t\t\t *\n\t\t\t * @see comlink-sync.ts\n\t\t\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t\t\t */\n\t\t\tthis.fileLockManager = await consumeAPISync<FileLockManager>(port);\n\t\t}\n\t}\n\n\tasync bootAndSetUpInitialWorker(args: PrimaryWorkerBootArgs) {\n\t\tconst constants = {\n\t\t\tWP_DEBUG: true,\n\t\t\tWP_DEBUG_LOG: true,\n\t\t\tWP_DEBUG_DISPLAY: false,\n\t\t};\n\t\tconst requestHandlerOptions: WorkerBootRequestHandlerOptions = {\n\t\t\t...args,\n\t\t\tcreateFiles: {\n\t\t\t\t'/internal/shared/ca-bundle.crt': rootCertificates.join('\\n'),\n\t\t\t},\n\t\t\tconstants,\n\t\t\tphpIniEntries: {\n\t\t\t\t'openssl.cafile': '/internal/shared/ca-bundle.crt',\n\t\t\t},\n\t\t\tonPHPInstanceCreated: async (php: PHP) => {\n\t\t\t\tawait mountResources(php, args.mountsBeforeWpInstall || []);\n\t\t\t\tif (this.blueprintTargetResolved) {\n\t\t\t\t\tawait mountResources(php, args.mountsAfterWpInstall || []);\n\t\t\t\t} else {\n\t\t\t\t\t// NOTE: Today (2025-09-11), during boot with a plugin auto-mount,\n\t\t\t\t\t// the Blueprint runner fails unless post-resolution mounts are\n\t\t\t\t\t// added to existing PHP instances. So we track them here so they\n\t\t\t\t\t// can be mounted at the necessary time.\n\t\t\t\t\t// Only plugin auto-mounts seem to need this, so perhaps there\n\t\t\t\t\t// is a change we can make to the Blueprint runner so such\n\t\t\t\t\t// a dance is unnecessary.\n\t\t\t\t\tthis.phpInstancesThatNeedMountsAfterTargetResolved.add(php);\n\t\t\t\t\tphp.addEventListener('runtime.beforeExit', () => {\n\t\t\t\t\t\tthis.phpInstancesThatNeedMountsAfterTargetResolved.delete(\n\t\t\t\t\t\t\tphp\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\tspawnHandler: () =>\n\t\t\t\tsandboxedSpawnHandlerFactory(() =>\n\t\t\t\t\tcreatePHPWorker(args, this.fileLockManager!)\n\t\t\t\t),\n\t\t};\n\t\tawait this.bootRequestHandler(requestHandlerOptions);\n\n\t\tconst primaryPhp = this.__internal_getPHP()!;\n\n\t\tif (args.mode === 'mount-only') {\n\t\t\tawait mountResources(primaryPhp, args.mountsAfterWpInstall || []);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runBlueprintV2({\n\t\t\t...args,\n\t\t\tmountsAfterWpInstall: args.mountsAfterWpInstall || [],\n\t\t});\n\t}\n\n\tasync bootWorker(args: SecondaryWorkerBootArgs) {\n\t\tawait this.bootRequestHandler({\n\t\t\t...args,\n\t\t\tonPHPInstanceCreated: async (php: PHP) => {\n\t\t\t\tawait mountResources(php, args.mountsBeforeWpInstall || []);\n\t\t\t\tawait mountResources(php, args.mountsAfterWpInstall || []);\n\n\t\t\t\t// Temporary workaround for LOCK_EX in sqlite-database-integration.\n\t\t\t\t// Creation of these files results in this error:\n\t\t\t\t// PHP Warning: file_put_contents(): Exclusive locks are not supported for this stream\n\t\t\t\t// in\n\t\t\t\t// /wordpress/wp-content/plugins/sqlite-database-integration/wp-includes/sqlite/class-wp-sqlite-db.php\n\t\t\t\t// on line 670\n\t\t\t\tif (!php.isDir('/wordpress/wp-content')) {\n\t\t\t\t\tphp.mkdir('/wordpress/wp-content');\n\t\t\t\t}\n\t\t\t\tif (!php.isDir('/wordpress/wp-content/database')) {\n\t\t\t\t\tphp.mkdir('/wordpress/wp-content/database');\n\t\t\t\t}\n\t\t\t\tif (!php.isFile('/wordpress/wp-content/database/.htaccess')) {\n\t\t\t\t\tphp.writeFile(\n\t\t\t\t\t\t'/wordpress/wp-content/database/.htaccess',\n\t\t\t\t\t\t'deny from all'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (!php.isFile('/wordpress/wp-content/database/index.php')) {\n\t\t\t\t\tphp.writeFile(\n\t\t\t\t\t\t'/wordpress/wp-content/database/index.php',\n\t\t\t\t\t\t'deny from all'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t\tspawnHandler: () =>\n\t\t\t\tsandboxedSpawnHandlerFactory(() =>\n\t\t\t\t\tcreatePHPWorker(args, this.fileLockManager!)\n\t\t\t\t),\n\t\t});\n\t}\n\n\tasync runBlueprintV2(args: WorkerRunBlueprintArgs) {\n\t\tconst requestHandler = this.__internal_getRequestHandler()!;\n\t\tconst { php, reap } =\n\t\t\tawait requestHandler.instanceManager.acquirePHPInstance({\n\t\t\t\tconsiderPrimary: false,\n\t\t\t});\n\n\t\t// Mount the current working directory to the PHP runtime for the purposes of\n\t\t// Blueprint resolution.\n\t\tconst primaryPhp = this.__internal_getPHP()!;\n\t\tlet unmountCwd = () => {};\n\t\tif (typeof args.blueprint === 'string') {\n\t\t\tconst blueprintPath = path.resolve(process.cwd(), args.blueprint);\n\t\t\tif (existsSync(blueprintPath)) {\n\t\t\t\tprimaryPhp.mkdir('/internal/shared/cwd');\n\t\t\t\tunmountCwd = await primaryPhp.mount(\n\t\t\t\t\t'/internal/shared/cwd',\n\t\t\t\t\tcreateNodeFsMountHandler(path.dirname(blueprintPath))\n\t\t\t\t);\n\t\t\t\targs.blueprint = path.join(\n\t\t\t\t\t'/internal/shared/cwd',\n\t\t\t\t\tpath.basename(args.blueprint)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tconst cliArgsToPass: (keyof WorkerRunBlueprintArgs)[] = [\n\t\t\t\t'mode',\n\t\t\t\t'db-engine',\n\t\t\t\t'db-host',\n\t\t\t\t'db-user',\n\t\t\t\t'db-pass',\n\t\t\t\t'db-name',\n\t\t\t\t'db-path',\n\t\t\t\t'truncate-new-site-directory',\n\t\t\t\t'allow',\n\t\t\t];\n\t\t\tconst cliArgs = cliArgsToPass\n\t\t\t\t.filter((arg) => arg in args)\n\t\t\t\t.map((arg) => `--${arg}=${args[arg]}`);\n\t\t\tcliArgs.push(`--site-url=${args.siteUrl}`);\n\n\t\t\tconst streamedResponse = await runBlueprintV2({\n\t\t\t\tphp,\n\t\t\t\tblueprint: args.blueprint,\n\t\t\t\tblueprintOverrides: {\n\t\t\t\t\tadditionalSteps: args['additional-blueprint-steps'],\n\t\t\t\t\twordpressVersion: args.wp,\n\t\t\t\t},\n\t\t\t\tcliArgs,\n\t\t\t\tonMessage: async (message: BlueprintMessage) => {\n\t\t\t\t\tswitch (message.type) {\n\t\t\t\t\t\tcase 'blueprint.target_resolved': {\n\t\t\t\t\t\t\tif (!this.blueprintTargetResolved) {\n\t\t\t\t\t\t\t\tthis.blueprintTargetResolved = true;\n\t\t\t\t\t\t\t\tfor (const php of this\n\t\t\t\t\t\t\t\t\t.phpInstancesThatNeedMountsAfterTargetResolved) {\n\t\t\t\t\t\t\t\t\t// console.log('mounting resources for php', php);\n\t\t\t\t\t\t\t\t\tthis.phpInstancesThatNeedMountsAfterTargetResolved.delete(\n\t\t\t\t\t\t\t\t\t\tphp\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\tawait mountResources(\n\t\t\t\t\t\t\t\t\t\tphp,\n\t\t\t\t\t\t\t\t\t\targs.mountsAfterWpInstall || []\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'blueprint.progress': {\n\t\t\t\t\t\t\tconst progressMessage = `${message.caption.trim()} – ${message.progress.toFixed(\n\t\t\t\t\t\t\t\t2\n\t\t\t\t\t\t\t)}%`;\n\t\t\t\t\t\t\toutput.progress(progressMessage);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'blueprint.error': {\n\t\t\t\t\t\t\tconst red = '\\x1b[31m';\n\t\t\t\t\t\t\tconst bold = '\\x1b[1m';\n\t\t\t\t\t\t\tconst reset = '\\x1b[0m';\n\t\t\t\t\t\t\tif (args.verbosity === 'debug' && message.details) {\n\t\t\t\t\t\t\t\toutput.stderr(\n\t\t\t\t\t\t\t\t\t`${red}${bold}Fatal error:${reset} Uncaught ${message.details.exception}: ${message.details.message}\\n` +\n\t\t\t\t\t\t\t\t\t\t` at ${message.details.file}:${message.details.line}\\n` +\n\t\t\t\t\t\t\t\t\t\t(message.details.trace\n\t\t\t\t\t\t\t\t\t\t\t? message.details.trace + '\\n'\n\t\t\t\t\t\t\t\t\t\t\t: '')\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\toutput.stderr(\n\t\t\t\t\t\t\t\t\t`${red}${bold}Error:${reset} ${message.message}\\n`\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\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\t/**\n\t\t\t * When we're debugging, every bit of information matters – let's immediately output\n\t\t\t * everything we get from the PHP output streams.\n\t\t\t */\n\t\t\tif (args.verbosity === 'debug') {\n\t\t\t\tstreamedResponse!.stdout.pipeTo(\n\t\t\t\t\tnew WritableStream({\n\t\t\t\t\t\twrite(chunk) {\n\t\t\t\t\t\t\tprocess.stdout.write(chunk);\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t\tstreamedResponse!.stderr.pipeTo(\n\t\t\t\t\tnew WritableStream({\n\t\t\t\t\t\twrite(chunk) {\n\t\t\t\t\t\t\tprocess.stderr.write(chunk);\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\tawait streamedResponse!.finished;\n\t\t\tif ((await streamedResponse!.exitCode) !== 0) {\n\t\t\t\t// exitCode != 1 means the blueprint execution failed. Let's throw an error.\n\t\t\t\t// and clean up.\n\t\t\t\tconst syncResponse =\n\t\t\t\t\tawait PHPResponse.fromStreamedResponse(streamedResponse);\n\t\t\t\tthrow new PHPExecutionFailureError(\n\t\t\t\t\t`PHP.run() failed with exit code ${syncResponse.exitCode}. ${syncResponse.errors} ${syncResponse.text}`,\n\t\t\t\t\tsyncResponse,\n\t\t\t\t\t'request'\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Capture the PHP error log details to provide more context for debugging.\n\t\t\tlet phpLogs = '';\n\t\t\ttry {\n\t\t\t\t// @TODO: Don't assume errorLogPath starts with /wordpress/\n\t\t\t\t// ...or maybe we can assume that in Playground CLI?\n\t\t\t\tphpLogs = php.readFileAsText(errorLogPath);\n\t\t\t} catch {\n\t\t\t\t// Ignore errors reading the PHP error log.\n\t\t\t}\n\t\t\t(error as any).phpLogs = phpLogs;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\treap();\n\t\t\tunmountCwd();\n\t\t}\n\t}\n\n\tasync bootRequestHandler({\n\t\tsiteUrl,\n\t\tallow,\n\t\tphpVersion,\n\t\tcreateFiles,\n\t\tconstants,\n\t\tphpIniEntries,\n\t\tfirstProcessId,\n\t\tprocessIdSpaceLength,\n\t\ttrace,\n\t\tnativeInternalDirPath,\n\t\twithIntl,\n\t\twithXdebug,\n\t\tonPHPInstanceCreated,\n\t\tspawnHandler,\n\t}: WorkerBootRequestHandlerOptions) {\n\t\tif (this.booted) {\n\t\t\tthrow new Error('Playground already booted');\n\t\t}\n\t\tthis.booted = true;\n\n\t\tlet nextProcessId = firstProcessId;\n\t\tconst lastProcessId = firstProcessId + processIdSpaceLength - 1;\n\n\t\ttry {\n\t\t\tconst requestHandler = await bootRequestHandler({\n\t\t\t\tsiteUrl,\n\t\t\t\tcreatePhpRuntime: async () => {\n\t\t\t\t\tconst processId = nextProcessId;\n\n\t\t\t\t\tif (nextProcessId < lastProcessId) {\n\t\t\t\t\t\tnextProcessId++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// We've reached the end of the process ID space. Start over.\n\t\t\t\t\t\tnextProcessId = firstProcessId;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn await loadNodeRuntime(phpVersion, {\n\t\t\t\t\t\temscriptenOptions: {\n\t\t\t\t\t\t\tfileLockManager: this.fileLockManager!,\n\t\t\t\t\t\t\tprocessId,\n\t\t\t\t\t\t\ttrace: trace ? tracePhpWasm : undefined,\n\t\t\t\t\t\t\tENV: {\n\t\t\t\t\t\t\t\tDOCROOT: '/wordpress',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tphpWasmInitOptions: { nativeInternalDirPath },\n\t\t\t\t\t\t},\n\t\t\t\t\t\tfollowSymlinks: allow?.includes('follow-symlinks'),\n\t\t\t\t\t\twithIntl: withIntl,\n\t\t\t\t\t\twithXdebug,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tmaxPhpInstances: 1,\n\t\t\t\tonPHPInstanceCreated,\n\t\t\t\tsapiName: 'cli',\n\t\t\t\tcreateFiles,\n\t\t\t\tconstants,\n\t\t\t\tphpIniEntries,\n\t\t\t\tcookieStore: false,\n\t\t\t\tspawnHandler,\n\t\t\t});\n\t\t\tthis.__internal_setRequestHandler(requestHandler);\n\n\t\t\tconst primaryPhp = await requestHandler.getPrimaryPhp();\n\t\t\tawait this.setPrimaryPHP(primaryPhp);\n\n\t\t\tsetApiReady();\n\t\t} catch (e) {\n\t\t\tsetAPIError(e as Error);\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t// Provide a named disposal method that can be invoked via comlink.\n\tasync dispose() {\n\t\tawait this[Symbol.asyncDispose]();\n\t}\n}\n\n/**\n * Spawns a new PHP process to be used in the PHP spawn handler (in proc_open() etc. calls).\n * It boots from this worker-thread-v1.ts file, but is a separate process.\n *\n * We explicitly avoid using PHPProcessManager.acquirePHPInstance() here.\n *\n * Why?\n *\n * Because each PHP instance acquires actual OS-level file locks via fcntl() and LockFileEx()\n * syscalls. Running multiple PHP instances from the same OS process would allow them to\n * acquire overlapping locks. Running every PHP instance in a separate OS process ensures\n * any locks that overlap between PHP instances conflict with each other as expected.\n *\n * @param options - The options for the worker.\n * @param fileLockManager - The file lock manager to use.\n * @returns A promise that resolves to the PHP worker.\n */\nasync function createPHPWorker(\n\t{\n\t\tsiteUrl,\n\t\tallow,\n\t\tphpVersion,\n\t\tcreateFiles,\n\t\tconstants,\n\t\tphpIniEntries,\n\t\tfirstProcessId,\n\t\tprocessIdSpaceLength,\n\t\ttrace,\n\t\tnativeInternalDirPath,\n\t\twithXdebug,\n\t\tmountsBeforeWpInstall,\n\t\tmountsAfterWpInstall,\n\t}: SecondaryWorkerBootArgs,\n\tfileLockManager: FileLockManager | RemoteAPI<FileLockManager>\n) {\n\tconst spawnedWorker = await spawnWorkerThread('v2');\n\n\tconst handler = consumeAPI<PlaygroundCliBlueprintV2Worker>(\n\t\tspawnedWorker.phpPort\n\t);\n\thandler.useFileLockManager(fileLockManager as any);\n\tawait handler.bootWorker({\n\t\tsiteUrl,\n\t\tallow,\n\t\tphpVersion,\n\t\tcreateFiles,\n\t\tconstants,\n\t\tphpIniEntries,\n\t\tfirstProcessId,\n\t\tprocessIdSpaceLength,\n\t\ttrace,\n\t\tnativeInternalDirPath,\n\t\twithXdebug,\n\t\tmountsBeforeWpInstall,\n\t\tmountsAfterWpInstall,\n\t});\n\n\treturn {\n\t\tphp: handler,\n\t\treap: () => {\n\t\t\ttry {\n\t\t\t\thandler.dispose();\n\t\t\t} catch {\n\t\t\t\t/** */\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tspawnedWorker.worker.terminate();\n\t\t\t} catch {\n\t\t\t\t/** */\n\t\t\t}\n\t\t},\n\t};\n}\n\nprocess.on('unhandledRejection', (e: any) => {\n\tlogger.error('Unhandled rejection:', e);\n});\n\nconst phpChannel = new MessageChannel();\n\nconst [setApiReady, setAPIError] = exposeAPI(\n\tnew PlaygroundCliBlueprintV2Worker(new EmscriptenDownloadMonitor()),\n\tundefined,\n\tphpChannel.port1\n);\n\nparentPort?.postMessage(\n\t{\n\t\tcommand: 'worker-script-initialized',\n\t\tphpPort: phpChannel.port2,\n\t},\n\t[phpChannel.port2 as any]\n);\n"],"names":["mountResources","php","mounts","mount","createNodeFsMountHandler","output","tracePhpWasm","processId","format","args","sprintf","data","shouldRenderProgress","PlaygroundCliBlueprintV2Worker","PHPWorker","monitor","port","jspi","consumeAPI","consumeAPISync","constants","requestHandlerOptions","rootCertificates","sandboxedSpawnHandlerFactory","createPHPWorker","primaryPhp","requestHandler","reap","unmountCwd","blueprintPath","path","existsSync","cliArgs","arg","streamedResponse","runBlueprintV2","message","progressMessage","red","bold","reset","chunk","syncResponse","PHPResponse","PHPExecutionFailureError","error","phpLogs","errorLogPath","siteUrl","allow","phpVersion","createFiles","phpIniEntries","firstProcessId","processIdSpaceLength","trace","nativeInternalDirPath","withIntl","withXdebug","onPHPInstanceCreated","spawnHandler","nextProcessId","lastProcessId","bootRequestHandler","loadNodeRuntime","setApiReady","e","setAPIError","mountsBeforeWpInstall","mountsAfterWpInstall","fileLockManager","spawnedWorker","spawnWorkerThread","handler","logger","phpChannel","MessageChannel","exposeAPI","EmscriptenDownloadMonitor","parentPort"],"mappings":";;;;;;;;;;;;;AA4CA,eAAeA,EAAeC,GAAUC,GAAiB;AACxD,aAAWC,KAASD;AACnB,QAAI;AACH,MAAAD,EAAI,MAAME,EAAM,OAAO,GACvB,MAAMF,EAAI;AAAA,QACTE,EAAM;AAAA,QACNC,EAAyBD,EAAM,QAAQ;AAAA,MAAA;AAAA,IAEzC,QAAQ;AACP,MAAAE,EAAO;AAAA,QACN,sCAAsCF,EAAM,QAAQ,OAAOA,EAAM,OAAO;AAAA;AAAA,MAAA,GAEzE,QAAQ,KAAK,CAAC;AAAA,IACf;AAEF;AASA,SAASG,EAAaC,GAAmBC,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AAA,EACA,OAAAC;AAAA,EACA,uBAAAC;AAAA,EACA,YAAAE;AAAA,EACA,uBAAAU;AAAA,EACA,sBAAAC;AACD,GACAC,GACC;AACD,QAAMC,IAAgB,MAAMC,EAAkB,IAAI,GAE5CC,IAAUvD;AAAA,IACfqD,EAAc;AAAA,EAAA;AAEf,SAAAE,EAAQ,mBAAmBH,CAAsB,GACjD,MAAMG,EAAQ,WAAW;AAAA,IACxB,SAAAzB;AAAA,IACA,OAAAC;AAAA,IACA,YAAAC;AAAA,IACA,aAAAC;AAAA,IACA,WAAA/B;AAAA,IACA,eAAAgC;AAAA,IACA,gBAAAC;AAAA,IACA,sBAAAC;AAAA,IACA,OAAAC;AAAA,IACA,uBAAAC;AAAA,IACA,YAAAE;AAAA,IACA,uBAAAU;AAAA,IACA,sBAAAC;AAAA,EAAA,CACA,GAEM;AAAA,IACN,KAAKI;AAAA,IACL,MAAM,MAAM;AACX,UAAI;AACH,QAAAA,EAAQ,QAAA;AAAA,MACT,QAAQ;AAAA,MAER;AACA,UAAI;AACH,QAAAF,EAAc,OAAO,UAAA;AAAA,MACtB,QAAQ;AAAA,MAER;AAAA,IACD;AAAA,EAAA;AAEF;AAEA,QAAQ,GAAG,sBAAsB,CAACL,MAAW;AAC5C,EAAAQ,EAAO,MAAM,wBAAwBR,CAAC;AACvC,CAAC;AAED,MAAMS,IAAa,IAAIC,EAAA,GAEjB,CAACX,GAAaE,CAAW,IAAIU;AAAA,EAClC,IAAIhE,EAA+B,IAAIiE,GAA2B;AAAA,EAClE;AAAA,EACAH,EAAW;AACZ;AAEAI,GAAY;AAAA,EACX;AAAA,IACC,SAAS;AAAA,IACT,SAASJ,EAAW;AAAA,EAAA;AAAA,EAErB,CAACA,EAAW,KAAY;AACzB;"}
|
|
1
|
+
{"version":3,"file":"worker-thread-v2.js","sources":["../../../../packages/playground/cli/src/blueprints-v2/worker-thread-v2.ts"],"sourcesContent":["import { errorLogPath, logger } from '@php-wasm/logger';\nimport type { FileLockManager } from '@php-wasm/node';\nimport { createNodeFsMountHandler, loadNodeRuntime } from '@php-wasm/node';\nimport { EmscriptenDownloadMonitor } from '@php-wasm/progress';\nimport type {\n\tPHP,\n\tFileTree,\n\tRemoteAPI,\n\tSupportedPHPVersion,\n\tSpawnHandler,\n} from '@php-wasm/universal';\nimport {\n\tPHPExecutionFailureError,\n\tPHPResponse,\n\tPHPWorker,\n\tconsumeAPI,\n\tconsumeAPISync,\n\texposeAPI,\n\tsandboxedSpawnHandlerFactory,\n} from '@php-wasm/universal';\nimport { sprintf } from '@php-wasm/util';\nimport {\n\ttype BlueprintMessage,\n\trunBlueprintV2,\n\ttype BlueprintV1Declaration,\n} from '@wp-playground/blueprints';\nimport {\n\ttype ParsedBlueprintV2String,\n\ttype RawBlueprintV2Data,\n} from '@wp-playground/blueprints';\nimport { bootRequestHandler } from '@wp-playground/wordpress';\nimport { existsSync } from 'fs';\nimport path from 'path';\nimport { rootCertificates } from 'tls';\nimport { MessageChannel, type MessagePort, parentPort } from 'worker_threads';\nimport { jspi } from 'wasm-feature-detect';\nimport { spawnWorkerThread, type RunCLIArgs } from '../run-cli';\nimport type {\n\tPhpIniOptions,\n\tPHPInstanceCreatedHook,\n} from '@wp-playground/wordpress';\nimport { shouldRenderProgress } from '../utils/progress';\nimport type { Mount } from '@php-wasm/cli-util';\n\nasync function mountResources(php: PHP, mounts: Mount[]) {\n\tfor (const mount of mounts) {\n\t\ttry {\n\t\t\tphp.mkdir(mount.vfsPath);\n\t\t\tawait php.mount(\n\t\t\t\tmount.vfsPath,\n\t\t\t\tcreateNodeFsMountHandler(mount.hostPath)\n\t\t\t);\n\t\t} catch {\n\t\t\toutput.stderr(\n\t\t\t\t`\\x1b[31m\\x1b[1mError mounting path ${mount.hostPath} at ${mount.vfsPath}\\x1b[0m\\n`\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\t}\n}\n\n/**\n * Print trace messages from PHP-WASM.\n *\n * @param {number} processId - The process ID.\n * @param {string} format - The format string.\n * @param {...any} args - The arguments.\n */\nfunction tracePhpWasm(processId: number, format: string, ...args: any[]) {\n\t// eslint-disable-next-line no-console\n\tconsole.log(\n\t\tperformance.now().toFixed(6).padStart(15, '0'),\n\t\tprocessId.toString().padStart(16, '0'),\n\t\tsprintf(format, ...args)\n\t);\n}\n\n/**\n * Force TTY status to preserve ANSI control codes in the output\n * when the environment is interactive.\n *\n * This script is spawned as `new Worker()` and process.stdout and process.stderr are\n * WritableWorkerStdio objects. By default, they strip ANSI control codes from the output\n * causing every progress bar update to be printed in a new line instead of updating the\n * same line.\n */\nObject.defineProperty(process.stdout, 'isTTY', { value: true });\nObject.defineProperty(process.stderr, 'isTTY', { value: true });\n\n/**\n * Output writer that ensures that progress bars are not printed on the same line as other output.\n */\nconst output = {\n\tlastWriteWasProgress: false,\n\tprogress(data: string) {\n\t\tif (!shouldRenderProgress(process.stdout)) {\n\t\t\treturn;\n\t\t}\n\t\tif (!process.stdout.isTTY) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.log(data);\n\t\t} else {\n\t\t\tif (!output.lastWriteWasProgress) {\n\t\t\t\tprocess.stdout.write('\\n');\n\t\t\t}\n\t\t\tprocess.stdout.write('\\r\\x1b[K' + data);\n\t\t\toutput.lastWriteWasProgress = true;\n\t\t}\n\t},\n\tstdout(data: string) {\n\t\tprocess.stdout.write('\\n\\n\\n');\n\t\tif (output.lastWriteWasProgress) {\n\t\t\toutput.lastWriteWasProgress = false;\n\t\t}\n\t\tprocess.stdout.write(data);\n\t},\n\tstderr(data: string) {\n\t\tprocess.stdout.write('\\n\\n\\n');\n\t\tif (output.lastWriteWasProgress) {\n\t\t\toutput.lastWriteWasProgress = false;\n\t\t}\n\t\tprocess.stderr.write(data);\n\t},\n};\n\nexport type PrimaryWorkerBootArgs = Omit<\n\tRunCLIArgs,\n\t'mount-before-install' | 'mount'\n> & {\n\tphpVersion: SupportedPHPVersion;\n\tsiteUrl: string;\n\tfirstProcessId: number;\n\tprocessIdSpaceLength: number;\n\ttrace: boolean;\n\tblueprint:\n\t\t| RawBlueprintV2Data\n\t\t| ParsedBlueprintV2String\n\t\t| BlueprintV1Declaration;\n\tnativeInternalDirPath: string;\n\tmountsBeforeWpInstall?: Array<Mount>;\n\tmountsAfterWpInstall?: Array<Mount>;\n\t/**\n\t * PHP constants to define via php.defineConstant().\n\t * Process-specific, set for each PHP instance.\n\t */\n\tconstants?: Record<string, string | number | boolean | null>;\n};\n\ntype WorkerRunBlueprintArgs = Omit<\n\tRunCLIArgs,\n\t'mount-before-install' | 'mount'\n> & {\n\tsiteUrl: string;\n\tblueprint:\n\t\t| RawBlueprintV2Data\n\t\t| ParsedBlueprintV2String\n\t\t| BlueprintV1Declaration;\n\tmountsAfterWpInstall?: Array<Mount>;\n};\n\nexport type SecondaryWorkerBootArgs = {\n\tsiteUrl: string;\n\tallow?: string;\n\tphpVersion: SupportedPHPVersion;\n\tphpIniEntries?: PhpIniOptions;\n\tconstants?: Record<string, string | number | boolean | null>;\n\tcreateFiles?: FileTree;\n\tfirstProcessId: number;\n\tprocessIdSpaceLength: number;\n\ttrace: boolean;\n\tnativeInternalDirPath: string;\n\twithIntl?: boolean;\n\twithXdebug?: boolean;\n\tmountsBeforeWpInstall?: Array<Mount>;\n\tmountsAfterWpInstall?: Array<Mount>;\n};\n\nexport type WorkerBootRequestHandlerOptions = Omit<\n\tSecondaryWorkerBootArgs,\n\t'mountsBeforeWpInstall' | 'mountsAfterWpInstall'\n> & {\n\tonPHPInstanceCreated: PHPInstanceCreatedHook;\n\tspawnHandler: () => SpawnHandler;\n};\n\nexport class PlaygroundCliBlueprintV2Worker extends PHPWorker {\n\tbooted = false;\n\tblueprintTargetResolved = false;\n\tphpInstancesThatNeedMountsAfterTargetResolved = new Set<PHP>();\n\tfileLockManager: RemoteAPI<FileLockManager> | FileLockManager | undefined;\n\n\tconstructor(monitor: EmscriptenDownloadMonitor) {\n\t\tsuper(undefined, monitor);\n\t}\n\n\t/**\n\t * Call this method before boot() to use file locking.\n\t *\n\t * This method is separate from boot() to simplify the related Comlink.transferHandlers\n\t * setup – if an argument is a MessagePort, we're transferring it, not copying it.\n\t *\n\t * @see comlink-sync.ts\n\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t */\n\tasync useFileLockManager(port: MessagePort) {\n\t\tif (await jspi()) {\n\t\t\t/**\n\t\t\t * If JSPI is available, php.js supports both synchronous and asynchronous locking syscalls.\n\t\t\t * Web browsers, however, only support asynchronous message passing so let's use the\n\t\t\t * asynchronous API. Every method call will return a promise.\n\t\t\t *\n\t\t\t * @see comlink-sync.ts\n\t\t\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t\t\t */\n\t\t\tthis.fileLockManager = consumeAPI<FileLockManager>(port);\n\t\t} else {\n\t\t\t/**\n\t\t\t * If JSPI is not available, php.js only supports synchronous locking syscalls.\n\t\t\t * Let's use the synchronous API. Every method call will block this thread\n\t\t\t * until the result is available.\n\t\t\t *\n\t\t\t * @see comlink-sync.ts\n\t\t\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t\t\t */\n\t\t\tthis.fileLockManager = await consumeAPISync<FileLockManager>(port);\n\t\t}\n\t}\n\n\tasync bootAndSetUpInitialWorker(args: PrimaryWorkerBootArgs) {\n\t\t// Start with CLI-provided constants (if any)\n\t\tconst constants = {\n\t\t\t...(args.constants || {}),\n\t\t};\n\t\tconst requestHandlerOptions: WorkerBootRequestHandlerOptions = {\n\t\t\t...args,\n\t\t\tcreateFiles: {\n\t\t\t\t'/internal/shared/ca-bundle.crt': rootCertificates.join('\\n'),\n\t\t\t},\n\t\t\tconstants,\n\t\t\tphpIniEntries: {\n\t\t\t\t'openssl.cafile': '/internal/shared/ca-bundle.crt',\n\t\t\t},\n\t\t\tonPHPInstanceCreated: async (php: PHP) => {\n\t\t\t\tawait mountResources(php, args.mountsBeforeWpInstall || []);\n\t\t\t\tif (this.blueprintTargetResolved) {\n\t\t\t\t\tawait mountResources(php, args.mountsAfterWpInstall || []);\n\t\t\t\t} else {\n\t\t\t\t\t// NOTE: Today (2025-09-11), during boot with a plugin auto-mount,\n\t\t\t\t\t// the Blueprint runner fails unless post-resolution mounts are\n\t\t\t\t\t// added to existing PHP instances. So we track them here so they\n\t\t\t\t\t// can be mounted at the necessary time.\n\t\t\t\t\t// Only plugin auto-mounts seem to need this, so perhaps there\n\t\t\t\t\t// is a change we can make to the Blueprint runner so such\n\t\t\t\t\t// a dance is unnecessary.\n\t\t\t\t\tthis.phpInstancesThatNeedMountsAfterTargetResolved.add(php);\n\t\t\t\t\tphp.addEventListener('runtime.beforeExit', () => {\n\t\t\t\t\t\tthis.phpInstancesThatNeedMountsAfterTargetResolved.delete(\n\t\t\t\t\t\t\tphp\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\tspawnHandler: () =>\n\t\t\t\tsandboxedSpawnHandlerFactory(() =>\n\t\t\t\t\tcreatePHPWorker(args, this.fileLockManager!)\n\t\t\t\t),\n\t\t};\n\t\tawait this.bootRequestHandler(requestHandlerOptions);\n\n\t\tconst primaryPhp = this.__internal_getPHP()!;\n\n\t\tif (args.mode === 'mount-only') {\n\t\t\tawait mountResources(primaryPhp, args.mountsAfterWpInstall || []);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runBlueprintV2({\n\t\t\t...args,\n\t\t\tmountsAfterWpInstall: args.mountsAfterWpInstall || [],\n\t\t});\n\t}\n\n\tasync bootWorker(args: SecondaryWorkerBootArgs) {\n\t\tawait this.bootRequestHandler({\n\t\t\t...args,\n\t\t\tonPHPInstanceCreated: async (php: PHP) => {\n\t\t\t\tawait mountResources(php, args.mountsBeforeWpInstall || []);\n\t\t\t\tawait mountResources(php, args.mountsAfterWpInstall || []);\n\n\t\t\t\t// Temporary workaround for LOCK_EX in sqlite-database-integration.\n\t\t\t\t// Creation of these files results in this error:\n\t\t\t\t// PHP Warning: file_put_contents(): Exclusive locks are not supported for this stream\n\t\t\t\t// in\n\t\t\t\t// /wordpress/wp-content/plugins/sqlite-database-integration/wp-includes/sqlite/class-wp-sqlite-db.php\n\t\t\t\t// on line 670\n\t\t\t\tif (!php.isDir('/wordpress/wp-content')) {\n\t\t\t\t\tphp.mkdir('/wordpress/wp-content');\n\t\t\t\t}\n\t\t\t\tif (!php.isDir('/wordpress/wp-content/database')) {\n\t\t\t\t\tphp.mkdir('/wordpress/wp-content/database');\n\t\t\t\t}\n\t\t\t\tif (!php.isFile('/wordpress/wp-content/database/.htaccess')) {\n\t\t\t\t\tphp.writeFile(\n\t\t\t\t\t\t'/wordpress/wp-content/database/.htaccess',\n\t\t\t\t\t\t'deny from all'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (!php.isFile('/wordpress/wp-content/database/index.php')) {\n\t\t\t\t\tphp.writeFile(\n\t\t\t\t\t\t'/wordpress/wp-content/database/index.php',\n\t\t\t\t\t\t'deny from all'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t\tspawnHandler: () =>\n\t\t\t\tsandboxedSpawnHandlerFactory(() =>\n\t\t\t\t\tcreatePHPWorker(args, this.fileLockManager!)\n\t\t\t\t),\n\t\t});\n\t}\n\n\tasync runBlueprintV2(args: WorkerRunBlueprintArgs) {\n\t\tconst requestHandler = this.__internal_getRequestHandler()!;\n\t\tconst { php, reap } =\n\t\t\tawait requestHandler.instanceManager.acquirePHPInstance({\n\t\t\t\tconsiderPrimary: false,\n\t\t\t});\n\n\t\t// Mount the current working directory to the PHP runtime for the purposes of\n\t\t// Blueprint resolution.\n\t\tconst primaryPhp = this.__internal_getPHP()!;\n\t\tlet unmountCwd = () => {};\n\t\tif (typeof args.blueprint === 'string') {\n\t\t\tconst blueprintPath = path.resolve(process.cwd(), args.blueprint);\n\t\t\tif (existsSync(blueprintPath)) {\n\t\t\t\tprimaryPhp.mkdir('/internal/shared/cwd');\n\t\t\t\tunmountCwd = await primaryPhp.mount(\n\t\t\t\t\t'/internal/shared/cwd',\n\t\t\t\t\tcreateNodeFsMountHandler(path.dirname(blueprintPath))\n\t\t\t\t);\n\t\t\t\targs.blueprint = path.join(\n\t\t\t\t\t'/internal/shared/cwd',\n\t\t\t\t\tpath.basename(args.blueprint)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tconst cliArgsToPass: (keyof WorkerRunBlueprintArgs)[] = [\n\t\t\t\t'mode',\n\t\t\t\t'db-engine',\n\t\t\t\t'db-host',\n\t\t\t\t'db-user',\n\t\t\t\t'db-pass',\n\t\t\t\t'db-name',\n\t\t\t\t'db-path',\n\t\t\t\t'truncate-new-site-directory',\n\t\t\t\t'allow',\n\t\t\t];\n\t\t\tconst cliArgs = cliArgsToPass\n\t\t\t\t.filter((arg) => arg in args)\n\t\t\t\t.map((arg) => `--${arg}=${args[arg]}`);\n\t\t\tcliArgs.push(`--site-url=${args.siteUrl}`);\n\n\t\t\tconst streamedResponse = await runBlueprintV2({\n\t\t\t\tphp,\n\t\t\t\tblueprint: args.blueprint,\n\t\t\t\tblueprintOverrides: {\n\t\t\t\t\tadditionalSteps: args['additional-blueprint-steps'],\n\t\t\t\t\twordpressVersion: args.wp,\n\t\t\t\t},\n\t\t\t\tcliArgs,\n\t\t\t\tonMessage: async (message: BlueprintMessage) => {\n\t\t\t\t\tswitch (message.type) {\n\t\t\t\t\t\tcase 'blueprint.target_resolved': {\n\t\t\t\t\t\t\tif (!this.blueprintTargetResolved) {\n\t\t\t\t\t\t\t\tthis.blueprintTargetResolved = true;\n\t\t\t\t\t\t\t\tfor (const php of this\n\t\t\t\t\t\t\t\t\t.phpInstancesThatNeedMountsAfterTargetResolved) {\n\t\t\t\t\t\t\t\t\t// console.log('mounting resources for php', php);\n\t\t\t\t\t\t\t\t\tthis.phpInstancesThatNeedMountsAfterTargetResolved.delete(\n\t\t\t\t\t\t\t\t\t\tphp\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\tawait mountResources(\n\t\t\t\t\t\t\t\t\t\tphp,\n\t\t\t\t\t\t\t\t\t\targs.mountsAfterWpInstall || []\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'blueprint.progress': {\n\t\t\t\t\t\t\tconst progressMessage = `${message.caption.trim()} – ${message.progress.toFixed(\n\t\t\t\t\t\t\t\t2\n\t\t\t\t\t\t\t)}%`;\n\t\t\t\t\t\t\toutput.progress(progressMessage);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'blueprint.error': {\n\t\t\t\t\t\t\tconst red = '\\x1b[31m';\n\t\t\t\t\t\t\tconst bold = '\\x1b[1m';\n\t\t\t\t\t\t\tconst reset = '\\x1b[0m';\n\t\t\t\t\t\t\tif (args.verbosity === 'debug' && message.details) {\n\t\t\t\t\t\t\t\toutput.stderr(\n\t\t\t\t\t\t\t\t\t`${red}${bold}Fatal error:${reset} Uncaught ${message.details.exception}: ${message.details.message}\\n` +\n\t\t\t\t\t\t\t\t\t\t` at ${message.details.file}:${message.details.line}\\n` +\n\t\t\t\t\t\t\t\t\t\t(message.details.trace\n\t\t\t\t\t\t\t\t\t\t\t? message.details.trace + '\\n'\n\t\t\t\t\t\t\t\t\t\t\t: '')\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\toutput.stderr(\n\t\t\t\t\t\t\t\t\t`${red}${bold}Error:${reset} ${message.message}\\n`\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\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\t/**\n\t\t\t * When we're debugging, every bit of information matters – let's immediately output\n\t\t\t * everything we get from the PHP output streams.\n\t\t\t */\n\t\t\tif (args.verbosity === 'debug') {\n\t\t\t\tstreamedResponse!.stdout.pipeTo(\n\t\t\t\t\tnew WritableStream({\n\t\t\t\t\t\twrite(chunk) {\n\t\t\t\t\t\t\tprocess.stdout.write(chunk);\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t\tstreamedResponse!.stderr.pipeTo(\n\t\t\t\t\tnew WritableStream({\n\t\t\t\t\t\twrite(chunk) {\n\t\t\t\t\t\t\tprocess.stderr.write(chunk);\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\tawait streamedResponse!.finished;\n\t\t\tif ((await streamedResponse!.exitCode) !== 0) {\n\t\t\t\t// exitCode != 1 means the blueprint execution failed. Let's throw an error.\n\t\t\t\t// and clean up.\n\t\t\t\tconst syncResponse =\n\t\t\t\t\tawait PHPResponse.fromStreamedResponse(streamedResponse);\n\t\t\t\tthrow new PHPExecutionFailureError(\n\t\t\t\t\t`PHP.run() failed with exit code ${syncResponse.exitCode}. ${syncResponse.errors} ${syncResponse.text}`,\n\t\t\t\t\tsyncResponse,\n\t\t\t\t\t'request'\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Capture the PHP error log details to provide more context for debugging.\n\t\t\tlet phpLogs = '';\n\t\t\ttry {\n\t\t\t\t// @TODO: Don't assume errorLogPath starts with /wordpress/\n\t\t\t\t// ...or maybe we can assume that in Playground CLI?\n\t\t\t\tphpLogs = php.readFileAsText(errorLogPath);\n\t\t\t} catch {\n\t\t\t\t// Ignore errors reading the PHP error log.\n\t\t\t}\n\t\t\t(error as any).phpLogs = phpLogs;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\treap();\n\t\t\tunmountCwd();\n\t\t}\n\t}\n\n\tasync bootRequestHandler({\n\t\tsiteUrl,\n\t\tallow,\n\t\tphpVersion,\n\t\tcreateFiles,\n\t\tconstants,\n\t\tphpIniEntries,\n\t\tfirstProcessId,\n\t\tprocessIdSpaceLength,\n\t\ttrace,\n\t\tnativeInternalDirPath,\n\t\twithIntl,\n\t\twithXdebug,\n\t\tonPHPInstanceCreated,\n\t\tspawnHandler,\n\t}: WorkerBootRequestHandlerOptions) {\n\t\tif (this.booted) {\n\t\t\tthrow new Error('Playground already booted');\n\t\t}\n\t\tthis.booted = true;\n\n\t\tlet nextProcessId = firstProcessId;\n\t\tconst lastProcessId = firstProcessId + processIdSpaceLength - 1;\n\n\t\ttry {\n\t\t\tconst requestHandler = await bootRequestHandler({\n\t\t\t\tsiteUrl,\n\t\t\t\tcreatePhpRuntime: async () => {\n\t\t\t\t\tconst processId = nextProcessId;\n\n\t\t\t\t\tif (nextProcessId < lastProcessId) {\n\t\t\t\t\t\tnextProcessId++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// We've reached the end of the process ID space. Start over.\n\t\t\t\t\t\tnextProcessId = firstProcessId;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn await loadNodeRuntime(phpVersion, {\n\t\t\t\t\t\temscriptenOptions: {\n\t\t\t\t\t\t\tfileLockManager: this.fileLockManager!,\n\t\t\t\t\t\t\tprocessId,\n\t\t\t\t\t\t\ttrace: trace ? tracePhpWasm : undefined,\n\t\t\t\t\t\t\tENV: {\n\t\t\t\t\t\t\t\tDOCROOT: '/wordpress',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tphpWasmInitOptions: { nativeInternalDirPath },\n\t\t\t\t\t\t},\n\t\t\t\t\t\tfollowSymlinks: allow?.includes('follow-symlinks'),\n\t\t\t\t\t\twithIntl: withIntl,\n\t\t\t\t\t\twithXdebug,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tmaxPhpInstances: 1,\n\t\t\t\tonPHPInstanceCreated,\n\t\t\t\tsapiName: 'cli',\n\t\t\t\tcreateFiles,\n\t\t\t\tconstants,\n\t\t\t\tphpIniEntries,\n\t\t\t\tcookieStore: false,\n\t\t\t\tspawnHandler,\n\t\t\t});\n\t\t\tthis.__internal_setRequestHandler(requestHandler);\n\n\t\t\tconst primaryPhp = await requestHandler.getPrimaryPhp();\n\t\t\tawait this.setPrimaryPHP(primaryPhp);\n\n\t\t\tsetApiReady();\n\t\t} catch (e) {\n\t\t\tsetAPIError(e as Error);\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t// Provide a named disposal method that can be invoked via comlink.\n\tasync dispose() {\n\t\tawait this[Symbol.asyncDispose]();\n\t}\n}\n\n/**\n * Spawns a new PHP process to be used in the PHP spawn handler (in proc_open() etc. calls).\n * It boots from this worker-thread-v1.ts file, but is a separate process.\n *\n * We explicitly avoid using PHPProcessManager.acquirePHPInstance() here.\n *\n * Why?\n *\n * Because each PHP instance acquires actual OS-level file locks via fcntl() and LockFileEx()\n * syscalls. Running multiple PHP instances from the same OS process would allow them to\n * acquire overlapping locks. Running every PHP instance in a separate OS process ensures\n * any locks that overlap between PHP instances conflict with each other as expected.\n *\n * @param options - The options for the worker.\n * @param fileLockManager - The file lock manager to use.\n * @returns A promise that resolves to the PHP worker.\n */\nasync function createPHPWorker(\n\t{\n\t\tsiteUrl,\n\t\tallow,\n\t\tphpVersion,\n\t\tcreateFiles,\n\t\tconstants,\n\t\tphpIniEntries,\n\t\tfirstProcessId,\n\t\tprocessIdSpaceLength,\n\t\ttrace,\n\t\tnativeInternalDirPath,\n\t\twithXdebug,\n\t\tmountsBeforeWpInstall,\n\t\tmountsAfterWpInstall,\n\t}: SecondaryWorkerBootArgs,\n\tfileLockManager: FileLockManager | RemoteAPI<FileLockManager>\n) {\n\tconst spawnedWorker = await spawnWorkerThread('v2');\n\n\tconst handler = consumeAPI<PlaygroundCliBlueprintV2Worker>(\n\t\tspawnedWorker.phpPort\n\t);\n\thandler.useFileLockManager(fileLockManager as any);\n\tawait handler.bootWorker({\n\t\tsiteUrl,\n\t\tallow,\n\t\tphpVersion,\n\t\tcreateFiles,\n\t\tconstants,\n\t\tphpIniEntries,\n\t\tfirstProcessId,\n\t\tprocessIdSpaceLength,\n\t\ttrace,\n\t\tnativeInternalDirPath,\n\t\twithXdebug,\n\t\tmountsBeforeWpInstall,\n\t\tmountsAfterWpInstall,\n\t});\n\n\treturn {\n\t\tphp: handler,\n\t\treap: () => {\n\t\t\ttry {\n\t\t\t\thandler.dispose();\n\t\t\t} catch {\n\t\t\t\t/** */\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tspawnedWorker.worker.terminate();\n\t\t\t} catch {\n\t\t\t\t/** */\n\t\t\t}\n\t\t},\n\t};\n}\n\nprocess.on('unhandledRejection', (e: any) => {\n\tlogger.error('Unhandled rejection:', e);\n});\n\nconst phpChannel = new MessageChannel();\n\nconst [setApiReady, setAPIError] = exposeAPI(\n\tnew PlaygroundCliBlueprintV2Worker(new EmscriptenDownloadMonitor()),\n\tundefined,\n\tphpChannel.port1\n);\n\nparentPort?.postMessage(\n\t{\n\t\tcommand: 'worker-script-initialized',\n\t\tphpPort: phpChannel.port2,\n\t},\n\t[phpChannel.port2 as any]\n);\n"],"names":["mountResources","php","mounts","mount","createNodeFsMountHandler","output","tracePhpWasm","processId","format","args","sprintf","data","shouldRenderProgress","PlaygroundCliBlueprintV2Worker","PHPWorker","monitor","port","jspi","consumeAPI","consumeAPISync","constants","requestHandlerOptions","rootCertificates","sandboxedSpawnHandlerFactory","createPHPWorker","primaryPhp","requestHandler","reap","unmountCwd","blueprintPath","path","existsSync","cliArgs","arg","streamedResponse","runBlueprintV2","message","progressMessage","red","bold","reset","chunk","syncResponse","PHPResponse","PHPExecutionFailureError","error","phpLogs","errorLogPath","siteUrl","allow","phpVersion","createFiles","phpIniEntries","firstProcessId","processIdSpaceLength","trace","nativeInternalDirPath","withIntl","withXdebug","onPHPInstanceCreated","spawnHandler","nextProcessId","lastProcessId","bootRequestHandler","loadNodeRuntime","setApiReady","e","setAPIError","mountsBeforeWpInstall","mountsAfterWpInstall","fileLockManager","spawnedWorker","spawnWorkerThread","handler","logger","phpChannel","MessageChannel","exposeAPI","EmscriptenDownloadMonitor","parentPort"],"mappings":";;;;;;;;;;;;;AA4CA,eAAeA,EAAeC,GAAUC,GAAiB;AACxD,aAAWC,KA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B;AAAA,EAClE;AAAA,EACAH,EAAW;AACZ;AAEAI,GAAY;AAAA,EACX;AAAA,IACC,SAAS;AAAA,IACT,SAASJ,EAAW;AAAA,EAAA;AAAA,EAErB,CAACA,EAAW,KAAY;AACzB;"}
|
package/run-cli-B8Dv6R-o.cjs
DELETED
|
@@ -1,64 +0,0 @@
|
|
|
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
|