-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplayground-runtime.ts
More file actions
1346 lines (1197 loc) · 53.1 KB
/
Copy pathplayground-runtime.ts
File metadata and controls
1346 lines (1197 loc) · 53.1 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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { randomBytes } from "node:crypto"
import { mkdir, readFile, realpath, writeFile } from "node:fs/promises"
import type { IncomingMessage, ServerResponse } from "node:http"
import { dirname, join, resolve } from "node:path"
import { HostToolRegistry, RUNTIME_EPISODE_OBSERVATION_SCHEMA, RUNTIME_EPISODE_SNAPSHOT_SCHEMA, assertRuntimeCommandAllowed, commandAgentRunResultJson, createCommandAgentRunResult, createHostToolRegistry, createRuntimeCommandResultEnvelope, parseCommandAgentRunRequest, resolveCommandPath, runtimeEpisodeDigest } from "@automattic/wp-codebox-core"
import { now, sha256 } from "@automattic/wp-codebox-core/internals"
import { recipeCommandDefinitions } from "@automattic/wp-codebox-core/contracts"
import { browserReviewSummary as browserArtifactReviewSummary, type BrowserArtifact } from "./browser-artifacts.js"
import { normalizeBrowserStorageStatePayload, wordpressFixtureUserStorageStatePhpCode, type WordPressFixtureUserSpec } from "./browser-auth-storage-state.js"
import { isBrowserCommandArtifactError, runBrowserActionsCommand, runBrowserProbeCommand, runBrowserScenarioCommand, runEditorActionsCommand, runEditorCanvasProbeCommand, runEditorOpenCommand, runHtmlCaptureCommand, runVisualCompareCommand, wordpressAdminAuthCookiePhpCode } from "./browser-command-runners.js"
import type { PluginCheckArtifact, ThemeCheckArtifact } from "./check-artifacts.js"
import { executePlaygroundCommand } from "./command-router.js"
import { firstCommandWordPressAdminAuthRequirement } from "./command-auth-requirements.js"
import { cleanWpCliOutput, shellArgv, wpCliCommandFromArgs, wpCliPhpScript } from "./commands.js"
import { bootstrapPhpCode } from "./php-bootstrap.js"
import { observeHttpResponse as observeHttpResponseArtifact, observeWordPressState as observeWordPressStateArtifact } from "./observation-artifacts.js"
import { PlaygroundCommandCrashError, assertPlaygroundResponseOk, errorMessage, type PlaygroundRunResponse } from "./playground-command-errors.js"
import { startPlaygroundCliServer, type PlaygroundCliModule } from "./playground-cli-runner.js"
import type { PlaygroundCliServer } from "./preview-server.js"
import { collectPlaygroundArtifacts } from "./runtime-artifact-helpers.js"
import { materializePlaygroundMountsFromVfs } from "./mount-materialization.js"
import { runAbilityCommand, runBenchCommand, runCorePhpunitCommand, runPhpCommand, runPhpunitCommand, runPluginCheckCommand, runRestRequestCommand, runThemeCheckCommand } from "./wordpress-command-runners.js"
import { PlaygroundSnapshotRestoreError, contentDigest, mountsFromSnapshot, runtimeSnapshotExportPayload, runtimeSnapshotExportPhp, runtimeSnapshotPayload, runtimeSnapshotRestorePhp, runtimeSpecFromSnapshot, snapshotDigest, type RuntimeSnapshotArtifact, type RuntimeSnapshotExportOptions } from "./runtime-snapshot.js"
import { createRuntimeWpCliBridge, type RuntimeWpCliBridge } from "./runtime-wp-cli-bridge.js"
import { writeReplayExportPackage } from "./replayable-wordpress-site-bundle.js"
import { preflightPhpWasmRuntimeAssets } from "./php-wasm-preflight.js"
import { previewReviewerAccess } from "./preview-reviewer-access.js"
import type {
ArtifactBundle,
ArtifactManifestFile,
ArtifactPreview,
ArtifactReviewerAuthBootstrap,
ArtifactSpec,
ExecutionResult,
ExecutionSpec,
LifecycleEvent,
MountSpec,
ObservationResult,
ObservationSpec,
Runtime,
RuntimeBackend,
RuntimeBackendProvider,
BrowserStartupProgressEvent,
RuntimeCreateSpec,
RuntimeRestoreSpec,
RuntimeEpisodeTraceRef,
RuntimeInfo,
RuntimeCommandResultEnvelope,
Snapshot,
} from "@automattic/wp-codebox-core"
function id(prefix: string): string {
return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
}
function commandExitCode(envelope: RuntimeCommandResultEnvelope | undefined): number {
return envelope?.status === "error" ? 1 : 0
}
function commandEnvelopeStdout(envelope: RuntimeCommandResultEnvelope): string {
if (typeof envelope.stdout === "string") {
return envelope.stdout
}
return envelope.json === undefined ? "" : `${JSON.stringify(envelope.json, null, 2)}\n`
}
interface ReviewerAuthBootstrapRecord {
expiresAt: string
redirectUrl: string
serverUrl: string
userId: number
}
function reviewerAuthRedirectUrl(url: string | undefined, serverUrl: string): string | undefined {
if (!url) {
return undefined
}
try {
return new URL(url, serverUrl).toString()
} catch {
return undefined
}
}
function isLocalPreviewUrl(url: string): boolean {
try {
const hostname = new URL(url).hostname.toLowerCase().replace(/^\[|\]$/g, "")
return hostname === "localhost" || hostname === "0.0.0.0" || hostname === "127.0.0.1" || hostname === "::1" || hostname.startsWith("127.")
} catch {
return false
}
}
function reviewerAuthSetCookieHeader(cookie: { name?: string; value?: string; path?: string; expires?: number; httpOnly?: boolean; secure?: boolean; sameSite?: "Lax" }): string {
const parts = [
`${String(cookie.name ?? "")}=${String(cookie.value ?? "")}`,
`Path=${typeof cookie.path === "string" && cookie.path.length > 0 ? cookie.path : "/"}`,
`Expires=${new Date((typeof cookie.expires === "number" ? cookie.expires : Math.floor(Date.now() / 1000) + 3600) * 1000).toUTCString()}`,
"SameSite=Lax",
]
if (cookie.httpOnly !== false) {
parts.push("HttpOnly")
}
if (cookie.secure === true) {
parts.push("Secure")
}
return parts.join("; ")
}
export class PlaygroundRuntimeBackend implements RuntimeBackend {
readonly kind = "wordpress-playground" as const
constructor(private readonly options: PlaygroundRuntimeBackendOptions = {}) {}
async create(spec: RuntimeCreateSpec): Promise<Runtime> {
return PlaygroundRuntime.create(spec, this.options)
}
async restore(snapshot: Snapshot, spec: RuntimeRestoreSpec = {}): Promise<Runtime> {
return PlaygroundRuntime.restore(snapshot, spec, this.options)
}
}
export interface PlaygroundRuntimeBackendOptions {
hostTools?: HostToolRegistry
cliModule?: PlaygroundCliModule
}
class PlaygroundRuntime implements Runtime {
private status: RuntimeInfo["status"] = "created"
private readonly runtimeId = id("runtime")
private readonly createdAt = now()
private readonly mounts: MountSpec[] = []
private readonly commands: ExecutionResult[] = []
private readonly observations: ObservationResult[] = []
private readonly snapshots: Snapshot[] = []
private readonly events: LifecycleEvent[] = []
private readonly browserProbes: BrowserArtifact[] = []
private readonly pluginChecks: PluginCheckArtifact[] = []
private readonly themeChecks: ThemeCheckArtifact[] = []
private readonly artifactRoot: string
private readonly hostTools?: HostToolRegistry
private cliServerPromise?: Promise<PlaygroundCliServer>
private readonly activeExecutionAbortControllers = new Set<AbortController>()
private activeExecutionSignal?: AbortSignal
private reviewerAuthBootstrapRouteRegistered = false
private readonly reviewerAuthBootstraps = new Map<string, ReviewerAuthBootstrapRecord>()
private constructor(private readonly spec: RuntimeCreateSpec, private readonly backendOptions: PlaygroundRuntimeBackendOptions = {}) {
this.artifactRoot = resolve(spec.artifactsDirectory ?? "artifacts", this.runtimeId)
this.hostTools = spec.hostTools instanceof HostToolRegistry
? spec.hostTools
: Array.isArray(spec.hostTools)
? createHostToolRegistry(spec.hostTools)
: backendOptions.hostTools
}
static async create(spec: RuntimeCreateSpec, options: PlaygroundRuntimeBackendOptions = {}): Promise<PlaygroundRuntime> {
const phpWasmRuntimeAssetPreflight = await preflightPhpWasmRuntimeAssets({ phpVersion: spec.environment.phpVersion })
const runtime = new PlaygroundRuntime({
...spec,
metadata: {
...(spec.metadata ?? {}),
phpWasmRuntimeAssetPreflight,
},
}, options)
await mkdir(runtime.artifactRoot, { recursive: true })
runtime.recordEvent("runtime.created", {
backend: "wordpress-playground",
environment: spec.environment,
policy: spec.policy,
hostTools: runtime.hostTools?.list() ?? [],
phpWasmRuntimeAssetPreflight,
})
return runtime
}
static async restore(snapshot: Snapshot, spec: RuntimeRestoreSpec = {}, options: PlaygroundRuntimeBackendOptions = {}): Promise<PlaygroundRuntime> {
const payload = await runtimeSnapshotPayload(snapshot)
if (payload.compatibility.backend !== "wordpress-playground") {
throw new PlaygroundSnapshotRestoreError(`Snapshot backend is not compatible with WordPress Playground: ${payload.compatibility.backend}`)
}
const runtimeSpec = spec.runtime ?? runtimeSpecFromSnapshot(snapshot)
const runtime = await PlaygroundRuntime.create(runtimeSpec, options)
for (const mount of spec.mounts ?? mountsFromSnapshot(snapshot)) {
await runtime.mount(mount)
}
await runtime.restoreSnapshotPayload(payload)
runtime.recordEvent("runtime.snapshot.restored", {
id: snapshot.id,
createdAt: snapshot.createdAt,
snapshotSchema: snapshot.schema ?? null,
})
return runtime
}
async info(): Promise<RuntimeInfo> {
const previewUrl = await this.currentPreviewUrl()
return {
id: this.runtimeId,
backend: "wordpress-playground",
environment: this.spec.environment,
createdAt: this.createdAt,
status: this.status,
...(previewUrl ? { previewUrl } : {}),
}
}
async mount(spec: MountSpec): Promise<void> {
if (this.status === "destroyed") {
throw new Error("Cannot mount into a destroyed runtime")
}
const mount = {
...spec,
source: await realpath(spec.source),
}
this.mounts.push(mount)
this.recordEvent("runtime.mounted", { mount })
}
async execute(spec: ExecutionSpec): Promise<ExecutionResult> {
assertRuntimeCommandAllowed(spec.command, this.spec.policy)
const startedAt = now()
const commandId = id("command")
this.recordEvent("runtime.command.started", {
id: commandId,
command: spec.command,
args: spec.args ?? [],
cwd: spec.cwd ?? null,
timeoutMs: spec.timeoutMs ?? null,
})
const abortController = new AbortController()
this.activeExecutionAbortControllers.add(abortController)
this.activeExecutionSignal = abortController.signal
try {
const output = await executePlaygroundCommand(this, spec, this.hostTools)
const envelope = typeof output === "string" ? undefined : output
const result: ExecutionResult = {
id: commandId,
command: spec.command,
args: spec.args ?? [],
exitCode: commandExitCode(envelope),
stdout: typeof output === "string" ? output : commandEnvelopeStdout(output),
stderr: envelope?.stderr ?? "",
...(envelope ? { result: envelope } : {}),
startedAt,
finishedAt: now(),
}
this.commands.push(result)
this.recordEvent("runtime.command.finished", {
id: result.id,
command: result.command,
exitCode: result.exitCode,
startedAt: result.startedAt,
finishedAt: result.finishedAt,
})
return result
} catch (error) {
const result: ExecutionResult = {
id: commandId,
command: spec.command,
args: spec.args ?? [],
exitCode: 1,
stdout: "",
stderr: errorMessage(error),
startedAt,
finishedAt: now(),
}
this.commands.push(result)
this.recordEvent("runtime.command.finished", {
id: result.id,
command: result.command,
exitCode: result.exitCode,
startedAt: result.startedAt,
finishedAt: result.finishedAt,
})
throw error
} finally {
this.activeExecutionAbortControllers.delete(abortController)
if (this.activeExecutionSignal === abortController.signal) {
this.activeExecutionSignal = undefined
}
}
}
async observe(spec: ObservationSpec): Promise<ObservationResult> {
const observationId = id("observation")
const observedAt = now()
const observed = await this.observeData(spec, observationId)
const observation: ObservationResult = {
schema: RUNTIME_EPISODE_OBSERVATION_SCHEMA,
id: observationId,
type: spec.type,
data: observed.data,
observedAt,
...(observed.artifactRefs.length > 0 ? { artifactRefs: observed.artifactRefs } : {}),
...(observed.artifactManifestFiles.length > 0 ? { artifactManifestFiles: observed.artifactManifestFiles } : {}),
}
observation.digest = runtimeEpisodeDigest({
schema: RUNTIME_EPISODE_OBSERVATION_SCHEMA,
type: observation.type,
data: observation.data,
observedAt: observation.observedAt,
artifactRefs: observation.artifactRefs ?? [],
})
this.observations.push(observation)
this.recordEvent("runtime.observed", {
type: observation.type,
observedAt: observation.observedAt,
})
return observation
}
async snapshot(options: RuntimeSnapshotExportOptions = {}): Promise<Snapshot> {
const snapshotId = id("snapshot")
const createdAt = now()
const payload = await this.captureRuntimeSnapshotArtifact(snapshotId, createdAt, options)
const artifactPath = `files/runtime-snapshots/${snapshotId}.json`
const absoluteArtifactPath = join(this.artifactRoot, artifactPath)
const artifactJson = `${JSON.stringify(payload, null, 2)}\n`
await mkdir(dirname(absoluteArtifactPath), { recursive: true })
await writeFile(absoluteArtifactPath, artifactJson)
const artifactDigest = { algorithm: "sha256" as const, value: sha256(Buffer.from(artifactJson, "utf8")) }
const snapshot: Snapshot = {
schema: RUNTIME_EPISODE_SNAPSHOT_SCHEMA,
id: snapshotId,
createdAt,
semantics: "runtime-state-artifact",
metadata: {
runtime: await this.info(),
mounts: this.mounts,
compatibility: payload.compatibility,
artifact: {
schema: payload.schema,
path: artifactPath,
absolutePath: absoluteArtifactPath,
digest: artifactDigest,
},
hashes: payload.hashes,
summary: {
databaseTables: payload.database.tables.length,
wpContentFiles: payload.files.length,
},
payload,
},
artifactRefs: [
{
kind: "runtime-snapshot-artifact",
id: snapshotId,
path: artifactPath,
digest: artifactDigest,
},
],
}
snapshot.digest = snapshotDigest(snapshot)
this.recordEvent("runtime.snapshot.created", {
id: snapshot.id,
createdAt: snapshot.createdAt,
artifactPath,
})
this.snapshots.push(snapshot)
return snapshot
}
private async captureRuntimeSnapshotArtifact(snapshotId: string, createdAt: string, options: RuntimeSnapshotExportOptions = {}): Promise<RuntimeSnapshotArtifact> {
const server = await this.bootPlayground()
const response = await this.runPlaygroundCommand("runtime.snapshot", server, {
code: bootstrapPhpCode(this.spec, runtimeSnapshotExportPhp({ ...options, excludedWpContentPaths: [...this.snapshotExcludedWpContentPaths(), ...(options.excludedWpContentPaths ?? [])] }), []),
})
assertPlaygroundResponseOk("runtime.snapshot", response)
const captured = await runtimeSnapshotExportPayload(server, response.text)
const databaseDigest = contentDigest(captured.database)
const filesDigest = contentDigest(captured.files.map((file) => ({ path: file.path, sha256: file.sha256, bytes: file.bytes })))
return {
schema: "wp-codebox/wordpress-runtime-snapshot/v1",
version: 1,
id: snapshotId,
createdAt,
...captured,
metadata: {
...captured.metadata,
runtime: await this.info(),
mounts: this.mounts,
mountedInputs: this.mounts.map((mount) => ({ source: mount.source, target: mount.target, mode: mount.mode, type: mount.type })),
},
hashes: {
database: databaseDigest,
files: filesDigest,
},
}
}
private snapshotExcludedWpContentPaths(): string[] {
return this.mounts.flatMap((mount) => {
if (mount.mode !== "readonly") {
return []
}
const relativePath = wpContentRelativePath(mount.target)
return relativePath ? [relativePath] : []
})
}
private async restoreSnapshotPayload(payload: RuntimeSnapshotArtifact): Promise<void> {
const runtime = await this.info()
if (runtime.backend !== payload.compatibility.backend) {
throw new PlaygroundSnapshotRestoreError(`Snapshot backend ${payload.compatibility.backend} cannot be restored into ${runtime.backend}.`)
}
const response = await this.runPlaygroundCommand("runtime.snapshot.restore", await this.bootPlayground(), {
code: bootstrapPhpCode(this.spec, runtimeSnapshotRestorePhp(payload), []),
})
assertPlaygroundResponseOk("runtime.snapshot.restore", response)
}
async collectArtifacts(spec: ArtifactSpec = {}): Promise<ArtifactBundle> {
if (this.status !== "destroyed" && this.cliServerPromise) {
const materialization = await materializePlaygroundMountsFromVfs(await this.cliServerPromise, this.mounts)
if (materialization.materialized > 0 || materialization.deleted > 0 || materialization.skipped > 0) {
this.recordEvent("runtime.mounts.materialized", { ...materialization })
}
}
return collectPlaygroundArtifacts({
artifactRoot: this.artifactRoot,
runtimeId: this.runtimeId,
createdAt: this.createdAt,
spec: this.spec,
mounts: this.mounts,
commands: this.commands,
observations: this.observations,
snapshots: this.snapshots,
events: this.events,
info: () => this.info(),
previewInfo: (createdAt, previewHoldSeconds, commands) => this.previewInfo(createdAt, previewHoldSeconds, commands),
recordArtifactsCollected: (bundleId, createdAt, artifactSpec) => this.recordEvent("runtime.artifacts.collected", {
id: bundleId,
directory: this.artifactRoot,
createdAt,
spec: artifactSpec,
}),
browserProbes: this.browserProbes,
pluginChecks: this.pluginChecks,
themeChecks: this.themeChecks,
}, spec)
}
async destroy(): Promise<void> {
if (this.status === "destroyed") {
return
}
this.status = "destroyed"
for (const controller of this.activeExecutionAbortControllers) {
controller.abort()
}
try {
const cliServer = await this.cliServerPromise
await cliServer?.[Symbol.asyncDispose]()
} finally {
this.recordEvent("runtime.destroyed", { runtimeId: this.runtimeId })
}
}
private async currentPreviewUrl(): Promise<string | undefined> {
if (this.status === "destroyed") {
return undefined
}
if (!this.cliServerPromise) {
return undefined
}
try {
const server = await this.cliServerPromise
return this.spec.preview?.publicUrl ?? server.serverUrl
} catch {
return undefined
}
}
private async previewInfo(createdAt: string, holdSeconds = 0, commands: ExecutionResult[] = []): Promise<ArtifactPreview | undefined> {
if (this.status === "destroyed") {
return undefined
}
const server = await this.bootPlayground()
const normalizedHoldSeconds = Math.max(0, Math.floor(holdSeconds))
const expiresAt = normalizedHoldSeconds > 0 ? new Date(Date.now() + normalizedHoldSeconds * 1000).toISOString() : undefined
const publicUrl = this.spec.preview?.publicUrl
const siteUrl = this.spec.preview?.siteUrl
const preview: ArtifactPreview = {
url: publicUrl ?? server.serverUrl,
...(publicUrl ? { publicUrl, localUrl: server.serverUrl } : {}),
...(siteUrl ? { siteUrl } : {}),
status: normalizedHoldSeconds > 0 ? "available" : "expired-on-completion",
lifecycle: normalizedHoldSeconds > 0 ? "held-after-run" : "destroyed-on-completion",
source: publicUrl ? "public-url-override" : "live-playground",
createdAt,
...(expiresAt ? { expiresAt, holdSeconds: normalizedHoldSeconds } : {}),
}
const reviewerAuthBootstrap = expiresAt ? this.createReviewerAuthBootstrap(server, preview, expiresAt, commands) : undefined
const previewWithBootstrap = {
...preview,
...(reviewerAuthBootstrap ? { reviewerAuthBootstrap } : {}),
}
return {
...previewWithBootstrap,
reviewerAccess: previewReviewerAccess(previewWithBootstrap),
}
}
private createReviewerAuthBootstrap(server: PlaygroundCliServer, preview: ArtifactPreview, expiresAt: string, commands: ExecutionResult[]): ArtifactReviewerAuthBootstrap | undefined {
const authRequirement = firstCommandWordPressAdminAuthRequirement(commands)
if (!authRequirement || !server.previewRoutes || !isLocalPreviewUrl(preview.localUrl ?? preview.url)) {
return undefined
}
this.registerReviewerAuthBootstrapRoute(server)
const token = randomBytes(24).toString("base64url")
const userId = authRequirement.userId
const redirectUrl = reviewerAuthRedirectUrl(authRequirement.redirectUrl, server.serverUrl) ?? server.serverUrl
this.reviewerAuthBootstraps.set(token, {
expiresAt,
redirectUrl,
serverUrl: server.serverUrl,
userId,
})
const bootstrapUrl = new URL("/__wp-codebox/reviewer-auth-bootstrap", server.serverUrl)
bootstrapUrl.searchParams.set("token", token)
return {
schema: "wp-codebox/reviewer-auth-bootstrap/v1",
kind: "local-wordpress-admin-fixture",
reviewerSafe: true,
bootstrapUrl: bootstrapUrl.toString(),
redirectUrl,
expiresAt,
evidence: {
command: authRequirement.command.command,
auth: "wordpress-admin",
userId,
},
}
}
private registerReviewerAuthBootstrapRoute(server: PlaygroundCliServer): void {
if (this.reviewerAuthBootstrapRouteRegistered || !server.previewRoutes) {
return
}
this.reviewerAuthBootstrapRouteRegistered = true
server.previewRoutes.add((incoming, outgoing) => this.handleReviewerAuthBootstrapRequest(server, incoming, outgoing))
}
private async handleReviewerAuthBootstrapRequest(server: PlaygroundCliServer, incoming: IncomingMessage, outgoing: ServerResponse): Promise<boolean> {
const requestUrl = new URL(incoming.url ?? "/", server.serverUrl)
if (requestUrl.pathname !== "/__wp-codebox/reviewer-auth-bootstrap") {
return false
}
const token = requestUrl.searchParams.get("token") ?? ""
const record = this.reviewerAuthBootstraps.get(token)
if (!record || Date.parse(record.expiresAt) <= Date.now()) {
this.writeReviewerAuthBootstrapResponse(outgoing, 410, "Reviewer auth bootstrap expired or unavailable.\n")
return true
}
const response = await this.runPlaygroundCommand("reviewer-auth-bootstrap.auth", server, { code: bootstrapPhpCode(this.spec, wordpressAdminAuthCookiePhpCode([record.serverUrl], record.userId), []) })
assertPlaygroundResponseOk("reviewer-auth-bootstrap.auth", response)
const cookies = JSON.parse(cleanWpCliOutput(response.text)) as Array<{ name?: string; value?: string; path?: string; expires?: number; httpOnly?: boolean; secure?: boolean; sameSite?: "Lax" }>
outgoing.writeHead(302, {
"location": record.redirectUrl,
"cache-control": "no-store",
"set-cookie": cookies.map((cookie) => reviewerAuthSetCookieHeader(cookie)),
})
outgoing.end()
return true
}
private writeReviewerAuthBootstrapResponse(outgoing: ServerResponse, status: number, message: string): void {
const body = Buffer.from(message, "utf8")
outgoing.writeHead(status, {
"content-type": "text/plain; charset=utf-8",
"content-length": String(body.byteLength),
"cache-control": "no-store",
})
outgoing.end(body)
}
private recordEvent(type: LifecycleEvent["type"], data?: Record<string, unknown>): LifecycleEvent {
const event: LifecycleEvent = {
id: id("event"),
type,
timestamp: now(),
...(data ? { data } : {}),
}
this.events.push(event)
return event
}
async runBrowserProbe(spec: ExecutionSpec): Promise<string> {
const server = await this.bootPlayground()
let result: Awaited<ReturnType<typeof runBrowserProbeCommand>>
try {
result = await runBrowserProbeCommand({ abortSignal: this.activeExecutionSignal, artifactRoot: this.artifactRoot, runtimeSpec: this.spec, runPlaygroundCommand: (command, targetServer, options) => this.runPlaygroundCommand(command, targetServer, options), server, spec, onProgress: (event) => this.recordEvent("runtime.browser-command-progress", { ...event, specCommand: spec.command }) })
} catch (error) {
if (isBrowserCommandArtifactError(error)) {
this.browserProbes.push(error.artifact)
}
throw error
}
this.browserProbes.push(...(result.artifacts ?? [result.artifact]))
return result.output
}
async runHtmlCapture(spec: ExecutionSpec): Promise<string> {
const server = await this.bootPlayground()
let result: Awaited<ReturnType<typeof runHtmlCaptureCommand>>
try {
result = await runHtmlCaptureCommand({ artifactRoot: this.artifactRoot, runtimeSpec: this.spec, runPlaygroundCommand: (command, targetServer, options) => this.runPlaygroundCommand(command, targetServer, options), server, spec })
} catch (error) {
if (isBrowserCommandArtifactError(error)) {
this.browserProbes.push(error.artifact)
}
throw error
}
this.browserProbes.push(result.artifact)
return result.output
}
async runEditorCanvasProbe(spec: ExecutionSpec): Promise<string> {
const server = await this.bootPlayground()
let result: Awaited<ReturnType<typeof runEditorCanvasProbeCommand>>
try {
result = await runEditorCanvasProbeCommand({ artifactRoot: this.artifactRoot, runtimeSpec: this.spec, server, spec })
} catch (error) {
if (isBrowserCommandArtifactError(error)) {
this.browserProbes.push(error.artifact)
}
throw error
}
this.browserProbes.push(result.artifact)
return result.output
}
async runBrowserActions(spec: ExecutionSpec): Promise<string> {
const server = await this.bootPlayground()
let result: Awaited<ReturnType<typeof runBrowserActionsCommand>>
try {
result = await runBrowserActionsCommand({ artifactRoot: this.artifactRoot, runtimeSpec: this.spec, runPlaygroundCommand: (command, targetServer, options) => this.runPlaygroundCommand(command, targetServer, options), server, spec, onProgress: (event) => this.recordEvent("runtime.browser-command-progress", { ...event, specCommand: spec.command }) })
} catch (error) {
if (isBrowserCommandArtifactError(error)) {
this.browserProbes.push(error.artifact)
}
throw error
}
this.browserProbes.push(result.artifact)
return result.output
}
async runBrowserScenario(spec: ExecutionSpec): Promise<string> {
const server = await this.bootPlayground()
let result: Awaited<ReturnType<typeof runBrowserScenarioCommand>>
try {
result = await runBrowserScenarioCommand({ artifactRoot: this.artifactRoot, runtimeSpec: this.spec, runPlaygroundCommand: (command, targetServer, options) => this.runPlaygroundCommand(command, targetServer, options), server, spec })
} catch (error) {
if (isBrowserCommandArtifactError(error)) {
this.browserProbes.push(error.artifact)
}
throw error
}
this.browserProbes.push(result.artifact)
return result.output
}
async runVisualCompare(spec: ExecutionSpec): Promise<string> {
const server = await this.bootPlayground()
let result: Awaited<ReturnType<typeof runVisualCompareCommand>>
try {
result = await runVisualCompareCommand({ artifactRoot: this.artifactRoot, runtimeSpec: this.spec, server, spec })
} catch (error) {
if (isBrowserCommandArtifactError(error)) {
this.browserProbes.push(error.artifact)
}
throw error
}
this.browserProbes.push(result.artifact)
return result.output
}
async runEditorOpen(spec: ExecutionSpec): Promise<string> {
const server = await this.bootPlayground()
const result = await runEditorOpenCommand({
artifactRoot: this.artifactRoot,
runPlaygroundCommand: (command, targetServer, options) => this.runPlaygroundCommand(command, targetServer, options),
runtimeSpec: this.spec,
server,
spec,
})
this.browserProbes.push(result.artifact)
return result.output
}
async runEditorActions(spec: ExecutionSpec): Promise<string> {
const server = await this.bootPlayground()
let result: Awaited<ReturnType<typeof runEditorActionsCommand>>
try {
result = await runEditorActionsCommand({
artifactRoot: this.artifactRoot,
runPlaygroundCommand: (command, targetServer, options) => this.runPlaygroundCommand(command, targetServer, options),
runtimeSpec: this.spec,
server,
spec,
})
} catch (error) {
if (isBrowserCommandArtifactError(error)) {
this.browserProbes.push(error.artifact)
}
throw error
}
this.browserProbes.push(result.artifact)
return result.output
}
async runPhp(spec: ExecutionSpec): Promise<string> {
const server = await this.bootPlayground()
return runPhpCommand({
createRuntimeWpCliBridge: (targetServer) => this.createRuntimeWpCliBridge(targetServer),
runPlaygroundCommand: (command, targetServer, options) => this.runPlaygroundCommand(command, targetServer, options),
runtimeSpec: this.spec,
server,
spec,
})
}
async runCommandAgent(spec: ExecutionSpec): Promise<RuntimeCommandResultEnvelope> {
const request = parseCommandAgentRunRequest(spec.args ?? [])
assertRuntimeCommandAllowed(request.command, this.spec.policy)
const execution = await this.execute({
command: request.command,
args: request.args,
cwd: spec.cwd,
timeoutMs: spec.timeoutMs,
})
const result = createCommandAgentRunResult({
request,
execution,
runtime: await this.info(),
environment: {
runtimeEnvNames: Object.keys(this.spec.runtimeEnv ?? {}),
secretEnvNames: Object.keys(this.spec.secretEnv ?? {}),
},
})
return createRuntimeCommandResultEnvelope({
status: result.exitCode === 0 ? "ok" : "error",
stdout: commandAgentRunResultJson(result),
stderr: result.stderr,
json: result,
...(result.exitCode === 0 ? {} : { error: { code: "command-agent-run-target-failed", message: `Target command failed: ${result.target.command}` } }),
diagnostics: result.diagnostics,
artifactRefs: execution.result?.artifactRefs,
})
}
async runWpCli(spec: ExecutionSpec): Promise<string> {
const server = await this.bootPlayground()
const command = wpCliCommandFromArgs(spec.args ?? [])
const argv = shellArgv(command)
if (argv[0] === "wp") {
argv.shift()
}
if (argv.length === 0) {
throw new Error("wordpress.wp-cli requires a non-empty command")
}
if (!server.playground.writeFile) {
throw new Error("wordpress.wp-cli requires a Playground backend with writeFile support")
}
const scriptPath = `/tmp/wp-codebox-wp-cli-${this.commands.length}.php`
await server.playground.writeFile(scriptPath, wpCliPhpScript(argv))
const response = await this.runPlaygroundCommand("wordpress.wp-cli", server, { scriptPath })
assertPlaygroundResponseOk("wordpress.wp-cli", response)
return cleanWpCliOutput(response.text)
}
async runExportBrowserStorageState(spec: ExecutionSpec): Promise<string> {
const server = await this.bootPlayground()
const outputDirectory = storageStateOutputDirectory(this.artifactRoot, stringArg(spec.args ?? [], "output-dir"))
const providedStorageState = await storageStatePayloadFromArgs(spec.args ?? [])
const payload = providedStorageState?.payload ?? await this.exportWordPressFixtureUserStorageState(spec, server)
const normalized = normalizeBrowserStorageStatePayload(payload, providedStorageState?.source ?? "inline")
if (normalized.summary.status !== "ready") {
throw new Error(`wordpress.export-browser-storage-state returned unsupported storage state: ${JSON.stringify(normalized.summary.diagnostics)}`)
}
const envelope = payload && typeof payload === "object" && !Array.isArray(payload) ? payload as Record<string, unknown> : {}
const exportedUser = envelope.user && typeof envelope.user === "object" && !Array.isArray(envelope.user) ? envelope.user as Record<string, unknown> : undefined
const storageStatePath = join(outputDirectory, "storage-state.json")
const summaryPath = join(outputDirectory, "summary.json")
const storageStateArtifactPath = artifactRelativePath(this.artifactRoot, storageStatePath)
const summaryArtifactPath = artifactRelativePath(this.artifactRoot, summaryPath)
const storageStateJson = `${JSON.stringify(normalized.storageState, null, 2)}\n`
const summary = {
schema: "wp-codebox/browser-storage-state-export-summary/v1",
status: "exported",
storageState: normalized.summary,
...(exportedUser ? { user: storageStateUserSummary(exportedUser) } : {}),
artifacts: {
storageState: storageStateArtifactPath,
summary: summaryArtifactPath,
},
}
const summaryJson = `${JSON.stringify(summary, null, 2)}\n`
await mkdir(outputDirectory, { recursive: true })
await writeFile(storageStatePath, storageStateJson)
await writeFile(summaryPath, summaryJson)
const storageStateDigest = { algorithm: "sha256" as const, value: sha256(Buffer.from(storageStateJson, "utf8")) }
const summaryDigest = { algorithm: "sha256" as const, value: sha256(Buffer.from(summaryJson, "utf8")) }
return `${JSON.stringify({
schema: "wp-codebox/browser-storage-state-export/v1",
status: "exported",
command: "wordpress.export-browser-storage-state",
storageState: normalized.summary,
...(exportedUser ? { user: storageStateUserSummary(exportedUser) } : {}),
artifacts: {
storageState: storageStateArtifactPath,
summary: summaryArtifactPath,
},
artifactRefs: [
{ kind: "browser-storage-state", path: storageStateArtifactPath, digest: storageStateDigest, redactionRequired: true },
{ kind: "browser-storage-state-summary", path: summaryArtifactPath, digest: summaryDigest },
],
}, null, 2)}\n`
}
private async exportWordPressFixtureUserStorageState(spec: ExecutionSpec, server: PlaygroundCliServer): Promise<unknown> {
const browserUrls = stringListArg(spec.args ?? [], "browser-urls") ?? [this.spec.preview?.publicUrl ?? server.serverUrl]
const user = jsonObjectStringArg(spec.args ?? [], "user-json") as WordPressFixtureUserSpec
const code = wordpressFixtureUserStorageStatePhpCode({ browserUrls, user })
const response = await this.runPlaygroundCommand("wordpress.export-browser-storage-state", server, {
code: bootstrapPhpCode(this.spec, code, spec.args ?? []),
})
assertPlaygroundResponseOk("wordpress.export-browser-storage-state", response)
try {
return JSON.parse(response.text)
} catch (error) {
throw new Error(`wordpress.export-browser-storage-state returned invalid JSON: ${errorMessage(error)}`)
}
}
async runCaptureStateBundle(spec: ExecutionSpec): Promise<string> {
const label = stringArg(spec.args ?? [], "label")
const snapshotOptions = snapshotOptionsFromArgs(spec.args ?? [])
const snapshot = await this.snapshot(snapshotOptions)
const snapshotOptionsMetadata = hasSnapshotOptions(snapshotOptions) ? { snapshotOptions } : {}
const summary = snapshot.metadata.summary && typeof snapshot.metadata.summary === "object" && !Array.isArray(snapshot.metadata.summary)
? snapshot.metadata.summary as Record<string, unknown>
: {}
return `${JSON.stringify({
schema: "wp-codebox/wordpress-state-bundle-capture/v1",
status: "captured",
replayStatus: "replayable-runtime-state",
...(label ? { label } : {}),
snapshot: {
id: snapshot.id,
createdAt: snapshot.createdAt,
semantics: snapshot.semantics,
digest: snapshot.digest,
artifactRefs: snapshot.artifactRefs ?? [],
},
summary: {
databaseTables: summary.databaseTables ?? 0,
wpContentFiles: summary.wpContentFiles ?? 0,
...snapshotOptionsMetadata,
},
}, null, 2)}\n`
}
async runExportReplayPackage(spec: ExecutionSpec): Promise<string> {
const label = stringArg(spec.args ?? [], "label")
const landingPage = stringArg(spec.args ?? [], "landing-page")
const outputDirectory = replayExportOutputDirectory(this.artifactRoot, stringArg(spec.args ?? [], "output-dir"))
const importMs = nonNegativeIntegerStringArg(spec.args ?? [], "import-ms") ?? 0
const snapshotOptions = snapshotOptionsFromArgs(spec.args ?? [])
const snapshotOptionsMetadata = hasSnapshotOptions(snapshotOptions) ? { snapshotOptions } : {}
const materializeStartedAtMs = Date.now()
let materialization: Awaited<ReturnType<typeof materializePlaygroundMountsFromVfs>> | undefined
if (this.status !== "destroyed" && this.cliServerPromise) {
materialization = await materializePlaygroundMountsFromVfs(await this.cliServerPromise, this.mounts)
if (materialization.materialized > 0 || materialization.deleted > 0 || materialization.skipped > 0) {
this.recordEvent("runtime.mounts.materialized", { ...materialization, source: "wordpress.export-replay-package" })
}
}
const materializeMs = Date.now() - materializeStartedAtMs
const snapshotStartedAtMs = Date.now()
const snapshot = await this.snapshot(snapshotOptions)
const snapshotMs = Date.now() - snapshotStartedAtMs
const payload = await runtimeSnapshotPayload(snapshot)
const exportStartedAtMs = Date.now()
const replayPackage = await writeReplayExportPackage(payload, {
directory: outputDirectory,
landingPage,
importMs,
materializeMs,
snapshotMs,
source: {
...(label ? { label } : {}),
command: "wordpress.export-replay-package",
runtimeId: this.runtimeId,
snapshotId: snapshot.id,
...snapshotOptionsMetadata,
artifactRoot: this.artifactRoot,
...(materialization ? { materialization } : {}),
},
})
replayPackage.metrics.exportMs = Date.now() - exportStartedAtMs
this.recordEvent("runtime.replay-package.exported", {
directory: replayPackage.directory,
metrics: replayPackage.metrics,
artifacts: replayPackage.artifacts,
})
return `${JSON.stringify({
schema: "wp-codebox/wordpress-replay-export/v1",
status: replayPackage.status,
...(label ? { label } : {}),
replayStatus: "replayable-runtime-state",
directory: replayPackage.directory,
metrics: replayPackage.metrics,
artifacts: replayPackage.artifacts,
manifest: {
id: replayPackage.manifest.id,
contentDigest: replayPackage.manifest.contentDigest,
createdAt: replayPackage.manifest.createdAt,
},
...snapshotOptionsMetadata,
}, null, 2)}\n`
}
async runPluginCheck(spec: ExecutionSpec): Promise<string> {
const server = await this.bootPlayground()
const result = await runPluginCheckCommand({
artifactRoot: this.artifactRoot,
runWpCliCommand: (targetServer, argv) => this.runWpCliCommand(targetServer, argv),
server,
spec,
})
this.pluginChecks.push(result.artifact)
return result.output
}
async runThemeCheck(spec: ExecutionSpec): Promise<string> {
const server = await this.bootPlayground()
const result = await runThemeCheckCommand({
artifactRoot: this.artifactRoot,
runPlaygroundCommand: (command, targetServer, options) => this.runPlaygroundCommand(command, targetServer, options),
runWpCliArgv: (targetServer, argv) => this.runWpCliArgv(targetServer, argv),
runtimeSpec: this.spec,
server,
spec,
})
this.themeChecks.push(result.artifact)
return result.output
}
private async runWpCliCommand(server: PlaygroundCliServer, argv: string[]): Promise<PlaygroundRunResponse> {
if (!server.playground.writeFile) {
throw new Error("WP-CLI commands require a Playground backend with writeFile support")
}
const scriptPath = `/tmp/wp-codebox-wp-cli-${this.commands.length}-${Date.now().toString(36)}.php`
await server.playground.writeFile(scriptPath, wpCliPhpScript(argv))