-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwordpress-command-runners.ts
More file actions
503 lines (451 loc) · 19.2 KB
/
wordpress-command-runners.ts
File metadata and controls
503 lines (451 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import type { BrowserArtifact } from "./browser-artifacts.js"
import { promoteBrowserMetricsToBenchResults } from "./browser-metrics.js"
import { writePluginCheckArtifacts, writeThemeCheckArtifacts, type PluginCheckArtifact, type ThemeCheckArtifact } from "./check-artifacts.js"
import {
abilityInputFromArgs,
abilityPhpCode,
argValue,
benchRunCode,
booleanArg,
cleanWpCliOutput,
commaListArg,
CORE_PHPUNIT_RESULT_FILE,
corePhpunitRunCode,
jsonArrayArg,
jsonObjectArg,
nonNegativeIntegerArg,
normalizePhpCode,
normalizePluginCheckOutput,
normalizeThemeCheckOutput,
phpunitRunCode,
PLUGIN_PHPUNIT_RESULT_FILE,
positiveIntegerArg,
restRequestInputFromArgs,
restRequestPhpCode,
themeCheckRunCode,
} from "./commands.js"
import { bootstrapAbilityPhpCode, bootstrapPhpCode, phpCodeFromArgs } from "./php-bootstrap.js"
import { assertPlaygroundResponseOk, type PlaygroundRunResponse } from "./playground-command-errors.js"
import type { PlaygroundCliServer } from "./preview-server.js"
import { persistCorePhpunitResult, persistPluginPhpunitResult, persistVfsDiagnosticFileToHost, readCorePhpunitDiagnostic, readPluginPhpunitDiagnostic } from "./runtime-diagnostics.js"
import type { RuntimeWpCliBridge } from "./runtime-wp-cli-bridge.js"
import type { ExecutionSpec, MountSpec, RuntimeCreateSpec } from "@automattic/wp-codebox-core"
type RunPlaygroundCommand = (command: string, server: PlaygroundCliServer, options: { code: string } | { scriptPath: string }) => Promise<PlaygroundRunResponse>
type RunWpCliCommand = (server: PlaygroundCliServer, argv: string[]) => Promise<PlaygroundRunResponse>
type CreateRuntimeWpCliBridge = (server: PlaygroundCliServer) => Promise<RuntimeWpCliBridge>
const BROWSER_PROVIDER_PROXY_SCHEMA = "wp-codebox/browser-provider-proxy-request/v1"
const BROWSER_PROVIDER_PROXY_MAX_BYTES = 1_000_000
type BrowserProviderProxyMessage = {
schema: typeof BROWSER_PROVIDER_PROXY_SCHEMA
[key: string]: unknown
}
export async function runPhpCommand({
createRuntimeWpCliBridge,
runPlaygroundCommand,
runtimeSpec,
server,
spec,
}: {
createRuntimeWpCliBridge: CreateRuntimeWpCliBridge
runPlaygroundCommand: RunPlaygroundCommand
runtimeSpec: RuntimeCreateSpec
server: PlaygroundCliServer
spec: ExecutionSpec
}): Promise<string> {
const code = await phpCodeFromArgs(spec.args ?? [])
const bridge = argValue(spec.args ?? [], "wp-cli-bridge") === "1" ? await createRuntimeWpCliBridge(server) : undefined
let response: PlaygroundRunResponse
const removeProviderProxy = installBrowserProviderProxy(server)
try {
response = await runPlaygroundCommand("wordpress.run-php", server, { code: bootstrapPhpCode(runtimeSpec, code, spec.args ?? [], bridge) })
assertPlaygroundResponseOk("wordpress.run-php", response)
} finally {
await removeProviderProxy?.()
if (bridge) {
await bridge.close()
}
}
return response.text
}
function installBrowserProviderProxy(server: PlaygroundCliServer): (() => Promise<void>) | undefined {
if (!server.playground.onMessage) {
return undefined
}
const remove = server.playground.onMessage(async (data) => {
const message = parseBrowserProviderProxyMessage(data)
if (!message) {
return undefined
}
return JSON.stringify(await executeBrowserProviderProxyRequest(message))
})
return async () => {
const cleanup = await remove
if (typeof cleanup === "function") {
await cleanup()
}
}
}
function parseBrowserProviderProxyMessage(data: string): BrowserProviderProxyMessage | undefined {
if (data.length > BROWSER_PROVIDER_PROXY_MAX_BYTES) {
return undefined
}
let message: unknown
try {
message = JSON.parse(data)
} catch {
return undefined
}
if (!message || typeof message !== "object" || Array.isArray(message)) {
return undefined
}
return (message as { schema?: unknown }).schema === BROWSER_PROVIDER_PROXY_SCHEMA
? message as BrowserProviderProxyMessage
: undefined
}
async function executeBrowserProviderProxyRequest(message: BrowserProviderProxyMessage): Promise<Record<string, unknown>> {
const body = JSON.stringify(message)
if (body.length > BROWSER_PROVIDER_PROXY_MAX_BYTES) {
return browserProviderProxyError("wp_codebox_browser_provider_proxy_payload_too_large", "Browser provider proxy request is too large.")
}
const endpoint = browserProviderProxyEndpoint()
if (!endpoint || typeof fetch !== "function") {
return browserProviderProxyError("wp_codebox_browser_provider_proxy_unavailable", "Browser provider proxy endpoint is unavailable.")
}
try {
const response = await fetch(endpoint, {
method: "POST",
credentials: "same-origin",
headers: browserProviderProxyHeaders(),
body,
})
const json = await response.json().catch(() => undefined)
if (!response.ok) {
return browserProviderProxyError("wp_codebox_browser_provider_proxy_http_error", "Browser provider proxy request failed.", { status: response.status, response: json })
}
if (!json || typeof json !== "object" || Array.isArray(json)) {
return browserProviderProxyError("wp_codebox_browser_provider_proxy_malformed_response", "Browser provider proxy returned a malformed response.")
}
return json as Record<string, unknown>
} catch (error) {
return browserProviderProxyError("wp_codebox_browser_provider_proxy_fetch_failed", error instanceof Error ? error.message : "Browser provider proxy request failed.")
}
}
function browserProviderProxyEndpoint(): string | undefined {
const globalValue = globalThis as typeof globalThis & { location?: { origin?: string }; window?: { wpApiSettings?: { root?: string } }; wpApiSettings?: { root?: string } }
const root = globalValue.wpApiSettings?.root ?? globalValue.window?.wpApiSettings?.root
if (typeof root === "string" && root.length > 0) {
return new URL("wp-codebox/v1/browser-provider-request", root).toString()
}
if (typeof globalValue.location?.origin === "string" && globalValue.location.origin.length > 0) {
return new URL("/wp-json/wp-codebox/v1/browser-provider-request", globalValue.location.origin).toString()
}
return undefined
}
function browserProviderProxyHeaders(): Record<string, string> {
const globalValue = globalThis as typeof globalThis & { window?: { wpApiSettings?: { nonce?: string } }; wpApiSettings?: { nonce?: string } }
const nonce = globalValue.wpApiSettings?.nonce ?? globalValue.window?.wpApiSettings?.nonce
return {
"Content-Type": "application/json",
...(typeof nonce === "string" && nonce.length > 0 ? { "X-WP-Nonce": nonce } : {}),
}
}
function browserProviderProxyError(code: string, message: string, data: Record<string, unknown> = {}): Record<string, unknown> {
const redactedData = redactBrowserProviderProxyData(data)
return {
success: false,
error: {
code,
message,
...(redactedData && typeof redactedData === "object" && !Array.isArray(redactedData) ? redactedData as Record<string, unknown> : {}),
},
}
}
function redactBrowserProviderProxyData(value: unknown): unknown {
if (!value || typeof value !== "object") {
return value
}
if (Array.isArray(value)) {
return value.map(redactBrowserProviderProxyData)
}
return Object.fromEntries(Object.entries(value as Record<string, unknown>).map(([key, item]) => [
key,
/authorization|secret|token|password|credential|private_key|api_key|\bkey\b|\bvalue\b/i.test(key) ? "[redacted]" : redactBrowserProviderProxyData(item),
]))
}
export async function runPluginCheckCommand({
artifactRoot,
runWpCliCommand,
server,
spec,
}: {
artifactRoot: string
runWpCliCommand: RunWpCliCommand
server: PlaygroundCliServer
spec: ExecutionSpec
}): Promise<{ artifact: PluginCheckArtifact; output: string }> {
const args = spec.args ?? []
const pluginSlug = argValue(args, "plugin-slug")?.trim()
if (!pluginSlug) {
throw new Error("wordpress.plugin-check requires plugin-slug=<slug>")
}
if (!/^[a-z0-9][a-z0-9_-]*$/.test(pluginSlug)) {
throw new Error("wordpress.plugin-check plugin-slug must be a WordPress plugin slug")
}
const checkSlugs = commaListArg(args, "checks")
if (!server.playground.writeFile) {
throw new Error("wordpress.plugin-check requires a Playground backend with writeFile support")
}
const pluginPath = `/wordpress/wp-content/plugins/${pluginSlug}`
const existsResponse = await runWpCliCommand(server, ["plugin", "path", pluginSlug])
if (existsResponse.exitCode !== 0) {
throw new Error(`wordpress.plugin-check target plugin is not installed or mounted at ${pluginPath}`)
}
const rawResponse = await runWpCliCommand(server, [
"plugin",
"check",
pluginSlug,
"--format=strict-json",
"--fields=file,line,column,type,code,message,docs",
"--mode=new",
...(checkSlugs.length > 0 ? [`--checks=${checkSlugs.join(",")}`] : []),
])
const rawOutput = cleanWpCliOutput(rawResponse.text)
const normalized = normalizePluginCheckOutput(rawOutput, rawResponse.exitCode ?? 0, pluginSlug)
return {
artifact: await writePluginCheckArtifacts(artifactRoot, pluginSlug, rawOutput, normalized),
output: `${JSON.stringify(normalized, null, 2)}\n`,
}
}
export async function runThemeCheckCommand({
artifactRoot,
runPlaygroundCommand,
runWpCliArgv,
runtimeSpec,
server,
spec,
}: {
artifactRoot: string
runPlaygroundCommand: RunPlaygroundCommand
runWpCliArgv: RunWpCliCommand
runtimeSpec: RuntimeCreateSpec
server: PlaygroundCliServer
spec: ExecutionSpec
}): Promise<{ artifact: ThemeCheckArtifact; output: string }> {
const args = spec.args ?? []
const theme = argValue(args, "theme")?.trim()
if (!theme) {
throw new Error("wordpress.theme-check requires theme=<slug>")
}
if (!server.playground.writeFile) {
throw new Error("wordpress.theme-check requires a Playground backend with writeFile support")
}
if (!await themeCheckPluginInstalled(runPlaygroundCommand, server)) {
const install = await runWpCliArgv(server, ["plugin", "install", "theme-check"])
assertPlaygroundResponseOk("wordpress.theme-check", install)
}
const response = await runPlaygroundCommand("wordpress.theme-check", server, { code: bootstrapPhpCode(runtimeSpec, themeCheckRunCode(theme), []) })
assertPlaygroundResponseOk("wordpress.theme-check", response)
const raw = cleanWpCliOutput(response.text)
const normalized = normalizeThemeCheckOutput(raw, response.exitCode ?? 0, theme)
return {
artifact: await writeThemeCheckArtifacts(artifactRoot, theme, raw, normalized),
output: `${JSON.stringify(normalized, null, 2)}\n`,
}
}
export async function runAbilityCommand({
runPlaygroundCommand,
runtimeSpec,
server,
spec,
}: {
runPlaygroundCommand: RunPlaygroundCommand
runtimeSpec: RuntimeCreateSpec
server: PlaygroundCliServer
spec: ExecutionSpec
}): Promise<string> {
const name = argValue(spec.args ?? [], "name")?.trim()
if (!name) {
throw new Error("wordpress.ability requires name=<ability-name>")
}
const input = abilityInputFromArgs(spec.args ?? [])
const response = await runPlaygroundCommand("wordpress.ability", server, { code: bootstrapAbilityPhpCode(runtimeSpec, abilityPhpCode(name, input)) })
assertPlaygroundResponseOk("wordpress.ability", response)
return response.text
}
export async function runRestRequestCommand({
runPlaygroundCommand,
runtimeSpec,
server,
spec,
}: {
runPlaygroundCommand: RunPlaygroundCommand
runtimeSpec: RuntimeCreateSpec
server: PlaygroundCliServer
spec: ExecutionSpec
}): Promise<string> {
const input = restRequestInputFromArgs(spec.args ?? [])
const response = await runPlaygroundCommand("wordpress.rest-request", server, { code: bootstrapPhpCode(runtimeSpec, restRequestPhpCode(input), []) })
assertPlaygroundResponseOk("wordpress.rest-request", response)
return response.text
}
export async function runBenchCommand({
browserProbes,
createRuntimeWpCliBridge,
runPlaygroundCommand,
runtimeSpec,
server,
spec,
}: {
browserProbes: BrowserArtifact[]
createRuntimeWpCliBridge: CreateRuntimeWpCliBridge
runPlaygroundCommand: RunPlaygroundCommand
runtimeSpec: RuntimeCreateSpec
server: PlaygroundCliServer
spec: ExecutionSpec
}): Promise<string> {
const args = spec.args ?? []
const pluginSlug = argValue(args, "plugin-slug")?.trim()
if (!pluginSlug) {
throw new Error("wordpress.bench requires plugin-slug=<slug>")
}
const componentId = argValue(args, "component-id")?.trim() || pluginSlug
const iterations = positiveIntegerArg(args, "iterations", 3)
const warmupIterations = nonNegativeIntegerArg(args, "warmup", 1)
const dependencySlugs = commaListArg(args, "dependency-slugs")
const env = jsonObjectArg(args, "env-json")
const bootstrapFiles = jsonArrayArg(args, "bootstrap-files-json").filter((file): file is string => typeof file === "string")
const workloads = jsonArrayArg(args, "workloads-json")
const lifecycle = jsonObjectArg(args, "lifecycle-json")
const resetPolicy = jsonObjectArg(args, "reset-policy-json")
const bridge = benchWorkloadsUseWpCli([workloads, lifecycle]) ? await createRuntimeWpCliBridge(server) : undefined
let response: PlaygroundRunResponse
try {
response = await runPlaygroundCommand("wordpress.bench", server, {
code: bootstrapPhpCode(runtimeSpec, benchRunCode({ componentId, pluginSlug, iterations, warmupIterations, dependencySlugs, env, bootstrapFiles, workloads, lifecycle, resetPolicy, wpCliBridge: bridge }), []),
})
assertPlaygroundResponseOk("wordpress.bench", response)
} finally {
if (bridge) {
await bridge.close()
}
}
return promoteBrowserMetricsToBenchResults(response.text, browserProbes)
}
export async function runPhpunitCommand({
artifactRoot,
mounts,
runPlaygroundCommand,
server,
spec,
}: {
artifactRoot: string
mounts: MountSpec[]
runPlaygroundCommand: RunPlaygroundCommand
server: PlaygroundCliServer
spec: ExecutionSpec
}): Promise<string> {
const args = spec.args ?? []
const explicitCode = argValue(args, "code") || argValue(args, "code-file")
const pluginSlug = argValue(args, "plugin-slug")?.trim() || ""
const resultFile = PLUGIN_PHPUNIT_RESULT_FILE
const code = explicitCode ? await phpCodeFromArgs(args, "wordpress.phpunit") : normalizePhpCode(phpunitRunCode({
pluginSlug,
cwd: argValue(args, "cwd")?.trim() || `/wordpress/wp-content/plugins/${pluginSlug}`,
autoloadFile: argValue(args, "autoload-file")?.trim() || "/wp-codebox-vendor/autoload.php",
testsDir: argValue(args, "tests-dir")?.trim() || "/wp-codebox-vendor/wp-phpunit/wp-phpunit",
phpunitXml: argValue(args, "phpunit-xml")?.trim() || `/wordpress/wp-content/plugins/${pluginSlug}/phpunit.xml.dist`,
selectedTestFile: argValue(args, "test-file")?.trim() || "",
changedTestFiles: jsonArrayArg(args, "changed-tests-json"),
phpunitArgs: jsonArrayArg(args, "phpunit-args-json").filter((value): value is string => typeof value === "string"),
env: jsonObjectArg(args, "env-json"),
wpConfigDefines: jsonObjectArg(args, "wp-config-defines-json"),
dependencyMounts: commaListArg(args, "dependency-mounts"),
bootstrapFiles: jsonArrayArg(args, "bootstrap-files-json").filter((value): value is string => typeof value === "string"),
bootstrapMode: argValue(args, "bootstrap-mode")?.trim() || "managed",
projectBootstrap: argValue(args, "project-bootstrap")?.trim() || "",
multisite: booleanArg(args, "multisite"),
resultFile,
}))
if (!explicitCode && !pluginSlug) {
throw new Error("wordpress.phpunit requires plugin-slug=<slug> when code/code-file is not provided")
}
let response: PlaygroundRunResponse
try {
response = await runPlaygroundCommand("wordpress.phpunit", server, { code })
} catch (error) {
await persistPluginPhpunitResult(server, resultFile, artifactRoot)
await persistVfsDiagnosticFileToHost(server, resultFile, `/wordpress/wp-content/plugins/${pluginSlug}/.pg-test-result.txt`, mounts)
const structured = await readPluginPhpunitDiagnostic(server, resultFile)
if (structured) {
throw new Error(`wordpress.phpunit could not run: ${structured}`)
}
throw error
}
await persistPluginPhpunitResult(server, resultFile, artifactRoot)
await persistVfsDiagnosticFileToHost(server, resultFile, `/wordpress/wp-content/plugins/${pluginSlug}/.pg-test-result.txt`, mounts)
assertPlaygroundResponseOk("wordpress.phpunit", response)
return response.text
}
export async function runCorePhpunitCommand({
artifactRoot,
runPlaygroundCommand,
server,
spec,
}: {
artifactRoot: string
runPlaygroundCommand: RunPlaygroundCommand
server: PlaygroundCliServer
spec: ExecutionSpec
}): Promise<string> {
const args = spec.args ?? []
const explicitCode = argValue(args, "code") || argValue(args, "code-file")
// Write structured diagnostics to a sandbox-internal /tmp path rather than inside
// the (often read-only) core mount, so the result survives read-only mounts and a
// mid-require die() in core's bootstrap.php and can be read back from the VFS (#314).
const resultFile = CORE_PHPUNIT_RESULT_FILE
const code = explicitCode ? await phpCodeFromArgs(args, "wordpress.core-phpunit") : normalizePhpCode(corePhpunitRunCode({
coreRoot: argValue(args, "core-root")?.trim() || "/wordpress",
testsDir: argValue(args, "tests-dir")?.trim() || "/wordpress/tests/phpunit",
phpunitXml: argValue(args, "phpunit-xml")?.trim() || "/wordpress/tests/phpunit/phpunit.xml.dist",
selectedTestFile: argValue(args, "test-file")?.trim() || "",
changedTestFiles: jsonArrayArg(args, "changed-tests-json"),
autoloadFile: argValue(args, "autoload-file")?.trim() || "/wordpress/vendor/autoload.php",
wpConfigDefines: jsonObjectArg(args, "wp-config-defines-json"),
multisite: booleanArg(args, "multisite"),
resultFile,
}))
let response: PlaygroundRunResponse
try {
response = await runPlaygroundCommand("wordpress.core-phpunit", server, { code })
} catch (error) {
// Core's bootstrap can die() mid-require when the Composer test toolchain is
// absent, which surfaces here as a PlaygroundCommandCrashError with empty
// output. Recover the structured diagnostics the PHP shutdown handler flushed
// to the result file and re-throw a clear, actionable error instead (#314).
await persistCorePhpunitResult(server, resultFile, artifactRoot)
const structured = await readCorePhpunitDiagnostic(server, resultFile)
if (structured) {
throw new Error(`wordpress.core-phpunit could not run: ${structured}`)
}
throw error
}
await persistCorePhpunitResult(server, resultFile, artifactRoot)
assertPlaygroundResponseOk("wordpress.core-phpunit", response)
return response.text
}
function benchWorkloadsUseWpCli(value: unknown): boolean {
if (Array.isArray(value)) {
return value.some(benchWorkloadsUseWpCli)
}
if (!value || typeof value !== "object") {
return false
}
const record = value as { type?: unknown; run?: unknown }
return record.type === "wp-cli" || benchWorkloadsUseWpCli(record.run)
}
async function themeCheckPluginInstalled(runPlaygroundCommand: RunPlaygroundCommand, server: PlaygroundCliServer): Promise<boolean> {
const response = await runPlaygroundCommand("wordpress.theme-check", server, {
code: "<?php echo file_exists('/wordpress/wp-content/plugins/theme-check/theme-check.php') ? 'yes' : 'no';",
})
return response.text.trim() === "yes"
}