@wp-playground/cli 3.0.2 → 3.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/blueprints-v1/blueprints-v1-handler.d.ts +1 -0
- package/cli.cjs +1 -1
- package/cli.js +1 -1
- package/index.cjs +1 -1
- package/index.js +1 -1
- package/package.json +12 -12
- package/{run-cli-B2OOyNez.cjs → run-cli-DdsLZ1X6.cjs} +8 -8
- package/run-cli-DdsLZ1X6.cjs.map +1 -0
- package/{run-cli-8MDZfFdj.js → run-cli-Md2TQOSk.js} +168 -164
- package/run-cli-Md2TQOSk.js.map +1 -0
- package/worker-thread-v1.cjs +2 -2
- package/worker-thread-v1.cjs.map +1 -1
- package/worker-thread-v1.js +36 -36
- package/worker-thread-v1.js.map +1 -1
- package/worker-thread-v2.cjs +2 -2
- package/worker-thread-v2.cjs.map +1 -1
- package/worker-thread-v2.js +13 -13
- package/worker-thread-v2.js.map +1 -1
- package/run-cli-8MDZfFdj.js.map +0 -1
- package/run-cli-B2OOyNez.cjs.map +0 -1
package/worker-thread-v2.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-thread-v2.cjs","sources":["../../../../packages/playground/cli/src/blueprints-v2/worker-thread-v2.ts"],"sourcesContent":["import { errorLogPath } 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} 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 type { Mount } from '../mounts';\nimport { jspi } from 'wasm-feature-detect';\nimport { type RunCLIArgs } from '../run-cli';\nimport type {\n\tPhpIniOptions,\n\tPHPInstanceCreatedHook,\n} from '@wp-playground/wordpress';\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 *\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 (!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\tif (output.lastWriteWasProgress) {\n\t\t\tprocess.stdout.write('\\n');\n\t\t\toutput.lastWriteWasProgress = false;\n\t\t}\n\t\tprocess.stdout.write(data);\n\t},\n\tstderr(data: string) {\n\t\tif (output.lastWriteWasProgress) {\n\t\t\tprocess.stdout.write('\\n');\n\t\t\toutput.lastWriteWasProgress = false;\n\t\t}\n\t\tprocess.stderr.write(data);\n\t},\n};\n\nexport type PrimaryWorkerBootArgs = RunCLIArgs & {\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};\n\ntype WorkerRunBlueprintArgs = RunCLIArgs & {\n\tsiteUrl: string;\n\tblueprint:\n\t\t| RawBlueprintV2Data\n\t\t| ParsedBlueprintV2String\n\t\t| BlueprintV1Declaration;\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\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};\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 bootAsPrimaryWorker(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['mount-before-install'] || []);\n\t\t\t\tif (this.blueprintTargetResolved) {\n\t\t\t\t\tawait mountResources(php, args.mount || []);\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};\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.mount || []);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runBlueprintV2(args);\n\t}\n\n\tasync bootAsSecondaryWorker(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\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.processManager.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(php, args.mount || []);\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.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.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 = await PHPResponse.fromStreamedResponse(\n\t\t\t\t\tstreamedResponse\n\t\t\t\t);\n\t\t\t\tthrow new PHPExecutionFailureError(\n\t\t\t\t\t`PHP.run() failed with exit code ${syncResponse.exitCode}.`,\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\twithXdebug,\n\t\tonPHPInstanceCreated,\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\twithXdebug,\n\t\t\t\t\t});\n\t\t\t\t},\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: sandboxedSpawnHandlerFactory,\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\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","PlaygroundCliBlueprintV2Worker","PHPWorker","monitor","port","jspi","consumeAPI","consumeAPISync","constants","requestHandlerOptions","rootCertificates","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","withXdebug","onPHPInstanceCreated","nextProcessId","lastProcessId","bootRequestHandler","loadNodeRuntime","sandboxedSpawnHandlerFactory","setApiReady","e","setAPIError","phpChannel","MessageChannel","exposeAPI","EmscriptenDownloadMonitor","parentPort"],"mappings":"0aA0CA,eAAeA,EAAeC,EAAUC,EAAiB,CACxD,UAAWC,KAASD,EACf,GAAA,CACCD,EAAA,MAAME,EAAM,OAAO,EACvB,MAAMF,EAAI,MACTE,EAAM,QACNC,EAAA,yBAAyBD,EAAM,QAAQ,CACxC,CAAA,MACO,CACAE,EAAA,OACN,sCAAsCF,EAAM,QAAQ,OAAOA,EAAM,OAAO;AAAA,CACzE,EACA,QAAQ,KAAK,CAAC,CAAA,CAGjB,CASA,SAASG,EAAaC,EAAmBC,KAAmBC,EAAa,CAEhE,QAAA,IACP,YAAY,MAAM,QAAQ,CAAC,EAAE,SAAS,GAAI,GAAG,EAC7CF,EAAU,SAAW,EAAA,SAAS,GAAI,GAAG,EACrCG,EAAA,QAAQF,EAAQ,GAAGC,CAAI,CACxB,CACD,CAUA,OAAO,eAAe,QAAQ,OAAQ,QAAS,CAAE,MAAO,GAAM,EAC9D,OAAO,eAAe,QAAQ,OAAQ,QAAS,CAAE,MAAO,GAAM,EAK9D,MAAMJ,EAAS,CACd,qBAAsB,GACtB,SAASM,EAAc,CACjB,QAAQ,OAAO,OAIdN,EAAO,sBACH,QAAA,OAAO,MAAM;AAAA,CAAI,EAElB,QAAA,OAAO,MAAM,WAAaM,CAAI,EACtCN,EAAO,qBAAuB,IAN9B,QAAQ,IAAIM,CAAI,CAQlB,EACA,OAAOA,EAAc,CAChBN,EAAO,uBACF,QAAA,OAAO,MAAM;AAAA,CAAI,EACzBA,EAAO,qBAAuB,IAEvB,QAAA,OAAO,MAAMM,CAAI,CAC1B,EACA,OAAOA,EAAc,CAChBN,EAAO,uBACF,QAAA,OAAO,MAAM;AAAA,CAAI,EACzBA,EAAO,qBAAuB,IAEv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4BACT,QAASJ,EAAW,KACrB,EACA,CAACA,EAAW,KAAY,CACzB"}
|
|
1
|
+
{"version":3,"file":"worker-thread-v2.cjs","sources":["../../../../packages/playground/cli/src/blueprints-v2/worker-thread-v2.ts"],"sourcesContent":["import { errorLogPath } 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} 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 type { Mount } from '../mounts';\nimport { jspi } from 'wasm-feature-detect';\nimport { type RunCLIArgs } from '../run-cli';\nimport type {\n\tPhpIniOptions,\n\tPHPInstanceCreatedHook,\n} from '@wp-playground/wordpress';\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 *\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 (!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\tif (output.lastWriteWasProgress) {\n\t\t\tprocess.stdout.write('\\n');\n\t\t\toutput.lastWriteWasProgress = false;\n\t\t}\n\t\tprocess.stdout.write(data);\n\t},\n\tstderr(data: string) {\n\t\tif (output.lastWriteWasProgress) {\n\t\t\tprocess.stdout.write('\\n');\n\t\t\toutput.lastWriteWasProgress = false;\n\t\t}\n\t\tprocess.stderr.write(data);\n\t},\n};\n\nexport type PrimaryWorkerBootArgs = RunCLIArgs & {\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};\n\ntype WorkerRunBlueprintArgs = RunCLIArgs & {\n\tsiteUrl: string;\n\tblueprint:\n\t\t| RawBlueprintV2Data\n\t\t| ParsedBlueprintV2String\n\t\t| BlueprintV1Declaration;\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\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};\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 bootAsPrimaryWorker(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\tthis.registerWorkerListeners(php);\n\t\t\t\tawait mountResources(php, args['mount-before-install'] || []);\n\t\t\t\tif (this.blueprintTargetResolved) {\n\t\t\t\t\tawait mountResources(php, args.mount || []);\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};\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.mount || []);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runBlueprintV2(args);\n\t}\n\n\tasync bootAsSecondaryWorker(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\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.processManager.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(php, args.mount || []);\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.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.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 = await PHPResponse.fromStreamedResponse(\n\t\t\t\t\tstreamedResponse\n\t\t\t\t);\n\t\t\t\tthrow new PHPExecutionFailureError(\n\t\t\t\t\t`PHP.run() failed with exit code ${syncResponse.exitCode}.`,\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\twithXdebug,\n\t\tonPHPInstanceCreated,\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\twithXdebug,\n\t\t\t\t\t});\n\t\t\t\t},\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: sandboxedSpawnHandlerFactory,\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\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","PlaygroundCliBlueprintV2Worker","PHPWorker","monitor","port","jspi","consumeAPI","consumeAPISync","constants","requestHandlerOptions","rootCertificates","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","withXdebug","onPHPInstanceCreated","nextProcessId","lastProcessId","bootRequestHandler","loadNodeRuntime","sandboxedSpawnHandlerFactory","setApiReady","e","setAPIError","phpChannel","MessageChannel","exposeAPI","EmscriptenDownloadMonitor","parentPort"],"mappings":"0aA0CA,eAAeA,EAAeC,EAAUC,EAAiB,CACxD,UAAWC,KAASD,EACf,GAAA,CACCD,EAAA,MAAME,EAAM,OAAO,EACvB,MAAMF,EAAI,MACTE,EAAM,QACNC,EAAA,yBAAyBD,EAAM,QAAQ,CACxC,CAAA,MACO,CACAE,EAAA,OACN,sCAAsCF,EAAM,QAAQ,OAAOA,EAAM,OAAO;AAAA,CACzE,EACA,QAAQ,KAAK,CAAC,CAAA,CAGjB,CASA,SAASG,EAAaC,EAAmBC,KAAmBC,EAAa,CAEhE,QAAA,IACP,YAAY,MAAM,QAAQ,CAAC,EAAE,SAAS,GAAI,GAAG,EAC7CF,EAAU,SAAW,EAAA,SAAS,GAAI,GAAG,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AS,YACV,EACA,mBAAoB,CAAE,sBAAA+C,CAAsB,CAC7C,EACA,eAAgBP,GAAO,SAAS,iBAAiB,EACjD,WAAAQ,CAAA,CACA,CACF,EACA,qBAAAC,EACA,SAAU,MACV,YAAAP,EACA,UAAA7B,EACA,cAAA8B,EACA,YAAa,GACb,aAAcW,EAAAA,4BAAA,CACd,EACD,KAAK,6BAA6BrC,CAAc,EAE1C,MAAAD,EAAa,MAAMC,EAAe,cAAc,EAChD,MAAA,KAAK,cAAcD,CAAU,EAEvBuC,EAAA,QACJC,EAAG,CACX,MAAAC,EAAYD,CAAU,EAChBA,CAAA,CACP,CAID,MAAM,SAAU,CACT,MAAA,KAAK,OAAO,YAAY,EAAE,CAAA,CAElC,CAEA,MAAME,EAAa,IAAIC,EAAAA,eAEjB,CAACJ,EAAaE,CAAW,EAAIG,EAAA,UAClC,IAAItD,EAA+B,IAAIuD,EAAAA,yBAA2B,EAClE,OACAH,EAAW,KACZ,EAEAI,EAAAA,YAAY,YACX,CACC,QAAS,4BACT,QAASJ,EAAW,KACrB,EACA,CAACA,EAAW,KAAY,CACzB"}
|
package/worker-thread-v2.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { errorLogPath as R } from "@php-wasm/logger";
|
|
2
2
|
import { createNodeFsMountHandler as y, loadNodeRuntime as x } from "@php-wasm/node";
|
|
3
3
|
import { EmscriptenDownloadMonitor as H } from "@php-wasm/progress";
|
|
4
|
-
import { exposeAPI as v, PHPWorker as
|
|
4
|
+
import { exposeAPI as v, PHPWorker as k, consumeAPI as $, consumeAPISync as A, PHPResponse as I, PHPExecutionFailureError as _, sandboxedSpawnHandlerFactory as M } from "@php-wasm/universal";
|
|
5
5
|
import { sprintf as S } from "@php-wasm/util";
|
|
6
6
|
import { runBlueprintV2 as B } from "@wp-playground/blueprints";
|
|
7
7
|
import { bootRequestHandler as E } from "@wp-playground/wordpress";
|
|
8
|
-
import { existsSync as
|
|
8
|
+
import { existsSync as L } from "fs";
|
|
9
9
|
import P from "path";
|
|
10
|
-
import { rootCertificates as
|
|
10
|
+
import { rootCertificates as q } from "tls";
|
|
11
11
|
import { MessageChannel as C, parentPort as O } from "worker_threads";
|
|
12
12
|
import { jspi as F } from "wasm-feature-detect";
|
|
13
13
|
async function u(s, e) {
|
|
@@ -48,7 +48,7 @@ const i = {
|
|
|
48
48
|
`), i.lastWriteWasProgress = !1), process.stderr.write(s);
|
|
49
49
|
}
|
|
50
50
|
};
|
|
51
|
-
class D extends
|
|
51
|
+
class D extends k {
|
|
52
52
|
constructor(e) {
|
|
53
53
|
super(void 0, e), this.booted = !1, this.blueprintTargetResolved = !1, this.phpInstancesThatNeedMountsAfterTargetResolved = /* @__PURE__ */ new Set();
|
|
54
54
|
}
|
|
@@ -62,7 +62,7 @@ class D extends $ {
|
|
|
62
62
|
* @see phpwasm-emscripten-library-file-locking-for-node.js
|
|
63
63
|
*/
|
|
64
64
|
async useFileLockManager(e) {
|
|
65
|
-
await F() ? this.fileLockManager =
|
|
65
|
+
await F() ? this.fileLockManager = $(e) : this.fileLockManager = await A(e);
|
|
66
66
|
}
|
|
67
67
|
async bootAsPrimaryWorker(e) {
|
|
68
68
|
const r = {
|
|
@@ -72,7 +72,7 @@ class D extends $ {
|
|
|
72
72
|
}, p = {
|
|
73
73
|
...e,
|
|
74
74
|
createFiles: {
|
|
75
|
-
"/internal/shared/ca-bundle.crt":
|
|
75
|
+
"/internal/shared/ca-bundle.crt": q.join(`
|
|
76
76
|
`)
|
|
77
77
|
},
|
|
78
78
|
constants: r,
|
|
@@ -80,7 +80,7 @@ class D extends $ {
|
|
|
80
80
|
"openssl.cafile": "/internal/shared/ca-bundle.crt"
|
|
81
81
|
},
|
|
82
82
|
onPHPInstanceCreated: async (o) => {
|
|
83
|
-
await u(o, e["mount-before-install"] || []), this.blueprintTargetResolved ? await u(o, e.mount || []) : (this.phpInstancesThatNeedMountsAfterTargetResolved.add(o), o.addEventListener("runtime.beforeExit", () => {
|
|
83
|
+
this.registerWorkerListeners(o), await u(o, e["mount-before-install"] || []), this.blueprintTargetResolved ? await u(o, e.mount || []) : (this.phpInstancesThatNeedMountsAfterTargetResolved.add(o), o.addEventListener("runtime.beforeExit", () => {
|
|
84
84
|
this.phpInstancesThatNeedMountsAfterTargetResolved.delete(
|
|
85
85
|
o
|
|
86
86
|
);
|
|
@@ -111,7 +111,7 @@ class D extends $ {
|
|
|
111
111
|
};
|
|
112
112
|
if (typeof e.blueprint == "string") {
|
|
113
113
|
const n = P.resolve(process.cwd(), e.blueprint);
|
|
114
|
-
|
|
114
|
+
L(n) && (o.mkdir("/internal/shared/cwd"), f = await o.mount(
|
|
115
115
|
"/internal/shared/cwd",
|
|
116
116
|
y(P.dirname(n))
|
|
117
117
|
), e.blueprint = P.join(
|
|
@@ -231,11 +231,11 @@ class D extends $ {
|
|
|
231
231
|
const m = await E({
|
|
232
232
|
siteUrl: e,
|
|
233
233
|
createPhpRuntime: async () => {
|
|
234
|
-
const
|
|
234
|
+
const T = c;
|
|
235
235
|
return c < W ? c++ : c = n, await x(p, {
|
|
236
236
|
emscriptenOptions: {
|
|
237
237
|
fileLockManager: this.fileLockManager,
|
|
238
|
-
processId:
|
|
238
|
+
processId: T,
|
|
239
239
|
trace: d ? N : void 0,
|
|
240
240
|
ENV: {
|
|
241
241
|
DOCROOT: "/wordpress"
|
|
@@ -255,8 +255,8 @@ class D extends $ {
|
|
|
255
255
|
spawnHandler: M
|
|
256
256
|
});
|
|
257
257
|
this.__internal_setRequestHandler(m);
|
|
258
|
-
const
|
|
259
|
-
await this.setPrimaryPHP(
|
|
258
|
+
const g = await m.getPrimaryPhp();
|
|
259
|
+
await this.setPrimaryPHP(g), V();
|
|
260
260
|
} catch (m) {
|
|
261
261
|
throw j(m), m;
|
|
262
262
|
}
|
|
@@ -271,7 +271,7 @@ const b = new C(), [V, j] = v(
|
|
|
271
271
|
void 0,
|
|
272
272
|
b.port1
|
|
273
273
|
);
|
|
274
|
-
O
|
|
274
|
+
O?.postMessage(
|
|
275
275
|
{
|
|
276
276
|
command: "worker-script-initialized",
|
|
277
277
|
phpPort: b.port2
|
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 } 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} 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 type { Mount } from '../mounts';\nimport { jspi } from 'wasm-feature-detect';\nimport { type RunCLIArgs } from '../run-cli';\nimport type {\n\tPhpIniOptions,\n\tPHPInstanceCreatedHook,\n} from '@wp-playground/wordpress';\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 *\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 (!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\tif (output.lastWriteWasProgress) {\n\t\t\tprocess.stdout.write('\\n');\n\t\t\toutput.lastWriteWasProgress = false;\n\t\t}\n\t\tprocess.stdout.write(data);\n\t},\n\tstderr(data: string) {\n\t\tif (output.lastWriteWasProgress) {\n\t\t\tprocess.stdout.write('\\n');\n\t\t\toutput.lastWriteWasProgress = false;\n\t\t}\n\t\tprocess.stderr.write(data);\n\t},\n};\n\nexport type PrimaryWorkerBootArgs = RunCLIArgs & {\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};\n\ntype WorkerRunBlueprintArgs = RunCLIArgs & {\n\tsiteUrl: string;\n\tblueprint:\n\t\t| RawBlueprintV2Data\n\t\t| ParsedBlueprintV2String\n\t\t| BlueprintV1Declaration;\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\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};\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 bootAsPrimaryWorker(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['mount-before-install'] || []);\n\t\t\t\tif (this.blueprintTargetResolved) {\n\t\t\t\t\tawait mountResources(php, args.mount || []);\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};\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.mount || []);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runBlueprintV2(args);\n\t}\n\n\tasync bootAsSecondaryWorker(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\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.processManager.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(php, args.mount || []);\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.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.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 = await PHPResponse.fromStreamedResponse(\n\t\t\t\t\tstreamedResponse\n\t\t\t\t);\n\t\t\t\tthrow new PHPExecutionFailureError(\n\t\t\t\t\t`PHP.run() failed with exit code ${syncResponse.exitCode}.`,\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\twithXdebug,\n\t\tonPHPInstanceCreated,\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\twithXdebug,\n\t\t\t\t\t});\n\t\t\t\t},\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: sandboxedSpawnHandlerFactory,\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\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","PlaygroundCliBlueprintV2Worker","PHPWorker","monitor","port","jspi","consumeAPI","consumeAPISync","constants","requestHandlerOptions","rootCertificates","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","withXdebug","onPHPInstanceCreated","nextProcessId","lastProcessId","bootRequestHandler","loadNodeRuntime","sandboxedSpawnHandlerFactory","setApiReady","e","setAPIError","phpChannel","MessageChannel","exposeAPI","EmscriptenDownloadMonitor","parentPort"],"mappings":";;;;;;;;;;;;AA0CA,eAAeA,EAAeC,GAAUC,GAAiB;AACxD,aAAWC,KAASD;AACf,QAAA;AACC,MAAAD,EAAA,MAAME,EAAM,OAAO,GACvB,MAAMF,EAAI;AAAA,QACTE,EAAM;AAAA,QACNC,EAAyBD,EAAM,QAAQ;AAAA,MACxC;AAAA,IAAA,QACO;AACA,MAAAE,EAAA;AAAA,QACN,sCAAsCF,EAAM,QAAQ,OAAOA,EAAM,OAAO;AAAA;AAAA,MACzE,GACA,QAAQ,KAAK,CAAC;AAAA,IAAA;AAGjB;AASA,SAASG,EAAaC,GAAmBC,MAAmBC,GAAa;AAEhE,UAAA;AAAA,IACP,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ACb,cAAcW;AAAA,MAAA,CACd;AACD,WAAK,6BAA6BrC,CAAc;AAE1C,YAAAD,IAAa,MAAMC,EAAe,cAAc;AAChD,YAAA,KAAK,cAAcD,CAAU,GAEvBuC,EAAA;AAAA,aACJC,GAAG;AACX,YAAAC,EAAYD,CAAU,GAChBA;AAAA,IAAA;AAAA,EACP;AAAA;AAAA,EAID,MAAM,UAAU;AACT,UAAA,KAAK,OAAO,YAAY,EAAE;AAAA,EAAA;AAElC;AAEA,MAAME,IAAa,IAAIC,EAAe,GAEhC,CAACJ,GAAaE,CAAW,IAAIG;AAAA,EAClC,IAAItD,EAA+B,IAAIuD,GAA2B;AAAA,EAClE;AAAA,EACAH,EAAW;AACZ;AAEAI,EAAY;AAAA,EACX;AAAA,IACC,SAAS;AAAA,IACT,SAASJ,EAAW;AAAA,EACrB;AAAA,EACA,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 } 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} 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 type { Mount } from '../mounts';\nimport { jspi } from 'wasm-feature-detect';\nimport { type RunCLIArgs } from '../run-cli';\nimport type {\n\tPhpIniOptions,\n\tPHPInstanceCreatedHook,\n} from '@wp-playground/wordpress';\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 *\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 (!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\tif (output.lastWriteWasProgress) {\n\t\t\tprocess.stdout.write('\\n');\n\t\t\toutput.lastWriteWasProgress = false;\n\t\t}\n\t\tprocess.stdout.write(data);\n\t},\n\tstderr(data: string) {\n\t\tif (output.lastWriteWasProgress) {\n\t\t\tprocess.stdout.write('\\n');\n\t\t\toutput.lastWriteWasProgress = false;\n\t\t}\n\t\tprocess.stderr.write(data);\n\t},\n};\n\nexport type PrimaryWorkerBootArgs = RunCLIArgs & {\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};\n\ntype WorkerRunBlueprintArgs = RunCLIArgs & {\n\tsiteUrl: string;\n\tblueprint:\n\t\t| RawBlueprintV2Data\n\t\t| ParsedBlueprintV2String\n\t\t| BlueprintV1Declaration;\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\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};\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 bootAsPrimaryWorker(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\tthis.registerWorkerListeners(php);\n\t\t\t\tawait mountResources(php, args['mount-before-install'] || []);\n\t\t\t\tif (this.blueprintTargetResolved) {\n\t\t\t\t\tawait mountResources(php, args.mount || []);\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};\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.mount || []);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runBlueprintV2(args);\n\t}\n\n\tasync bootAsSecondaryWorker(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\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.processManager.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(php, args.mount || []);\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.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.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 = await PHPResponse.fromStreamedResponse(\n\t\t\t\t\tstreamedResponse\n\t\t\t\t);\n\t\t\t\tthrow new PHPExecutionFailureError(\n\t\t\t\t\t`PHP.run() failed with exit code ${syncResponse.exitCode}.`,\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\twithXdebug,\n\t\tonPHPInstanceCreated,\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\twithXdebug,\n\t\t\t\t\t});\n\t\t\t\t},\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: sandboxedSpawnHandlerFactory,\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\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","PlaygroundCliBlueprintV2Worker","PHPWorker","monitor","port","jspi","consumeAPI","consumeAPISync","constants","requestHandlerOptions","rootCertificates","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","withXdebug","onPHPInstanceCreated","nextProcessId","lastProcessId","bootRequestHandler","loadNodeRuntime","sandboxedSpawnHandlerFactory","setApiReady","e","setAPIError","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,IAAYiD;AAElB,iBAAIA,IAAgBC,IACnBD,MAGgBA,IAAAN,GAGV,MAAMS,EAAgBZ,GAAY;AAAA,YACxC,mBAAmB;AAAA,cAClB,iBAAiB,KAAK;AAAA,cACtB,WAAAxC;AAAA,cACA,OAAO6C,IAAQ9C,IAAe;AAAA,cAC9B,KAAK;AAAA,gBACJ,SAAS;AAAA,cACV;AAAA,cACA,oBAAoB,EAAE,uBAAA+C,EAAsB;AAAA,YAC7C;AAAA,YACA,gBAAgBP,GAAO,SAAS,iBAAiB;AAAA,YACjD,YAAAQ;AAAA,UAAA,CACA;AAAA,QACF;AAAA,QACA,sBAAAC;AAAA,QACA,UAAU;AAAA,QACV,aAAAP;AAAA,QACA,WAAA7B;AAAA,QACA,eAAA8B;AAAA,QACA,aAAa;AAAA,QACb,cAAcW;AAAA,MAAA,CACd;AACD,WAAK,6BAA6BrC,CAAc;AAE1C,YAAAD,IAAa,MAAMC,EAAe,cAAc;AAChD,YAAA,KAAK,cAAcD,CAAU,GAEvBuC,EAAA;AAAA,aACJC,GAAG;AACX,YAAAC,EAAYD,CAAU,GAChBA;AAAA,IAAA;AAAA,EACP;AAAA;AAAA,EAID,MAAM,UAAU;AACT,UAAA,KAAK,OAAO,YAAY,EAAE;AAAA,EAAA;AAElC;AAEA,MAAME,IAAa,IAAIC,EAAe,GAEhC,CAACJ,GAAaE,CAAW,IAAIG;AAAA,EAClC,IAAItD,EAA+B,IAAIuD,GAA2B;AAAA,EAClE;AAAA,EACAH,EAAW;AACZ;AAEAI,GAAY;AAAA,EACX;AAAA,IACC,SAAS;AAAA,IACT,SAASJ,EAAW;AAAA,EACrB;AAAA,EACA,CAACA,EAAW,KAAY;AACzB;"}
|
package/run-cli-8MDZfFdj.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-cli-8MDZfFdj.js","sources":["../../../../packages/playground/cli/src/start-server.ts","../../../../packages/playground/cli/src/load-balancer.ts","../../../../packages/playground/cli/src/is-valid-wordpress-slug.ts","../../../../packages/playground/cli/src/resolve-blueprint.ts","../../../../packages/playground/cli/src/blueprints-v2/blueprints-v2-handler.ts","../../../../packages/playground/cli/src/blueprints-v1/download.ts","../../../../packages/playground/cli/src/blueprints-v1/blueprints-v1-handler.ts","../../../../packages/playground/cli/src/temp-dir.ts","../../../../packages/playground/cli/src/run-cli.ts"],"sourcesContent":["import type { PHPRequest, PHPResponse } from '@php-wasm/universal';\nimport type { Request } from 'express';\nimport express from 'express';\nimport type { IncomingMessage, Server, ServerResponse } from 'http';\nimport type { AddressInfo } from 'net';\nimport type { RunCLIServer } from './run-cli';\n\nexport interface ServerOptions {\n\tport: number;\n\tonBind: (server: Server, port: number) => Promise<RunCLIServer>;\n\thandleRequest: (request: PHPRequest) => Promise<PHPResponse>;\n}\n\nexport async function startServer(\n\toptions: ServerOptions\n): Promise<RunCLIServer> {\n\tconst app = express();\n\n\tconst server = await new Promise<\n\t\tServer<typeof IncomingMessage, typeof ServerResponse>\n\t>((resolve, reject) => {\n\t\tconst server = app.listen(options.port, () => {\n\t\t\tconst address = server.address();\n\t\t\tif (address === null || typeof address === 'string') {\n\t\t\t\treject(new Error('Server address is not available'));\n\t\t\t} else {\n\t\t\t\tresolve(server);\n\t\t\t}\n\t\t});\n\t});\n\n\tapp.use('/', async (req, res) => {\n\t\tconst phpResponse = await options.handleRequest({\n\t\t\turl: req.url,\n\t\t\theaders: parseHeaders(req),\n\t\t\tmethod: req.method as any,\n\t\t\tbody: await bufferRequestBody(req),\n\t\t});\n\n\t\tres.statusCode = phpResponse.httpStatusCode;\n\t\tfor (const key in phpResponse.headers) {\n\t\t\tres.setHeader(key, phpResponse.headers[key]);\n\t\t}\n\t\tres.end(phpResponse.bytes);\n\t});\n\n\tconst address = server.address();\n\tconst port = (address! as AddressInfo).port;\n\treturn await options.onBind(server, port);\n}\n\nconst bufferRequestBody = async (req: Request): Promise<Uint8Array> =>\n\tawait new Promise((resolve) => {\n\t\tconst body: Uint8Array[] = [];\n\t\treq.on('data', (chunk) => {\n\t\t\tbody.push(chunk);\n\t\t});\n\t\treq.on('end', () => {\n\t\t\tresolve(new Uint8Array(Buffer.concat(body)));\n\t\t});\n\t});\n\nconst parseHeaders = (req: Request): Record<string, string> => {\n\tconst requestHeaders: Record<string, string> = {};\n\tif (req.rawHeaders && req.rawHeaders.length) {\n\t\tfor (let i = 0; i < req.rawHeaders.length; i += 2) {\n\t\t\trequestHeaders[req.rawHeaders[i].toLowerCase()] =\n\t\t\t\treq.rawHeaders[i + 1];\n\t\t}\n\t}\n\treturn requestHeaders;\n};\n","import type { PHPRequest, PHPResponse, RemoteAPI } from '@php-wasm/universal';\nimport type { PlaygroundCliBlueprintV1Worker as PlaygroundCliWorkerV1 } from './blueprints-v1/worker-thread-v1';\nimport type { PlaygroundCliBlueprintV2Worker as PlaygroundCliWorkerV2 } from './blueprints-v2/worker-thread-v2';\n\ntype PlaygroundCliWorker = PlaygroundCliWorkerV1 | PlaygroundCliWorkerV2;\n\n// TODO: Let's merge worker management into PHPProcessManager\n// when we can have multiple workers in both CLI and web.\n// ¡ATTENTION!:Please don't expand upon this as an independent abstraction.\n\n// TODO: Could we just spawn a worker using the factory function to PHPProcessManager?\ntype WorkerLoad = {\n\tworker: RemoteAPI<PlaygroundCliWorker>;\n\tactiveRequests: Set<Promise<PHPResponse>>;\n};\nexport class LoadBalancer {\n\tworkerLoads: WorkerLoad[] = [];\n\n\tconstructor(\n\t\t// NOTE: We require a worker to start so that a load balancer\n\t\t// may not exist without being able to service requests.\n\t\t// Playground CLI initialization, as of 2025-06-11, requires that\n\t\t// an initial worker is booted alone and initialized via Blueprint\n\t\t// before additional workers are created based on the initialized worker.\n\t\tinitialWorker: RemoteAPI<PlaygroundCliWorker>\n\t) {\n\t\tthis.addWorker(initialWorker);\n\t}\n\n\taddWorker(worker: RemoteAPI<PlaygroundCliWorker>) {\n\t\tthis.workerLoads.push({\n\t\t\tworker,\n\t\t\tactiveRequests: new Set(),\n\t\t});\n\t}\n\n\tasync handleRequest(request: PHPRequest) {\n\t\tlet smallestWorkerLoad = this.workerLoads[0];\n\n\t\t// TODO: Is there any way for us to track CPU load so we could avoid\n\t\t// picking a worker that is under heavy load despite few requests?\n\t\t// Possibly this: https://nodejs.org/api/worker_threads.html#workerperformance\n\t\t// Though we probably don't need to worry about it.\n\t\tfor (let i = 1; i < this.workerLoads.length; i++) {\n\t\t\tconst workerLoad = this.workerLoads[i];\n\t\t\tif (\n\t\t\t\tworkerLoad.activeRequests.size <\n\t\t\t\tsmallestWorkerLoad.activeRequests.size\n\t\t\t) {\n\t\t\t\tsmallestWorkerLoad = workerLoad;\n\t\t\t}\n\t\t}\n\n\t\t// TODO: Add trace facility to Playground CLI to observe internals like request routing.\n\n\t\tconst promiseForResponse = smallestWorkerLoad.worker.request(request);\n\t\tsmallestWorkerLoad.activeRequests.add(promiseForResponse);\n\n\t\t// Add URL to promise for use while debugging\n\t\t(promiseForResponse as any).url = request.url;\n\n\t\treturn promiseForResponse.finally(() => {\n\t\t\tsmallestWorkerLoad.activeRequests.delete(promiseForResponse);\n\t\t});\n\t}\n}\n","/**\n * Checks if the given version string is a valid WordPress version.\n *\n * The Regex is based on the releases on https://wordpress.org/download/releases/#betas\n * The version string can be one of the following formats:\n * - \"latest\"\n * - \"trunk\"\n * - \"nightly\"\n * - \"x.y\" (x and y are integers) e.g. \"6.2\"\n * - \"x.y.z\" (x, y and z are integers) e.g. \"6.2.1\"\n * - \"x.y.z-betaN\" (N is an integer) e.g. \"6.2.1-beta1\"\n * - \"x.y.z-RCN\" (N is an integer) e.g. \"6.2-RC1\"\n *\n * @param version The version string to check.\n * @returns A boolean value indicating whether the version string is a valid WordPress version.\n */\nexport function isValidWordPressSlug(version: string): boolean {\n\tconst versionPattern =\n\t\t/^latest$|^trunk$|^nightly$|^(?:(\\d+)\\.(\\d+)(?:\\.(\\d+))?)((?:-beta(?:\\d+)?)|(?:-RC(?:\\d+)?))?$/;\n\treturn versionPattern.test(version);\n}\n","import fs from 'fs';\nimport path from 'path';\nimport {\n\tZipFilesystem,\n\tNodeJsFilesystem,\n\tOverlayFilesystem,\n\tInMemoryFilesystem,\n} from '@wp-playground/storage';\nimport { resolveRemoteBlueprint } from '@wp-playground/blueprints';\n\ntype ResolveBlueprintOptions = {\n\tsourceString: string | undefined;\n\tblueprintMayReadAdjacentFiles: boolean;\n};\n\n/**\n * Resolves a blueprint from a URL or a local path.\n *\n * @TODO: Extract the common Blueprint resolution logic between CLI and\n * the website into a single, isomorphic resolveBlueprint() function.\n * Still retain the CLI-specific bits in the CLI package.\n *\n * @param sourceString - The source string to resolve the blueprint from.\n * @param blueprintMayReadAdjacentFiles - Whether the blueprint may read adjacent files.\n * @returns The resolved blueprint.\n */\nexport async function resolveBlueprint({\n\tsourceString,\n\tblueprintMayReadAdjacentFiles,\n}: ResolveBlueprintOptions) {\n\tif (!sourceString) {\n\t\treturn undefined;\n\t}\n\n\tif (\n\t\tsourceString.startsWith('http://') ||\n\t\tsourceString.startsWith('https://')\n\t) {\n\t\treturn await resolveRemoteBlueprint(sourceString);\n\t}\n\n\t// If the sourceString does not refer to a remote blueprint, try to\n\t// resolve it from a local filesystem.\n\n\tlet blueprintPath = path.resolve(process.cwd(), sourceString);\n\tif (!fs.existsSync(blueprintPath)) {\n\t\tthrow new Error(`Blueprint file does not exist: ${blueprintPath}`);\n\t}\n\n\tconst stat = fs.statSync(blueprintPath);\n\tif (stat.isDirectory()) {\n\t\tblueprintPath = path.join(blueprintPath, 'blueprint.json');\n\t}\n\n\tif (!stat.isFile() && stat.isSymbolicLink()) {\n\t\tthrow new Error(\n\t\t\t`Blueprint path is neither a file nor a directory: ${blueprintPath}`\n\t\t);\n\t}\n\n\tconst extension = path.extname(blueprintPath);\n\tswitch (extension) {\n\t\tcase '.zip':\n\t\t\treturn ZipFilesystem.fromArrayBuffer(\n\t\t\t\tfs.readFileSync(blueprintPath).buffer as ArrayBuffer\n\t\t\t);\n\t\tcase '.json': {\n\t\t\tconst blueprintText = fs.readFileSync(blueprintPath, 'utf-8');\n\t\t\ttry {\n\t\t\t\tJSON.parse(blueprintText);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Blueprint file at ${blueprintPath} is not a valid JSON file`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst contextPath = path.dirname(blueprintPath);\n\t\t\tconst nodeJsFilesystem = new NodeJsFilesystem(contextPath);\n\t\t\treturn new OverlayFilesystem([\n\t\t\t\tnew InMemoryFilesystem({\n\t\t\t\t\t'blueprint.json': blueprintText,\n\t\t\t\t}),\n\t\t\t\t/**\n\t\t\t\t * Wrap the NodeJS filesystem to prevent access to local files\n\t\t\t\t * unless the user explicitly allowed it.\n\t\t\t\t */\n\t\t\t\t{\n\t\t\t\t\tread(path) {\n\t\t\t\t\t\tif (!blueprintMayReadAdjacentFiles) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Error: Blueprint contained tried to read a local file at path \"${path}\" (via a resource of type \"bundled\"). ` +\n\t\t\t\t\t\t\t\t\t`Playground restricts access to local resources by default as a security measure. \\n\\n` +\n\t\t\t\t\t\t\t\t\t`You can allow this Blueprint to read files from the same parent directory by explicitly adding the ` +\n\t\t\t\t\t\t\t\t\t`--blueprint-may-read-adjacent-files option to your command.`\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn nodeJsFilesystem.read(path);\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t]);\n\t\t}\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Unsupported blueprint file extension: ${extension}. Only .zip and .json files are supported.`\n\t\t\t);\n\t}\n}\n","import type { RemoteAPI, SupportedPHPVersion } from '@php-wasm/universal';\nimport { consumeAPI } from '@php-wasm/universal';\nimport type {\n\tPlaygroundCliBlueprintV2Worker,\n\tSecondaryWorkerBootArgs,\n} from './worker-thread-v2';\nimport type { MessagePort as NodeMessagePort } from 'worker_threads';\nimport type { RunCLIArgs, SpawnedWorker, WorkerType } from '../run-cli';\n\n/**\n * Boots Playground CLI workers using Blueprint version 2.\n *\n * Progress tracking, downloads, steps, and all other features are\n * implemented in PHP and orchestrated by the worker thread.\n */\nexport class BlueprintsV2Handler {\n\tprivate phpVersion: SupportedPHPVersion;\n\tprivate lastProgressMessage = '';\n\n\tprivate siteUrl: string;\n\tprivate processIdSpaceLength: number;\n\tprivate args: RunCLIArgs;\n\n\tconstructor(\n\t\targs: RunCLIArgs,\n\t\toptions: {\n\t\t\tsiteUrl: string;\n\t\t\tprocessIdSpaceLength: number;\n\t\t}\n\t) {\n\t\tthis.args = args;\n\t\tthis.siteUrl = options.siteUrl;\n\t\tthis.processIdSpaceLength = options.processIdSpaceLength;\n\t\tthis.phpVersion = args.php as SupportedPHPVersion;\n\t}\n\n\tgetWorkerType(): WorkerType {\n\t\treturn 'v2';\n\t}\n\n\tasync bootPrimaryWorker(\n\t\tphpPort: NodeMessagePort,\n\t\tfileLockManagerPort: NodeMessagePort,\n\t\tnativeInternalDirPath: string\n\t) {\n\t\tconst playground: RemoteAPI<PlaygroundCliBlueprintV2Worker> =\n\t\t\tconsumeAPI(phpPort);\n\n\t\tawait playground.useFileLockManager(fileLockManagerPort);\n\n\t\tconst workerBootArgs = {\n\t\t\t...this.args,\n\t\t\tphpVersion: this.phpVersion,\n\t\t\tsiteUrl: this.siteUrl,\n\t\t\tfirstProcessId: 1,\n\t\t\tprocessIdSpaceLength: this.processIdSpaceLength,\n\t\t\ttrace: this.args.debug || false,\n\t\t\tblueprint: this.args.blueprint!,\n\t\t\tnativeInternalDirPath,\n\t\t};\n\n\t\tawait playground.bootAsPrimaryWorker(workerBootArgs);\n\t\treturn playground;\n\t}\n\n\tasync bootSecondaryWorker({\n\t\tworker,\n\t\tfileLockManagerPort,\n\t\tfirstProcessId,\n\t\tnativeInternalDirPath,\n\t}: {\n\t\tworker: SpawnedWorker;\n\t\tfileLockManagerPort: NodeMessagePort;\n\t\tfirstProcessId: number;\n\t\tnativeInternalDirPath: string;\n\t}) {\n\t\tconst playground: RemoteAPI<PlaygroundCliBlueprintV2Worker> =\n\t\t\tconsumeAPI(worker.phpPort);\n\n\t\tawait playground.useFileLockManager(fileLockManagerPort);\n\n\t\tconst workerBootArgs: SecondaryWorkerBootArgs = {\n\t\t\t...this.args,\n\t\t\tphpVersion: this.phpVersion!,\n\t\t\tsiteUrl: this.siteUrl,\n\t\t\tfirstProcessId,\n\t\t\tprocessIdSpaceLength: this.processIdSpaceLength,\n\t\t\ttrace: this.args.debug || false,\n\t\t\tnativeInternalDirPath,\n\t\t\tmountsBeforeWpInstall: this.args['mount-before-install'] || [],\n\t\t\tmountsAfterWpInstall: this.args.mount || [],\n\t\t};\n\n\t\tawait playground.bootAsSecondaryWorker(workerBootArgs);\n\n\t\treturn playground;\n\t}\n\n\twriteProgressUpdate(\n\t\twriteStream: NodeJS.WriteStream,\n\t\tmessage: string,\n\t\tfinalUpdate: boolean\n\t) {\n\t\tif (message === this.lastProgressMessage) {\n\t\t\t// Avoid repeating the same message\n\t\t\treturn;\n\t\t}\n\t\tthis.lastProgressMessage = message;\n\n\t\tif (writeStream.isTTY) {\n\t\t\t// Overwrite previous progress updates in-place for a quieter UX.\n\t\t\twriteStream.cursorTo(0);\n\t\t\twriteStream.write(message);\n\t\t\twriteStream.clearLine(1);\n\n\t\t\tif (finalUpdate) {\n\t\t\t\twriteStream.write('\\n');\n\t\t\t}\n\t\t} else {\n\t\t\t// Fall back to writing one line per progress update\n\t\t\twriteStream.write(`${message}\\n`);\n\t\t}\n\t}\n}\n","import type { EmscriptenDownloadMonitor } from '@php-wasm/progress';\nimport fs from 'fs-extra';\nimport os from 'os';\nimport path, { basename } from 'path';\n\nexport const CACHE_FOLDER = path.join(os.homedir(), '.wordpress-playground');\n\nexport async function fetchSqliteIntegration(\n\tmonitor: EmscriptenDownloadMonitor\n) {\n\tconst sqliteZip = await cachedDownload(\n\t\t'https://github.com/WordPress/sqlite-database-integration/archive/refs/heads/develop.zip',\n\t\t'sqlite.zip',\n\t\tmonitor\n\t);\n\treturn sqliteZip;\n}\n\n// @TODO: Support HTTP cache, invalidate the local file if the remote file has\n// changed\nexport async function cachedDownload(\n\tremoteUrl: string,\n\tcacheKey: string,\n\tmonitor: EmscriptenDownloadMonitor\n) {\n\tconst artifactPath = path.join(CACHE_FOLDER, cacheKey);\n\tif (!fs.existsSync(artifactPath)) {\n\t\tfs.ensureDirSync(CACHE_FOLDER);\n\t\tawait downloadTo(remoteUrl, artifactPath, monitor);\n\t}\n\treturn readAsFile(artifactPath);\n}\n\nasync function downloadTo(\n\tremoteUrl: string,\n\tlocalPath: string,\n\tmonitor: EmscriptenDownloadMonitor\n) {\n\tconst response = await monitor.monitorFetch(fetch(remoteUrl));\n\tconst reader = response.body!.getReader();\n\tconst tmpPath = `${localPath}.partial`;\n\tconst writer = fs.createWriteStream(tmpPath);\n\twhile (true) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (value) {\n\t\t\twriter.write(value);\n\t\t}\n\t\tif (done) {\n\t\t\tbreak;\n\t\t}\n\t}\n\twriter.close();\n\tif (!writer.closed) {\n\t\tawait new Promise((resolve, reject) => {\n\t\t\twriter.on('finish', () => {\n\t\t\t\tfs.renameSync(tmpPath, localPath);\n\t\t\t\tresolve(null);\n\t\t\t});\n\t\t\twriter.on('error', (err: any) => {\n\t\t\t\tfs.removeSync(tmpPath);\n\t\t\t\treject(err);\n\t\t\t});\n\t\t});\n\t}\n}\n\nexport function readAsFile(path: string, fileName?: string): File {\n\treturn new File([fs.readFileSync(path)], fileName ?? basename(path));\n}\n","import { logger } from '@php-wasm/logger';\nimport { EmscriptenDownloadMonitor, ProgressTracker } from '@php-wasm/progress';\nimport type { SupportedPHPVersion } from '@php-wasm/universal';\nimport { consumeAPI } from '@php-wasm/universal';\nimport type {\n\tBlueprintBundle,\n\tBlueprintV1Declaration,\n} from '@wp-playground/blueprints';\nimport {\n\tcompileBlueprintV1,\n\tisBlueprintBundle,\n} from '@wp-playground/blueprints';\nimport { RecommendedPHPVersion, zipDirectory } from '@wp-playground/common';\nimport fs from 'fs';\nimport path from 'path';\nimport { resolveWordPressRelease } from '@wp-playground/wordpress';\nimport {\n\tCACHE_FOLDER,\n\tcachedDownload,\n\tfetchSqliteIntegration,\n\treadAsFile,\n} from './download';\nimport type { PlaygroundCliBlueprintV1Worker } from './worker-thread-v1';\nimport type { MessagePort as NodeMessagePort } from 'worker_threads';\nimport {\n\tLogVerbosity,\n\ttype RunCLIArgs,\n\ttype SpawnedWorker,\n\ttype WorkerType,\n} from '../run-cli';\n\n/**\n * Boots Playground CLI workers using Blueprint version 1.\n *\n * Progress tracking, downloads, steps, and all other features are\n * implemented in TypeScript and orchestrated by this class.\n */\nexport class BlueprintsV1Handler {\n\tprivate phpVersion: SupportedPHPVersion | undefined;\n\tprivate lastProgressMessage = '';\n\n\tprivate siteUrl: string;\n\tprivate processIdSpaceLength: number;\n\tprivate args: RunCLIArgs;\n\n\tconstructor(\n\t\targs: RunCLIArgs,\n\t\toptions: {\n\t\t\tsiteUrl: string;\n\t\t\tprocessIdSpaceLength: number;\n\t\t}\n\t) {\n\t\tthis.args = args;\n\t\tthis.siteUrl = options.siteUrl;\n\t\tthis.processIdSpaceLength = options.processIdSpaceLength;\n\t}\n\n\tgetWorkerType(): WorkerType {\n\t\treturn 'v1';\n\t}\n\n\tasync bootPrimaryWorker(\n\t\tphpPort: NodeMessagePort,\n\t\tfileLockManagerPort: NodeMessagePort,\n\t\tnativeInternalDirPath: string\n\t) {\n\t\tconst compiledBlueprint = await this.compileInputBlueprint(\n\t\t\tthis.args['additional-blueprint-steps'] || []\n\t\t);\n\t\tthis.phpVersion = compiledBlueprint.versions.php;\n\n\t\tlet wpDetails: any = undefined;\n\t\t// @TODO: Rename to FetchProgressMonitor. There's nothing Emscripten\n\t\t// about that class anymore.\n\t\tconst monitor = new EmscriptenDownloadMonitor();\n\t\tif (!this.args.skipWordPressSetup) {\n\t\t\tlet progressReached100 = false;\n\t\t\tmonitor.addEventListener('progress', ((\n\t\t\t\te: CustomEvent<ProgressEvent & { finished: boolean }>\n\t\t\t) => {\n\t\t\t\tif (progressReached100) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// @TODO Every progress bar will want percentages. The\n\t\t\t\t// download monitor should just provide that.\n\t\t\t\tconst { loaded, total } = e.detail;\n\t\t\t\t// Use floor() so we don't report 100% until truly there.\n\t\t\t\tconst percentProgress = Math.floor(\n\t\t\t\t\tMath.min(100, (100 * loaded) / total)\n\t\t\t\t);\n\t\t\t\tprogressReached100 = percentProgress === 100;\n\n\t\t\t\tthis.writeProgressUpdate(\n\t\t\t\t\tprocess.stdout,\n\t\t\t\t\t`Downloading WordPress ${percentProgress}%...`,\n\t\t\t\t\tprogressReached100\n\t\t\t\t);\n\t\t\t}) as any);\n\n\t\t\twpDetails = await resolveWordPressRelease(this.args.wp);\n\t\t\tlogger.log(\n\t\t\t\t`Resolved WordPress release URL: ${wpDetails?.releaseUrl}`\n\t\t\t);\n\t\t}\n\n\t\tconst preinstalledWpContentPath =\n\t\t\twpDetails &&\n\t\t\tpath.join(\n\t\t\t\tCACHE_FOLDER,\n\t\t\t\t`prebuilt-wp-content-for-wp-${wpDetails.version}.zip`\n\t\t\t);\n\t\tconst wordPressZip = !wpDetails\n\t\t\t? undefined\n\t\t\t: fs.existsSync(preinstalledWpContentPath)\n\t\t\t? readAsFile(preinstalledWpContentPath)\n\t\t\t: await cachedDownload(\n\t\t\t\t\twpDetails.releaseUrl,\n\t\t\t\t\t`${wpDetails.version}.zip`,\n\t\t\t\t\tmonitor\n\t\t\t );\n\n\t\tlogger.log(`Fetching SQLite integration plugin...`);\n\t\tconst sqliteIntegrationPluginZip = this.args.skipSqliteSetup\n\t\t\t? undefined\n\t\t\t: await fetchSqliteIntegration(monitor);\n\n\t\tconst followSymlinks = this.args.followSymlinks === true;\n\t\tconst trace = this.args.experimentalTrace === true;\n\n\t\tconst mountsBeforeWpInstall = this.args['mount-before-install'] || [];\n\t\tconst mountsAfterWpInstall = this.args.mount || [];\n\n\t\tconst playground = consumeAPI<PlaygroundCliBlueprintV1Worker>(phpPort);\n\n\t\t// Comlink communication proxy\n\t\tawait playground.isConnected();\n\n\t\tlogger.log(`Booting WordPress...`);\n\n\t\tawait playground.useFileLockManager(fileLockManagerPort);\n\t\tawait playground.bootAsPrimaryWorker({\n\t\t\tphpVersion: this.phpVersion,\n\t\t\twpVersion: compiledBlueprint.versions.wp,\n\t\t\tsiteUrl: this.siteUrl,\n\t\t\tmountsBeforeWpInstall,\n\t\t\tmountsAfterWpInstall,\n\t\t\twordPressZip: wordPressZip && (await wordPressZip!.arrayBuffer()),\n\t\t\tsqliteIntegrationPluginZip:\n\t\t\t\tawait sqliteIntegrationPluginZip?.arrayBuffer(),\n\t\t\tfirstProcessId: 0,\n\t\t\tprocessIdSpaceLength: this.processIdSpaceLength,\n\t\t\tfollowSymlinks,\n\t\t\ttrace,\n\t\t\tinternalCookieStore: this.args.internalCookieStore,\n\t\t\twithXdebug: this.args.xdebug,\n\t\t\tnativeInternalDirPath,\n\t\t});\n\n\t\tif (\n\t\t\twpDetails &&\n\t\t\t!this.args['mount-before-install'] &&\n\t\t\t!fs.existsSync(preinstalledWpContentPath)\n\t\t) {\n\t\t\tlogger.log(`Caching preinstalled WordPress for the next boot...`);\n\t\t\tfs.writeFileSync(\n\t\t\t\tpreinstalledWpContentPath,\n\t\t\t\t(await zipDirectory(playground, '/wordpress'))!\n\t\t\t);\n\t\t\tlogger.log(`Cached!`);\n\t\t}\n\n\t\treturn playground;\n\t}\n\n\tasync bootSecondaryWorker({\n\t\tworker,\n\t\tfileLockManagerPort,\n\t\tfirstProcessId,\n\t\tnativeInternalDirPath,\n\t}: {\n\t\tworker: SpawnedWorker;\n\t\tfileLockManagerPort: NodeMessagePort;\n\t\tfirstProcessId: number;\n\t\tnativeInternalDirPath: string;\n\t}) {\n\t\tconst additionalPlayground = consumeAPI<PlaygroundCliBlueprintV1Worker>(\n\t\t\tworker.phpPort\n\t\t);\n\n\t\tawait additionalPlayground.isConnected();\n\t\tawait additionalPlayground.useFileLockManager(fileLockManagerPort);\n\t\tawait additionalPlayground.bootAsSecondaryWorker({\n\t\t\tphpVersion: this.phpVersion!,\n\t\t\tsiteUrl: this.siteUrl,\n\t\t\tmountsBeforeWpInstall: this.args['mount-before-install'] || [],\n\t\t\tmountsAfterWpInstall: this.args['mount'] || [],\n\t\t\tfirstProcessId,\n\t\t\tprocessIdSpaceLength: this.processIdSpaceLength,\n\t\t\tfollowSymlinks: this.args.followSymlinks === true,\n\t\t\ttrace: this.args.experimentalTrace === true,\n\t\t\t// @TODO: Move this to the request handler or else every worker\n\t\t\t// will have a separate cookie store.\n\t\t\tinternalCookieStore: this.args.internalCookieStore,\n\t\t\twithXdebug: this.args.xdebug,\n\t\t\tnativeInternalDirPath,\n\t\t});\n\t\tawait additionalPlayground.isReady();\n\t\treturn additionalPlayground;\n\t}\n\n\tasync compileInputBlueprint(additionalBlueprintSteps: any[]) {\n\t\tconst args = this.args;\n\t\tconst resolvedBlueprint = args.blueprint as BlueprintV1Declaration;\n\t\t/**\n\t\t * @TODO This looks similar to the resolveBlueprint() call in the website package:\n\t\t * \t https://github.com/WordPress/wordpress-playground/blob/ce586059e5885d185376184fdd2f52335cca32b0/packages/playground/website/src/main.tsx#L41\n\t\t *\n\t\t * \t\t Also the Blueprint Builder tool does something similar.\n\t\t * Perhaps all these cases could be handled by the same function?\n\t\t */\n\t\tconst blueprint: BlueprintV1Declaration | BlueprintBundle =\n\t\t\tisBlueprintBundle(resolvedBlueprint)\n\t\t\t\t? resolvedBlueprint\n\t\t\t\t: {\n\t\t\t\t\t\tlogin: args.login,\n\t\t\t\t\t\t...(resolvedBlueprint || {}),\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\tresolvedBlueprint?.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\tresolvedBlueprint?.preferredVersions?.wp ??\n\t\t\t\t\t\t\t\t'latest',\n\t\t\t\t\t\t\t...(resolvedBlueprint?.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\tthis.writeProgressUpdate(\n\t\t\t\tprocess.stdout,\n\t\t\t\tmessage,\n\t\t\t\tprogressReached100\n\t\t\t);\n\t\t});\n\t\treturn await compileBlueprintV1(blueprint as BlueprintV1Declaration, {\n\t\t\tprogress: tracker,\n\t\t\tadditionalSteps: additionalBlueprintSteps,\n\t\t});\n\t}\n\n\twriteProgressUpdate(\n\t\twriteStream: NodeJS.WriteStream,\n\t\tmessage: string,\n\t\tfinalUpdate: boolean\n\t) {\n\t\tif (this.args.verbosity === LogVerbosity.Quiet.name) {\n\t\t\treturn;\n\t\t}\n\t\tif (message === this.lastProgressMessage) {\n\t\t\t// Avoid repeating the same message\n\t\t\treturn;\n\t\t}\n\t\tthis.lastProgressMessage = message;\n\n\t\tif (writeStream.isTTY) {\n\t\t\t// Overwrite previous progress updates in-place for a quieter UX.\n\t\t\twriteStream.cursorTo(0);\n\t\t\twriteStream.write(message);\n\t\t\twriteStream.clearLine(1);\n\n\t\t\tif (finalUpdate) {\n\t\t\t\twriteStream.write('\\n');\n\t\t\t}\n\t\t} else {\n\t\t\t// Fall back to writing one line per progress update\n\t\t\twriteStream.write(`${message}\\n`);\n\t\t}\n\t}\n}\n","import fs from 'fs';\nimport path from 'path';\nimport { logger } from '@php-wasm/logger';\nimport {\n\tdir as tmpDir,\n\tsetGracefulCleanup as tmpSetGracefulCleanup,\n} from 'tmp-promise';\n// NOTE: We use ps-man rather than more popular packages because there\n// is no native build required to install the package.\n// @ts-ignore -- There are no types for this package.\nimport ps from 'ps-man';\n\n/**\n * Create a temp dir for the Playground CLI.\n *\n * The temp dir is created in the system temp dir and is named\n * based on the Playground CLI binary name and the process ID.\n *\n * @param substrToIdentifyTempDirs The substring to identify the temp dir.\n * @param autoCleanup Whether to skip cleanup on process exit. Primarily used for unit testing.\n * @returns The path to the temp dir.\n */\nexport async function createPlaygroundCliTempDir(\n\tsubstrToIdentifyTempDirs: string,\n\t// Allow controlling auto-cleanup for test purposes.\n\tautoCleanup = true\n) {\n\tconst nodeBinaryName = path.basename(process.argv0);\n\n\t// We place the binary name before the playground-related fragment\n\t// so we can use the position of the fragment to parse the binary name.\n\t// Otherwise, we would have to parse the binary name from the full path.\n\tconst tempDirPrefix = `${nodeBinaryName}${substrToIdentifyTempDirs}${process.pid}-`;\n\n\tconst nativeDirPath = (\n\t\tawait tmpDir({\n\t\t\tprefix: tempDirPrefix,\n\t\t\t/*\n\t\t\t * Allow recursive cleanup on process exit.\n\t\t\t *\n\t\t\t * NOTE: I worried about whether this cleanup would follow symlinks\n\t\t\t * and delete target files instead of unlinking the symlink,\n\t\t\t * but this feature uses rimraf under the hood which respects symlinks:\n\t\t\t * https://github.com/raszi/node-tmp/blob/3d2fe387f3f91b13830b9182faa02c3231ea8258/lib/tmp.js#L318\n\t\t\t */\n\t\t\tunsafeCleanup: true,\n\t\t})\n\t).path;\n\n\tif (autoCleanup) {\n\t\t// Request graceful cleanup on process exit.\n\t\ttmpSetGracefulCleanup();\n\t}\n\n\treturn nativeDirPath;\n}\n\n/**\n * Cleanup stale Playground temp dirs.\n *\n * A temp dir is considered stale if it is older than the specified age\n * and the associated process no longer exists.\n *\n * @param substrToIdentifyTempDirs The substring to identify the temp dir.\n * @param staleAgeInMillis The age in milliseconds after which a temp dir is considered stale.\n * @param tempRootDir The root directory of the temp dirs.\n */\nexport async function cleanupStalePlaygroundTempDirs(\n\tsubstrToIdentifyTempDirs: string,\n\tstaleAgeInMillis: number,\n\ttempRootDir: string\n) {\n\tconst stalePlaygroundTempDirs = await findStalePlaygroundTempDirs(\n\t\tsubstrToIdentifyTempDirs,\n\t\tstaleAgeInMillis,\n\t\ttempRootDir\n\t);\n\tconst promisesToRemove = stalePlaygroundTempDirs.map(\n\t\t(stalePlaygroundTempDir) =>\n\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t// TODO: Non-blocking: Consider how to avoid conflicts with another CLI doing cleanup.\n\t\t\t\tfs.rm(stalePlaygroundTempDir, { recursive: true }, (err) => {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t`Failed to delete stale Playground temp dir: ${stalePlaygroundTempDir}`,\n\t\t\t\t\t\t\terr\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t\t`Deleted stale Playground temp dir: ${stalePlaygroundTempDir}`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t})\n\t);\n\tawait Promise.all(promisesToRemove);\n}\n\nasync function findStalePlaygroundTempDirs(\n\tsubstrToIdentifyTempDirs: string,\n\tstaleAgeInMillis: number,\n\ttempRootDir: string\n) {\n\ttry {\n\t\tconst tempPaths = fs\n\t\t\t.readdirSync(tempRootDir)\n\t\t\t.map((dirName) => path.join(tempRootDir, dirName));\n\n\t\tconst stalePlaygroundTempDirs = [];\n\t\tfor (const tempPath of tempPaths) {\n\t\t\tconst appearsToBeStale = await appearsToBeStalePlaygroundTempDir(\n\t\t\t\tsubstrToIdentifyTempDirs,\n\t\t\t\tstaleAgeInMillis,\n\t\t\t\ttempPath\n\t\t\t);\n\t\t\tif (appearsToBeStale) {\n\t\t\t\tstalePlaygroundTempDirs.push(tempPath);\n\t\t\t}\n\t\t}\n\t\treturn stalePlaygroundTempDirs;\n\t} catch (e) {\n\t\tlogger.warn(`Failed to find stale Playground temp dirs: ${e}`);\n\t\t// Failing to find stale temp dirs should not prevent the CLI from starting.\n\t\treturn [];\n\t}\n}\n\nasync function appearsToBeStalePlaygroundTempDir(\n\tsubstrToIdentifyTempDirs: string,\n\tstaleAgeInMillis: number,\n\tabsolutePath: string\n) {\n\tconst lstat = fs.lstatSync(absolutePath);\n\tif (!lstat.isDirectory()) {\n\t\t// A non-directory cannot be a Playground temp dir.\n\t\treturn false;\n\t}\n\n\tconst dirName = path.basename(absolutePath);\n\tif (!dirName.includes(substrToIdentifyTempDirs)) {\n\t\t// This doesn't look like one of our temp dirs.\n\t\treturn false;\n\t}\n\n\tconst match = dirName.match(\n\t\tnew RegExp(`^(.+)${substrToIdentifyTempDirs}(\\\\d+)-`)\n\t);\n\tif (!match) {\n\t\t// We cannot parse the temp dir name,\n\t\t// so there is nothing more to try.\n\t\treturn false;\n\t}\n\n\tconst info = {\n\t\tabsolutePath,\n\t\texecutableName: match[1],\n\t\tpid: match[2],\n\t};\n\n\tif (await doesProcessExist(info.pid, info.executableName)) {\n\t\t// It looks like the temp dir's process is still running.\n\t\treturn false;\n\t}\n\n\tconst STALE_DATE = Date.now() - staleAgeInMillis;\n\tconst dirStat = fs.statSync(absolutePath);\n\tif (dirStat.mtime.getTime() < STALE_DATE) {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nasync function doesProcessExist(pid: string, executableName: string) {\n\t// Define this type because there are no types for ps.list()\n\ttype ProcessInfo = {\n\t\tpid: string;\n\t\tcommand: string;\n\t};\n\t// Look for an existing process with the same PID and executable name.\n\tconst [existingProcess] = await new Promise<ProcessInfo[]>(\n\t\t(resolve, reject) => {\n\t\t\tps.list(\n\t\t\t\t{\n\t\t\t\t\tpid,\n\t\t\t\t\tname: executableName,\n\t\t\t\t\t// Remove path from executable name in the results.\n\t\t\t\t\tclean: true,\n\t\t\t\t},\n\t\t\t\t(err: any, processes: ProcessInfo[]) => {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresolve(processes);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t);\n\treturn (\n\t\t!!existingProcess &&\n\t\texistingProcess.pid === pid &&\n\t\texistingProcess.command === executableName\n\t);\n}\n","import { errorLogPath, logger, LogSeverity } from '@php-wasm/logger';\nimport type {\n\tPHPRequest,\n\tRemoteAPI,\n\tSupportedPHPVersion,\n} from '@php-wasm/universal';\nimport {\n\tPHPResponse,\n\texposeAPI,\n\texposeSyncAPI,\n\tprintDebugDetails,\n} from '@php-wasm/universal';\nimport type {\n\tBlueprintBundle,\n\tBlueprintV1Declaration,\n\tBlueprintV2Declaration,\n} from '@wp-playground/blueprints';\nimport { runBlueprintV1Steps } from '@wp-playground/blueprints';\nimport { RecommendedPHPVersion } from '@wp-playground/common';\nimport fs, { mkdirSync } from 'fs';\nimport type { Server } from 'http';\nimport { MessageChannel as NodeMessageChannel, Worker } from 'worker_threads';\n// @ts-ignore\nimport {\n\texpandAutoMounts,\n\tparseMountDirArguments,\n\tparseMountWithDelimiterArguments,\n} from './mounts';\nimport { startServer } from './start-server';\nimport type {\n\tMount,\n\tPlaygroundCliBlueprintV1Worker,\n} from './blueprints-v1/worker-thread-v1';\nimport type { PlaygroundCliBlueprintV2Worker } from './blueprints-v2/worker-thread-v2';\nimport { FileLockManagerForNode } from '@php-wasm/node';\nimport { LoadBalancer } from './load-balancer';\n/* eslint-disable no-console */\nimport { SupportedPHPVersions } from '@php-wasm/universal';\nimport { cpus } from 'os';\nimport { jspi } from 'wasm-feature-detect';\nimport type { MessagePort as NodeMessagePort } from 'worker_threads';\nimport yargs from 'yargs';\nimport { isValidWordPressSlug } from './is-valid-wordpress-slug';\nimport { resolveBlueprint } from './resolve-blueprint';\nimport { BlueprintsV2Handler } from './blueprints-v2/blueprints-v2-handler';\nimport { BlueprintsV1Handler } from './blueprints-v1/blueprints-v1-handler';\nimport { startBridge } from '@php-wasm/xdebug-bridge';\nimport path from 'path';\nimport os from 'os';\nimport {\n\tcleanupStalePlaygroundTempDirs,\n\tcreatePlaygroundCliTempDir,\n} from './temp-dir';\n\n// Inlined worker URLs for static analysis by downstream bundlers\n// These are replaced at build time by the Vite plugin in vite.config.ts\ndeclare const __WORKER_V1_URL__: string;\ndeclare const __WORKER_V2_URL__: string;\n\nexport const LogVerbosity = {\n\tQuiet: { name: 'quiet', severity: LogSeverity.Fatal },\n\tNormal: { name: 'normal', severity: LogSeverity.Info },\n\tDebug: { name: 'debug', severity: LogSeverity.Debug },\n} as const;\n\ntype LogVerbosity = (typeof LogVerbosity)[keyof typeof LogVerbosity]['name'];\n\nexport type WorkerType = 'v1' | 'v2';\n\nexport async function parseOptionsAndRunCLI() {\n\ttry {\n\t\t/**\n\t\t * @TODO This looks similar to Query API args https://wordpress.github.io/wordpress-playground/developers/apis/query-api/\n\t\t * Perhaps the two could be handled by the same code?\n\t\t */\n\t\tconst yargsObject = yargs(process.argv.slice(2))\n\t\t\t.usage('Usage: wp-playground <command> [options]')\n\t\t\t.positional('command', {\n\t\t\t\tdescribe: 'Command to run',\n\t\t\t\tchoices: ['server', 'run-blueprint', 'build-snapshot'] as const,\n\t\t\t\tdemandOption: true,\n\t\t\t})\n\t\t\t.option('outfile', {\n\t\t\t\tdescribe: 'When building, write to this output file.',\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: 'wordpress.zip',\n\t\t\t})\n\t\t\t.option('port', {\n\t\t\t\tdescribe: 'Port to listen on when serving.',\n\t\t\t\ttype: 'number',\n\t\t\t\tdefault: 9400,\n\t\t\t})\n\t\t\t.option('site-url', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Site URL to use for WordPress. Defaults to http://127.0.0.1:{port}',\n\t\t\t\ttype: 'string',\n\t\t\t})\n\t\t\t.option('php', {\n\t\t\t\tdescribe: 'PHP version to use.',\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: RecommendedPHPVersion,\n\t\t\t\tchoices: SupportedPHPVersions,\n\t\t\t})\n\t\t\t.option('wp', {\n\t\t\t\tdescribe: 'WordPress version to use.',\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: 'latest',\n\t\t\t})\n\t\t\t// @TODO: Support read-only mounts, e.g. via WORKERFS, a custom\n\t\t\t// ReadOnlyNODEFS, or by copying the files into MEMFS\n\t\t\t.option('mount', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Mount a directory to the PHP runtime (can be used multiple times). Format: /host/path:/vfs/path',\n\t\t\t\ttype: 'array',\n\t\t\t\tstring: true,\n\t\t\t\tcoerce: parseMountWithDelimiterArguments,\n\t\t\t})\n\t\t\t.option('mount-before-install', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Mount a directory to the PHP runtime before WordPress installation (can be used multiple times). Format: /host/path:/vfs/path',\n\t\t\t\ttype: 'array',\n\t\t\t\tstring: true,\n\t\t\t\tcoerce: parseMountWithDelimiterArguments,\n\t\t\t})\n\t\t\t.option('mount-dir', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Mount a directory to the PHP runtime (can be used multiple times). Format: \"/host/path\" \"/vfs/path\"',\n\t\t\t\ttype: 'array',\n\t\t\t\tnargs: 2,\n\t\t\t\tarray: true,\n\t\t\t\t// coerce: parseMountDirArguments,\n\t\t\t})\n\t\t\t.option('mount-dir-before-install', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Mount a directory before WordPress installation (can be used multiple times). Format: \"/host/path\" \"/vfs/path\"',\n\t\t\t\ttype: 'string',\n\t\t\t\tnargs: 2,\n\t\t\t\tarray: true,\n\t\t\t\tcoerce: parseMountDirArguments,\n\t\t\t})\n\t\t\t.option('login', {\n\t\t\t\tdescribe: 'Should log the user in',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('blueprint', {\n\t\t\t\tdescribe: 'Blueprint to execute.',\n\t\t\t\ttype: 'string',\n\t\t\t})\n\t\t\t.option('blueprint-may-read-adjacent-files', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Consent flag: Allow \"bundled\" resources in a local blueprint to read files in the same directory as the blueprint file.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('skip-wordpress-setup', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Do not download, unzip, and install WordPress. Useful for mounting a pre-configured WordPress directory at /wordpress.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('skip-sqlite-setup', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Skip the SQLite integration plugin setup to allow the WordPress site to use MySQL.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t// Hidden - Deprecated in favor of verbosity\n\t\t\t.option('quiet', {\n\t\t\t\tdescribe: 'Do not output logs and progress messages.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t\thidden: true,\n\t\t\t})\n\t\t\t.option('verbosity', {\n\t\t\t\tdescribe: 'Output logs and progress messages.',\n\t\t\t\ttype: 'string',\n\t\t\t\tchoices: Object.values(LogVerbosity).map(\n\t\t\t\t\t(verbosity) => verbosity.name\n\t\t\t\t),\n\t\t\t\tdefault: 'normal',\n\t\t\t})\n\t\t\t.option('debug', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Print PHP error log content if an error occurs during Playground boot.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('auto-mount', {\n\t\t\t\tdescribe: `Automatically mount the specified directory. If no path is provided, mount the current working directory. You can mount a WordPress directory, a plugin directory, a theme directory, a wp-content directory, or any directory containing PHP and HTML files.`,\n\t\t\t\ttype: 'string',\n\t\t\t})\n\t\t\t.option('follow-symlinks', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Allow Playground to follow symlinks by automatically mounting symlinked directories and files encountered in mounted directories. \\nWarning: Following symlinks will expose files outside mounted directories to Playground and could be a security risk.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('experimental-trace', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Print detailed messages about system behavior to the console. Useful for troubleshooting.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t\t// Hide this option because we want to replace with a more general log-level flag.\n\t\t\t\thidden: true,\n\t\t\t})\n\t\t\t.option('internal-cookie-store', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Enable internal cookie handling. When enabled, Playground will manage cookies internally using ' +\n\t\t\t\t\t'an HttpCookieStore that persists cookies across requests. When disabled, cookies are handled ' +\n\t\t\t\t\t'externally (e.g., by a browser in Node.js environments).',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('xdebug', {\n\t\t\t\tdescribe: 'Enable Xdebug.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('experimental-devtools', {\n\t\t\t\tdescribe: 'Enable experimental browser development tools.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t})\n\t\t\t.option('experimental-multi-worker', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Enable experimental multi-worker support which requires ' +\n\t\t\t\t\t'a /wordpress directory backed by a real filesystem. ' +\n\t\t\t\t\t'Pass a positive number to specify the number of workers to use. ' +\n\t\t\t\t\t'Otherwise, default to the number of CPUs minus 1.',\n\t\t\t\ttype: 'number',\n\t\t\t\tcoerce: (value?: number) => value ?? cpus().length - 1,\n\t\t\t})\n\t\t\t.option('experimental-blueprints-v2-runner', {\n\t\t\t\tdescribe: 'Use the experimental Blueprint V2 runner.',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t\t// Remove the \"hidden\" flag once Blueprint V2 is fully supported\n\t\t\t\thidden: true,\n\t\t\t})\n\t\t\t.option('mode', {\n\t\t\t\tdescribe:\n\t\t\t\t\t'Blueprints v2 runner mode to use. This option is required when using the --experimental-blueprints-v2-runner flag with a blueprint.',\n\t\t\t\ttype: 'string',\n\t\t\t\tchoices: ['create-new-site', 'apply-to-existing-site'],\n\t\t\t\t// Remove the \"hidden\" flag once Blueprint V2 is fully supported\n\t\t\t\thidden: true,\n\t\t\t})\n\t\t\t.showHelpOnFail(false)\n\t\t\t.strictOptions()\n\t\t\t.check(async (args) => {\n\t\t\t\t// Support multiple spellings of \"WordPress\"\n\t\t\t\tif (\n\t\t\t\t\targs['skip-wordpress-setup'] ||\n\t\t\t\t\targs['skipWordpressSetup']\n\t\t\t\t) {\n\t\t\t\t\targs['skipWordPressSetup'] = true;\n\t\t\t\t}\n\n\t\t\t\tif (args.wp !== undefined && !isValidWordPressSlug(args.wp)) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// Check if is valid URL\n\t\t\t\t\t\tnew URL(args.wp);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'Unrecognized WordPress version. Please use \"latest\", a URL, or a numeric version such as \"6.2\", \"6.0.1\", \"6.2-beta1\", or \"6.2-RC1\"'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (args['site-url'] !== undefined && args['site-url'] !== '') {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnew URL(args['site-url']);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Invalid site-url \"${args['site-url']}\". Please provide a valid URL (e.g., http://localhost:8080 or https://example.com)`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (args['auto-mount']) {\n\t\t\t\t\tlet autoMountIsDir = false;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst autoMountStats = fs.statSync(args['auto-mount']);\n\t\t\t\t\t\tautoMountIsDir = autoMountStats.isDirectory();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tautoMountIsDir = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!autoMountIsDir) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`The specified --auto-mount path is not a directory: '${args['auto-mount']}'.`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (args['experimental-multi-worker'] !== undefined) {\n\t\t\t\t\tif (args['experimental-multi-worker'] <= 1) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'The --experimental-multi-worker flag must be a positive integer greater than 1.'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (args['experimental-blueprints-v2-runner'] === true) {\n\t\t\t\t\tif (args['mode'] !== undefined) {\n\t\t\t\t\t\tif ('skip-wordpress-setup' in args) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t'The --skipWordPressSetup option cannot be used with the --mode option. Use one or the other.'\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ('skip-sqlite-setup' in args) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t'The --skipSqliteSetup option is not supported in Blueprint V2 mode.'\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (args['auto-mount'] !== undefined) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t'The --mode option cannot be used with --auto-mount because --auto-mount automatically sets the mode.'\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Support the legacy v1 runner options\n\t\t\t\t\t\tif (args['skip-wordpress-setup'] === true) {\n\t\t\t\t\t\t\targs['mode'] = 'apply-to-existing-site';\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\targs['mode'] = 'create-new-site';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Support the legacy v1 runner options\n\t\t\t\t\tconst allow = (args['allow'] as string[]) || [];\n\n\t\t\t\t\tif (args['followSymlinks'] === true) {\n\t\t\t\t\t\tallow.push('follow-symlinks');\n\t\t\t\t\t}\n\n\t\t\t\t\tif (args['blueprint-may-read-adjacent-files'] === true) {\n\t\t\t\t\t\tallow.push('read-local-fs');\n\t\t\t\t\t}\n\n\t\t\t\t\targs['allow'] = allow;\n\t\t\t\t} else {\n\t\t\t\t\tif (args['mode'] !== undefined) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'The --mode option requires the --experimentalBlueprintsV2Runner flag.'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn true;\n\t\t\t});\n\n\t\tyargsObject.wrap(yargsObject.terminalWidth());\n\t\tconst args = await yargsObject.argv;\n\n\t\tconst command = args._[0] as string;\n\n\t\tif (!['run-blueprint', 'server', 'build-snapshot'].includes(command)) {\n\t\t\tyargsObject.showHelp();\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\tconst cliArgs = {\n\t\t\t...args,\n\t\t\tcommand,\n\t\t\tmount: [...(args.mount || []), ...(args['mount-dir'] || [])],\n\t\t\t'mount-before-install': [\n\t\t\t\t...(args['mount-before-install'] || []),\n\t\t\t\t...(args['mount-dir-before-install'] || []),\n\t\t\t],\n\t\t} as RunCLIArgs;\n\n\t\tawait runCLI(cliArgs);\n\t} catch (e) {\n\t\tif (!(e instanceof Error)) {\n\t\t\tthrow e;\n\t\t}\n\t\tconst debug = process.argv.includes('--debug');\n\t\tif (debug) {\n\t\t\tprintDebugDetails(e);\n\t\t} else {\n\t\t\tconst messageChain = [];\n\t\t\tlet currentError = e;\n\t\t\tdo {\n\t\t\t\tmessageChain.push(currentError.message);\n\t\t\t\tcurrentError = currentError.cause as Error;\n\t\t\t} while (currentError instanceof Error);\n\t\t\tconsole.error(\n\t\t\t\t'\\x1b[1m' + messageChain.join(' caused by ') + '\\x1b[0m'\n\t\t\t);\n\t\t}\n\t\tprocess.exit(1);\n\t}\n}\n\nexport interface RunCLIArgs {\n\tblueprint?:\n\t\t| BlueprintV1Declaration\n\t\t| BlueprintV2Declaration\n\t\t| BlueprintBundle;\n\tcommand: 'server' | 'run-blueprint' | 'build-snapshot';\n\tdebug?: boolean;\n\tlogin?: boolean;\n\tmount?: Mount[];\n\t'mount-before-install'?: Mount[];\n\toutfile?: string;\n\tphp?: SupportedPHPVersion;\n\tport?: number;\n\t'site-url'?: string;\n\tquiet?: boolean;\n\tverbosity?: LogVerbosity;\n\twp?: string;\n\tautoMount?: string;\n\texperimentalMultiWorker?: number;\n\texperimentalTrace?: boolean;\n\texitOnPrimaryWorkerCrash?: boolean;\n\tinternalCookieStore?: boolean;\n\t'additional-blueprint-steps'?: any[];\n\txdebug?: boolean;\n\texperimentalDevtools?: boolean;\n\t'experimental-blueprints-v2-runner'?: boolean;\n\n\t// --------- Blueprint V1 args -----------\n\tskipWordPressSetup?: boolean;\n\tskipSqliteSetup?: boolean;\n\tfollowSymlinks?: boolean;\n\t'blueprint-may-read-adjacent-files'?: boolean;\n\n\t// --------- Blueprint V2 args -----------\n\tmode?: 'mount-only' | 'create-new-site' | 'apply-to-existing-site';\n\n\t// --------- Blueprint V2 args (not available via CLI yet) -----------\n\t'db-engine'?: 'sqlite' | 'mysql';\n\t'db-host'?: string;\n\t'db-user'?: string;\n\t'db-pass'?: string;\n\t'db-name'?: string;\n\t'db-path'?: string;\n\t'truncate-new-site-directory'?: boolean;\n\tallow?: string;\n}\n\ntype PlaygroundCliWorker =\n\t| PlaygroundCliBlueprintV1Worker\n\t| PlaygroundCliBlueprintV2Worker;\n\nexport interface RunCLIServer extends AsyncDisposable {\n\tplayground: RemoteAPI<PlaygroundCliWorker>;\n\tserver: Server;\n\t[Symbol.asyncDispose](): Promise<void>;\n\t// Expose the number of worker threads to the test runner.\n\tworkerThreadCount: number;\n}\n\nexport async function runCLI(args: RunCLIArgs): Promise<RunCLIServer> {\n\tlet loadBalancer: LoadBalancer;\n\tlet playground: RemoteAPI<PlaygroundCliWorker>;\n\n\tconst playgroundsToCleanUp: {\n\t\tplayground: RemoteAPI<PlaygroundCliWorker>;\n\t\tworker: Worker;\n\t}[] = [];\n\n\t/**\n\t * Expand auto-mounts to include the necessary mounts and steps\n\t * when running in auto-mount mode.\n\t */\n\tif (args.autoMount !== undefined) {\n\t\tif (args.autoMount === '') {\n\t\t\t// No auto-mount path was provided, so use the current working directory.\n\t\t\t// Note: We default here instead of in the yargs declaration because\n\t\t\t// it allows us to test the default as part of the runCLI() unit tests.\n\t\t\targs = { ...args, autoMount: process.cwd() };\n\t\t}\n\t\targs = expandAutoMounts(args);\n\t}\n\n\t// Keeping 'quiet' option to preserve backward compatibility\n\tif (args.quiet) {\n\t\targs.verbosity = 'quiet';\n\t\tdelete args['quiet'];\n\t}\n\n\t// Promote \"debug\" flag to verbosity but keep args.debug around – the\n\t// program behavior may change in more ways than just logging verbosity\n\t// when debug mode is enabled, e.g. error objects may carry additional details.\n\tif (args.debug) {\n\t\targs.verbosity = 'debug';\n\t} else if (args.verbosity === 'debug') {\n\t\targs.debug = true;\n\t}\n\n\tif (args.verbosity) {\n\t\tconst severity = Object.values(LogVerbosity).find(\n\t\t\t(v) => v.name === args.verbosity\n\t\t)!.severity;\n\t\tlogger.setSeverityFilterLevel(severity);\n\t}\n\n\t// Declare file lock manager outside scope of startServer\n\t// so we can look at it when debugging request handling.\n\tconst nativeFlockSync =\n\t\tos.platform() === 'win32'\n\t\t\t? // @TODO: Enable fs-ext here when it works with Windows.\n\t\t\t undefined\n\t\t\t: await import('fs-ext')\n\t\t\t\t\t.then((m) => m.flockSync)\n\t\t\t\t\t.catch(() => {\n\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t'The fs-ext package is not installed. ' +\n\t\t\t\t\t\t\t\t'Internal file locking will not be integrated with ' +\n\t\t\t\t\t\t\t\t'host OS file locking.'\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t});\n\tconst fileLockManager = new FileLockManagerForNode(nativeFlockSync);\n\n\tlet wordPressReady = false;\n\tlet isFirstRequest = true;\n\n\tlogger.log('Starting a PHP server...');\n\n\treturn startServer({\n\t\tport: args['port'] as number,\n\t\tonBind: async (server: Server, port: number): Promise<RunCLIServer> => {\n\t\t\tconst serverUrl = `http://127.0.0.1:${port}`;\n\t\t\tconst siteUrl = args['site-url'] || serverUrl;\n\n\t\t\t// Create the blueprints handler\n\t\t\tconst totalWorkerCount = args.experimentalMultiWorker ?? 1;\n\t\t\tconst processIdSpaceLength = Math.floor(\n\t\t\t\tNumber.MAX_SAFE_INTEGER / totalWorkerCount\n\t\t\t);\n\n\t\t\t/*\n\t\t\t * Use a real temp dir as a target for the following Playground paths\n\t\t\t * so that multiple worker threads can share the same files.\n\t\t\t * - /internal\n\t\t\t * - /tmp\n\t\t\t * - /wordpress\n\t\t\t *\n\t\t\t * Sharing the same files leads to faster boot times and uses less memory\n\t\t\t * because we don't have to create or maintain multiple copies of the same files.\n\t\t\t */\n\t\t\tconst tempDirNameDelimiter = '-playground-cli-site-';\n\t\t\tconst nativeDirPath = await createPlaygroundCliTempDir(\n\t\t\t\ttempDirNameDelimiter\n\t\t\t);\n\n\t\t\t// We do not know the system temp dir,\n\t\t\t// but we can try to infer from the location of the current temp dir.\n\t\t\tconst tempDirRoot = path.dirname(nativeDirPath);\n\n\t\t\tconst twoDaysInMillis = 2 * 24 * 60 * 60 * 1000;\n\t\t\tconst tempDirStaleAgeInMillis = twoDaysInMillis;\n\n\t\t\t// NOTE: This is an async operation, but we do not care to block on it.\n\t\t\t// Let's let the cleanup happen as the main thread has time.\n\t\t\tcleanupStalePlaygroundTempDirs(\n\t\t\t\ttempDirNameDelimiter,\n\t\t\t\ttempDirStaleAgeInMillis,\n\t\t\t\ttempDirRoot\n\t\t\t);\n\n\t\t\t// NOTE: We do not add mount declarations for /internal here\n\t\t\t// because it will be mounted as part of php-wasm init.\n\t\t\tconst nativeInternalDirPath = path.join(nativeDirPath, 'internal');\n\t\t\tmkdirSync(nativeInternalDirPath);\n\n\t\t\tconst userProvidableNativeSubdirs = [\n\t\t\t\t'wordpress',\n\t\t\t\t// Note: These dirs are from Emscripten's \"default dirs\" list:\n\t\t\t\t// https://github.com/emscripten-core/emscripten/blob/f431ec220e472e1f8d3db6b52fe23fb377facf30/src/lib/libfs.js#L1400-L1402\n\t\t\t\t//\n\t\t\t\t// Any Playground process with multiple workers may assume\n\t\t\t\t// these are part of a shared filesystem, so let's recognize\n\t\t\t\t// them explicitly here.\n\t\t\t\t'tmp',\n\t\t\t\t'home',\n\t\t\t];\n\n\t\t\tfor (const subdirName of userProvidableNativeSubdirs) {\n\t\t\t\tconst isMountingSubdirName = (mount: Mount) =>\n\t\t\t\t\tmount.vfsPath === `/${subdirName}`;\n\t\t\t\tconst thisSubdirHasAMount =\n\t\t\t\t\targs['mount-before-install']?.some(isMountingSubdirName) ||\n\t\t\t\t\targs['mount']?.some(isMountingSubdirName);\n\t\t\t\tif (!thisSubdirHasAMount) {\n\t\t\t\t\t// The user hasn't requested mounting a different native dir for this path,\n\t\t\t\t\t// so let's create a mount from within our native temp dir.\n\t\t\t\t\tconst nativeSubdirPath = path.join(\n\t\t\t\t\t\tnativeDirPath,\n\t\t\t\t\t\tsubdirName\n\t\t\t\t\t);\n\t\t\t\t\tmkdirSync(nativeSubdirPath);\n\n\t\t\t\t\tif (args['mount-before-install'] === undefined) {\n\t\t\t\t\t\targs['mount-before-install'] = [];\n\t\t\t\t\t}\n\n\t\t\t\t\t// Make the real mount first so any further subdirs are mounted into it.\n\t\t\t\t\targs['mount-before-install'].unshift({\n\t\t\t\t\t\tvfsPath: `/${subdirName}`,\n\t\t\t\t\t\thostPath: nativeSubdirPath,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet handler: BlueprintsV1Handler | BlueprintsV2Handler;\n\t\t\tif (args['experimental-blueprints-v2-runner']) {\n\t\t\t\thandler = new BlueprintsV2Handler(args, {\n\t\t\t\t\tsiteUrl,\n\t\t\t\t\tprocessIdSpaceLength,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\thandler = new BlueprintsV1Handler(args, {\n\t\t\t\t\tsiteUrl,\n\t\t\t\t\tprocessIdSpaceLength,\n\t\t\t\t});\n\n\t\t\t\tif (typeof args.blueprint === 'string') {\n\t\t\t\t\targs.blueprint = await resolveBlueprint({\n\t\t\t\t\t\tsourceString: args.blueprint,\n\t\t\t\t\t\tblueprintMayReadAdjacentFiles:\n\t\t\t\t\t\t\targs['blueprint-may-read-adjacent-files'] === true,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Kick off worker threads now to save time later.\n\t\t\t// There is no need to wait for other async processes to complete.\n\t\t\tconst promisedWorkers = spawnWorkerThreads(\n\t\t\t\ttotalWorkerCount,\n\t\t\t\thandler.getWorkerType(),\n\t\t\t\t({ exitCode, isMain, workerIndex }) => {\n\t\t\t\t\tif (exitCode === 0) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlogger.error(\n\t\t\t\t\t\t`Worker ${workerIndex} exited with code ${exitCode}\\n`\n\t\t\t\t\t);\n\t\t\t\t\t// If the primary worker crashes, exit the entire process.\n\t\t\t\t\tif (!isMain) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (!args.exitOnPrimaryWorkerCrash) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tlogger.log(`Setting up WordPress ${args.wp}`);\n\n\t\t\ttry {\n\t\t\t\tconst [initialWorker, ...additionalWorkers] =\n\t\t\t\t\tawait promisedWorkers;\n\n\t\t\t\tconst fileLockManagerPort = await exposeFileLockManager(\n\t\t\t\t\tfileLockManager\n\t\t\t\t);\n\n\t\t\t\t// Boot the primary worker using the handler\n\t\t\t\tplayground = await handler.bootPrimaryWorker(\n\t\t\t\t\tinitialWorker.phpPort,\n\t\t\t\t\tfileLockManagerPort,\n\t\t\t\t\tnativeInternalDirPath\n\t\t\t\t);\n\t\t\t\tplaygroundsToCleanUp.push({\n\t\t\t\t\tplayground,\n\t\t\t\t\tworker: initialWorker.worker,\n\t\t\t\t});\n\n\t\t\t\tawait playground.isReady();\n\t\t\t\twordPressReady = true;\n\t\t\t\tlogger.log(`Booted!`);\n\n\t\t\t\tloadBalancer = new LoadBalancer(playground);\n\n\t\t\t\tif (!args['experimental-blueprints-v2-runner']) {\n\t\t\t\t\tconst compiledBlueprint = await (\n\t\t\t\t\t\thandler as BlueprintsV1Handler\n\t\t\t\t\t).compileInputBlueprint(\n\t\t\t\t\t\targs['additional-blueprint-steps'] || []\n\t\t\t\t\t);\n\n\t\t\t\t\tif (compiledBlueprint) {\n\t\t\t\t\t\tlogger.log(`Running the Blueprint...`);\n\t\t\t\t\t\tawait runBlueprintV1Steps(\n\t\t\t\t\t\t\tcompiledBlueprint,\n\t\t\t\t\t\t\tplayground\n\t\t\t\t\t\t);\n\t\t\t\t\t\tlogger.log(`Finished running the blueprint`);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (args.command === 'build-snapshot') {\n\t\t\t\t\tawait zipSite(playground, args.outfile as string);\n\t\t\t\t\tlogger.log(`WordPress exported to ${args.outfile}`);\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t} else if (args.command === 'run-blueprint') {\n\t\t\t\t\tlogger.log(`Blueprint executed`);\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\targs.experimentalMultiWorker &&\n\t\t\t\t\targs.experimentalMultiWorker > 1\n\t\t\t\t) {\n\t\t\t\t\tlogger.log(`Preparing additional workers...`);\n\n\t\t\t\t\t// Boot additional workers using the handler\n\t\t\t\t\tconst initialWorkerProcessIdSpace = processIdSpaceLength;\n\t\t\t\t\tawait Promise.all(\n\t\t\t\t\t\tadditionalWorkers.map(async (worker, index) => {\n\t\t\t\t\t\t\tconst firstProcessId =\n\t\t\t\t\t\t\t\tinitialWorkerProcessIdSpace +\n\t\t\t\t\t\t\t\tindex * processIdSpaceLength;\n\n\t\t\t\t\t\t\tconst fileLockManagerPort =\n\t\t\t\t\t\t\t\tawait exposeFileLockManager(fileLockManager);\n\n\t\t\t\t\t\t\tconst additionalPlayground =\n\t\t\t\t\t\t\t\tawait handler.bootSecondaryWorker({\n\t\t\t\t\t\t\t\t\tworker,\n\t\t\t\t\t\t\t\t\tfileLockManagerPort,\n\t\t\t\t\t\t\t\t\tfirstProcessId,\n\t\t\t\t\t\t\t\t\tnativeInternalDirPath,\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tplaygroundsToCleanUp.push({\n\t\t\t\t\t\t\t\tplayground: additionalPlayground,\n\t\t\t\t\t\t\t\tworker: worker.worker,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tloadBalancer.addWorker(additionalPlayground);\n\t\t\t\t\t\t})\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tlogger.log(\n\t\t\t\t\t`WordPress is running on ${serverUrl} with ${totalWorkerCount} worker(s)`\n\t\t\t\t);\n\n\t\t\t\tif (args.experimentalDevtools && args.xdebug) {\n\t\t\t\t\tconst bridge = await startBridge({\n\t\t\t\t\t\tgetPHPFile: async (path: string) =>\n\t\t\t\t\t\t\tawait playground!.readFileAsText(path),\n\t\t\t\t\t});\n\n\t\t\t\t\tbridge.start();\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tplayground,\n\t\t\t\t\tserver,\n\t\t\t\t\t[Symbol.asyncDispose]: async function disposeCLI() {\n\t\t\t\t\t\tawait Promise.all(\n\t\t\t\t\t\t\tplaygroundsToCleanUp.map(\n\t\t\t\t\t\t\t\tasync ({ playground, worker }) => {\n\t\t\t\t\t\t\t\t\tawait playground.dispose();\n\t\t\t\t\t\t\t\t\tawait worker.terminate();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t);\n\t\t\t\t\t\tawait new Promise((resolve) => server.close(resolve));\n\t\t\t\t\t},\n\t\t\t\t\tworkerThreadCount: totalWorkerCount,\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tif (!args.debug) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlet phpLogs = '';\n\t\t\t\tif (await playground?.fileExists(errorLogPath)) {\n\t\t\t\t\tphpLogs = await playground.readFileAsText(errorLogPath);\n\t\t\t\t}\n\t\t\t\tthrow new Error(phpLogs, { cause: error });\n\t\t\t}\n\t\t},\n\t\tasync handleRequest(request: PHPRequest) {\n\t\t\tif (!wordPressReady) {\n\t\t\t\treturn PHPResponse.forHttpCode(\n\t\t\t\t\t502,\n\t\t\t\t\t'WordPress is not ready yet'\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Clear the playground_auto_login_already_happened cookie on the first request.\n\t\t\t// Otherwise the first Playground CLI server started on the machine will set it,\n\t\t\t// all the subsequent runs will get the stale cookie, and the auto-login will\n\t\t\t// assume they don't have to auto-login again.\n\t\t\tif (isFirstRequest) {\n\t\t\t\tisFirstRequest = false;\n\t\t\t\tconst headers: Record<string, string[]> = {\n\t\t\t\t\t'Content-Type': ['text/plain'],\n\t\t\t\t\t'Content-Length': ['0'],\n\t\t\t\t\tLocation: ['/'],\n\t\t\t\t};\n\t\t\t\tif (\n\t\t\t\t\trequest.headers?.['cookie']?.includes(\n\t\t\t\t\t\t'playground_auto_login_already_happened'\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\theaders['Set-Cookie'] = [\n\t\t\t\t\t\t'playground_auto_login_already_happened=1; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/',\n\t\t\t\t\t];\n\t\t\t\t}\n\t\t\t\treturn new PHPResponse(302, headers, new Uint8Array());\n\t\t\t}\n\t\t\treturn await loadBalancer.handleRequest(request);\n\t\t},\n\t});\n}\n\nexport type SpawnedWorker = {\n\tworker: Worker;\n\tphpPort: NodeMessagePort;\n};\nasync function spawnWorkerThreads(\n\tcount: number,\n\tworkerType: WorkerType,\n\tonWorkerExit: (options: {\n\t\texitCode: number;\n\t\tisMain: boolean;\n\t\tworkerIndex: number;\n\t}) => void\n): Promise<SpawnedWorker[]> {\n\tconst promises = [];\n\tfor (let i = 0; i < count; i++) {\n\t\tconst worker = await spawnWorkerThread(workerType);\n\t\tconst onExit: (code: number) => void = (code: number) => {\n\t\t\tonWorkerExit({\n\t\t\t\texitCode: code,\n\t\t\t\tisMain: i === 0,\n\t\t\t\tworkerIndex: i,\n\t\t\t});\n\t\t};\n\t\tpromises.push(\n\t\t\tnew Promise<{ worker: Worker; phpPort: NodeMessagePort }>(\n\t\t\t\t(resolve, reject) => {\n\t\t\t\t\tworker.once('message', function (message: any) {\n\t\t\t\t\t\t// Let the worker confirm it has initialized.\n\t\t\t\t\t\t// We could use the 'online' event to detect start of JS execution,\n\t\t\t\t\t\t// but that would miss initialization errors.\n\t\t\t\t\t\tif (message.command === 'worker-script-initialized') {\n\t\t\t\t\t\t\tresolve({ worker, phpPort: message.phpPort });\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tworker.once('error', function (e: Error) {\n\t\t\t\t\t\tconsole.error(e);\n\t\t\t\t\t\tconst error = new Error(\n\t\t\t\t\t\t\t`Worker failed to load worker. ${\n\t\t\t\t\t\t\t\te.message ? `Original error: ${e.message}` : ''\n\t\t\t\t\t\t\t}`\n\t\t\t\t\t\t);\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t});\n\t\t\t\t\tworker.once('exit', onExit);\n\t\t\t\t}\n\t\t\t)\n\t\t);\n\t}\n\treturn Promise.all(promises);\n}\n\n/**\n * A statically analyzable function that spawns a worker thread of a given type.\n *\n * **Important:** This function builds to code that has the worker URL hardcoded\n * inline, e.g. `new Worker(new URL('./worker-thread-v1.js', import.meta.url))`.\n * This allows the downstream consumers to statically analyze the code, recognize\n * it uses workers, create new entrypoints, and rewrite the new Worker() calls.\n *\n * @param workerType\n * @returns\n */\nasync function spawnWorkerThread(workerType: 'v1' | 'v2') {\n\t/**\n\t * When running the CLI from source via `node cli.ts`, the Vite-provided\n\t * __WORKER_V1_URL__ and __WORKER_V2_URL__ are undefined. Let's set them to\n\t * the correct paths.\n\t */\n\tif (typeof __WORKER_V1_URL__ === 'undefined') {\n\t\t// @ts-expect-error\n\t\tglobalThis['__WORKER_V1_URL__'] = './blueprints-v1/worker-thread-v1.ts';\n\t}\n\tif (typeof __WORKER_V2_URL__ === 'undefined') {\n\t\t// @ts-expect-error\n\t\tglobalThis['__WORKER_V2_URL__'] = './blueprints-v2/worker-thread-v2.ts';\n\t}\n\tif (workerType === 'v1') {\n\t\treturn new Worker(new URL(__WORKER_V1_URL__, import.meta.url));\n\t} else {\n\t\treturn new Worker(new URL(__WORKER_V2_URL__, import.meta.url));\n\t}\n}\n\n/**\n * Expose the file lock manager API on a MessagePort and return it.\n *\n * @see comlink-sync.ts\n * @see phpwasm-emscripten-library-file-locking-for-node.js\n */\nasync function exposeFileLockManager(fileLockManager: FileLockManagerForNode) {\n\tconst { port1, port2 } = new NodeMessageChannel();\n\tif (await jspi()) {\n\t\t/**\n\t\t * When JSPI is available, the worker thread expects an asynchronous API.\n\t\t *\n\t\t * @see worker-thread.ts\n\t\t * @see comlink-sync.ts\n\t\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t\t */\n\t\texposeAPI(fileLockManager, null, port1);\n\t} else {\n\t\t/**\n\t\t * When JSPI is not available, the worker thread expects a synchronous API.\n\t\t *\n\t\t * @see worker-thread.ts\n\t\t * @see comlink-sync.ts\n\t\t * @see phpwasm-emscripten-library-file-locking-for-node.js\n\t\t */\n\t\tawait exposeSyncAPI(fileLockManager, port1);\n\t}\n\treturn port2;\n}\n\nasync function zipSite(\n\tplayground: RemoteAPI<PlaygroundCliWorker>,\n\toutfile: string\n) {\n\tawait playground.run({\n\t\tcode: `<?php\n\t\t$zip = new ZipArchive();\n\t\tif(false === $zip->open('/tmp/build.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {\n\t\t\tthrow new Exception('Failed to create ZIP');\n\t\t}\n\t\t$files = new RecursiveIteratorIterator(\n\t\t\tnew RecursiveDirectoryIterator('/wordpress')\n\t\t);\n\t\tforeach ($files as $file) {\n\t\t\techo $file . PHP_EOL;\n\t\t\tif (!$file->isFile()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t$zip->addFile($file->getPathname(), $file->getPathname());\n\t\t}\n\t\t$zip->close();\n\n\t`,\n\t});\n\tconst zip = await playground.readFileAsBuffer('/tmp/build.zip');\n\tfs.writeFileSync(outfile, zip);\n}\n"],"names":["startServer","options","app","express","server","resolve","reject","address","req","res","phpResponse","parseHeaders","bufferRequestBody","key","port","body","chunk","requestHeaders","i","LoadBalancer","initialWorker","worker","request","smallestWorkerLoad","workerLoad","promiseForResponse","isValidWordPressSlug","version","resolveBlueprint","sourceString","blueprintMayReadAdjacentFiles","resolveRemoteBlueprint","blueprintPath","path","fs","stat","extension","ZipFilesystem","blueprintText","contextPath","nodeJsFilesystem","NodeJsFilesystem","OverlayFilesystem","InMemoryFilesystem","BlueprintsV2Handler","args","phpPort","fileLockManagerPort","nativeInternalDirPath","playground","consumeAPI","workerBootArgs","firstProcessId","writeStream","message","finalUpdate","CACHE_FOLDER","os","fetchSqliteIntegration","monitor","cachedDownload","remoteUrl","cacheKey","artifactPath","downloadTo","readAsFile","localPath","reader","tmpPath","writer","done","value","err","fileName","basename","BlueprintsV1Handler","compiledBlueprint","wpDetails","EmscriptenDownloadMonitor","progressReached100","e","loaded","total","percentProgress","resolveWordPressRelease","logger","preinstalledWpContentPath","wordPressZip","sqliteIntegrationPluginZip","followSymlinks","trace","mountsBeforeWpInstall","mountsAfterWpInstall","zipDirectory","additionalPlayground","additionalBlueprintSteps","resolvedBlueprint","blueprint","isBlueprintBundle","RecommendedPHPVersion","tracker","ProgressTracker","lastCaption","progressInteger","compileBlueprintV1","LogVerbosity","createPlaygroundCliTempDir","substrToIdentifyTempDirs","autoCleanup","tempDirPrefix","nativeDirPath","tmpDir","tmpSetGracefulCleanup","cleanupStalePlaygroundTempDirs","staleAgeInMillis","tempRootDir","promisesToRemove","findStalePlaygroundTempDirs","stalePlaygroundTempDir","tempPaths","dirName","stalePlaygroundTempDirs","tempPath","appearsToBeStalePlaygroundTempDir","absolutePath","match","info","doesProcessExist","STALE_DATE","pid","executableName","existingProcess","ps","processes","LogSeverity","parseOptionsAndRunCLI","yargsObject","yargs","SupportedPHPVersions","parseMountWithDelimiterArguments","parseMountDirArguments","verbosity","cpus","autoMountIsDir","allow","command","cliArgs","runCLI","printDebugDetails","messageChain","currentError","loadBalancer","playgroundsToCleanUp","expandAutoMounts","severity","v","nativeFlockSync","m","fileLockManager","FileLockManagerForNode","wordPressReady","isFirstRequest","serverUrl","siteUrl","totalWorkerCount","processIdSpaceLength","tempDirNameDelimiter","tempDirRoot","tempDirStaleAgeInMillis","mkdirSync","userProvidableNativeSubdirs","subdirName","isMountingSubdirName","mount","nativeSubdirPath","handler","promisedWorkers","spawnWorkerThreads","exitCode","isMain","workerIndex","additionalWorkers","exposeFileLockManager","runBlueprintV1Steps","zipSite","initialWorkerProcessIdSpace","index","startBridge","error","phpLogs","errorLogPath","PHPResponse","headers","count","workerType","onWorkerExit","promises","spawnWorkerThread","onExit","code","Worker","port1","port2","NodeMessageChannel","jspi","exposeAPI","exposeSyncAPI","outfile","zip"],"mappings":";;;;;;;;;;;;;;;;;;;;AAaA,eAAsBA,GACrBC,GACwB;AACxB,QAAMC,IAAMC,GAAQ,GAEdC,IAAS,MAAM,IAAI,QAEvB,CAACC,GAASC,MAAW;AACtB,UA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