-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrecipe-builders.ts
More file actions
331 lines (301 loc) · 14.4 KB
/
Copy pathrecipe-builders.ts
File metadata and controls
331 lines (301 loc) · 14.4 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
import type { RuntimePreviewSpec, RuntimeWorkerCount, RuntimeWordPressInstallMode, WorkspaceRecipe, WorkspaceRecipeExtraPlugin, WorkspaceRecipeMount, WorkspaceRecipePHPWasmExtensionManifest, WorkspaceRecipeRuntimeBackendPackage, WorkspaceRecipeRuntimeService, WorkspaceRecipeStep } from "./runtime-contracts.js"
import { commandArg, commandJsonArg, commandStringListArg } from "./command-codecs.js"
export { buildRuntimePackageRunRecipe, CODEBOX_RUN_RUNTIME_PACKAGE_ABILITY, RUNTIME_PACKAGE_ARTIFACT_DECLARATION_SCHEMA, RUNTIME_PACKAGE_EXECUTION_INPUT_SCHEMA, RUNTIME_PACKAGE_EXECUTION_RESULT_SCHEMA, RUNTIME_PACKAGE_OUTPUT_PROJECTION_SCHEMA, runtimePackageExecutionInput, type RuntimePackageArtifactDeclaration, type RuntimePackageExecutionInput, type RuntimePackageOutputProjection, type RuntimePackageRunRecipeOptions } from "./runtime-package-execution.js"
export { RUNTIME_PACKAGE_DIAGNOSTIC_SCHEMA, RUNTIME_PACKAGE_RESULT_SCHEMA, RUNTIME_PACKAGE_TASK_SCHEMA, normalizeRuntimePackageResult, normalizeRuntimePackageTask, validateRuntimePackageTask, type RuntimePackageDiagnostic, type RuntimePackageResult, type RuntimePackageTask } from "./runtime-package-contracts.js"
import { normalizeSharedMounts } from "./mount-primitives.js"
import { DEFAULT_WORDPRESS_VERSION } from "./runtime-defaults.js"
import { resolvePluginEntrypointContract } from "./component-contracts.js"
type JsonObject = Record<string, unknown>
export interface NormalizeRecipeMountsOptions {
defaultMode?: WorkspaceRecipeMount["mode"]
}
export interface WordPressPhpunitRecipeOptions {
wordpressVersion?: string
phpVersion?: string
workers?: RuntimeWorkerCount
databaseType?: "sqlite" | "mysql"
wordpressInstallMode?: RuntimeWordPressInstallMode
blueprint?: unknown
extensions?: WorkspaceRecipePHPWasmExtensionManifest[]
backendPackage?: WorkspaceRecipeRuntimeBackendPackage
preview?: RuntimePreviewSpec
mounts?: WorkspaceRecipeMount[]
services?: WorkspaceRecipeRuntimeService[]
extra_plugins?: WorkspaceRecipeExtraPlugin[]
pluginSource?: string
pluginSlug: string
cwd?: string
selectedTestFile?: string
changedTestFiles?: string[]
env?: JsonObject
wpConfigDefines?: JsonObject
autoloadFile?: string
projectAutoloadFile?: string
testsDir?: string
testRoot?: string
phpunitXml?: string
dependencyMounts?: string[]
bootstrapFiles?: string[]
preloadFiles?: string[]
phpunitArgs?: string[]
bootstrapMode?: "managed" | "project" | (string & {})
projectBootstrap?: string
multisite?: boolean
prepareSteps?: WorkspaceRecipeStep[]
}
export interface WordPressBenchRecipeOptions {
wordpressVersion?: string
blueprint?: unknown
mounts?: WorkspaceRecipeMount[]
extra_plugins?: WorkspaceRecipeExtraPlugin[]
componentId?: string
pluginSlug: string
iterations?: number
warmupIterations?: number
dependencySlugs?: string[]
env?: JsonObject
wpConfigDefines?: JsonObject
bootstrapFiles?: string[]
workloads?: unknown[]
scenarioIds?: string[]
lifecycle?: JsonObject
resetPolicy?: JsonObject
prepareSteps?: WorkspaceRecipeStep[]
postSteps?: WorkspaceRecipeStep[]
}
export function normalizeRecipeMounts(mounts: readonly WorkspaceRecipeMount[] = [], options: NormalizeRecipeMountsOptions = {}): WorkspaceRecipeMount[] {
return normalizeSharedMounts(mounts, { defaultMode: options.defaultMode ?? "readwrite", label: "Recipe mount" })
}
export function buildWordPressPhpunitRecipe(options: WordPressPhpunitRecipeOptions): WorkspaceRecipe {
const pluginSlug = requiredPluginSlug(options.pluginSlug, "buildWordPressPhpunitRecipe")
const pluginTarget = `/wordpress/wp-content/plugins/${pluginSlug}`
const autoloadFile = options.autoloadFile ?? (options.bootstrapMode === "project" ? "" : "/wp-codebox-vendor/autoload.php")
const services = phpunitRuntimeServices(options.databaseType, options.services)
const extraPlugins = normalizeExtraPlugins(options.extra_plugins)
return {
schema: "wp-codebox/workspace-recipe/v1",
runtime: {
wp: options.wordpressVersion ?? DEFAULT_WORDPRESS_VERSION,
...(options.phpVersion ? { phpVersion: options.phpVersion } : {}),
...(options.workers !== undefined ? { workers: options.workers } : {}),
...(options.wordpressInstallMode ? { wordpressInstallMode: options.wordpressInstallMode } : {}),
blueprint: blueprintWithMultisite(options.blueprint ?? { steps: [] }, (options.multisite ?? false) && options.databaseType !== "mysql"),
...(options.preview || options.multisite ? { preview: multisitePreview(options.preview, options.multisite ?? false) } : {}),
...(options.extensions?.length ? { extensions: options.extensions } : {}),
...(options.backendPackage ? { backendPackage: options.backendPackage } : {}),
},
inputs: {
extra_plugins: extraPlugins,
...(services.length > 0 ? { services } : {}),
mounts: normalizeRecipeMounts([
...(options.pluginSource ? [{ source: options.pluginSource, target: pluginTarget } satisfies WorkspaceRecipeMount] : []),
...(options.mounts ?? []),
]),
},
workflow: {
...(options.prepareSteps && options.prepareSteps.length > 0 ? { before: normalizeRecipeSteps(options.prepareSteps, "prepareSteps") } : {}),
steps: [{
command: "wordpress.phpunit",
args: [
commandArg("plugin-slug", pluginSlug),
commandArg("cwd", options.cwd ?? pluginTarget),
commandArg("test-file", options.selectedTestFile ?? ""),
commandJsonArg("changed-tests-json", options.changedTestFiles ?? []),
commandJsonArg("env-json", options.env ?? {}),
commandJsonArg("wp-config-defines-json", options.wpConfigDefines ?? {}),
commandArg("autoload-file", autoloadFile),
commandArg("autoload-file-role", autoloadFile ? "harness" : ""),
commandArg("project-autoload-file", options.projectAutoloadFile ?? ""),
commandArg("tests-dir", options.testsDir ?? "/wp-codebox-vendor/wp-phpunit/wp-phpunit"),
commandArg("test-root", options.testRoot ?? `${pluginTarget}/tests`),
commandArg("phpunit-xml", options.phpunitXml ?? `${pluginTarget}/phpunit.xml.dist`),
commandArg("phpunit-xml-default", options.phpunitXml === undefined ? "1" : ""),
commandStringListArg("dependency-mounts", options.dependencyMounts ?? []),
commandJsonArg("dependency-plugins-json", phpunitDependencyPlugins(options.dependencyMounts ?? [], extraPlugins)),
commandJsonArg("bootstrap-files-json", options.bootstrapFiles ?? []),
commandJsonArg("preload-files-json", options.preloadFiles ?? []),
commandJsonArg("phpunit-args-json", options.phpunitArgs ?? []),
commandArg("bootstrap-mode", options.bootstrapMode ?? "managed"),
commandArg("project-bootstrap", options.projectBootstrap ?? ""),
commandArg("multisite", options.multisite ? "1" : "0"),
...(options.databaseType ? [commandArg("database-type", options.databaseType)] : []),
],
}],
},
}
}
function phpunitDependencyPlugins(mounts: readonly string[], plugins: readonly WorkspaceRecipeExtraPlugin[]): Array<{ path: string; pluginFile: string; activate: boolean; loadAs: "plugin" | "mu-plugin" }> {
return mounts.map((path) => {
const normalized = path.replace(/\/+$/g, "")
const slug = normalized.slice(normalized.lastIndexOf("/") + 1)
const plugin = plugins.find((candidate) => candidate.slug === slug || candidate.mountSlug === slug)
const loadAs = plugin?.loadAs === "mu-plugin" ? "mu-plugin" : "plugin"
const pluginFile = plugin
? resolvePluginEntrypointContract({ source: plugin.source ?? plugin.sourcePath ?? "", slug, pluginFile: plugin.pluginFile, loadAs }).pluginFile
: `${slug}/${slug}.php`
return {
path: loadAs === "mu-plugin" ? `/wordpress/wp-content/mu-plugins/contained-runtime/${slug}` : path,
pluginFile,
activate: plugin?.activate !== false,
loadAs,
}
})
}
function phpunitRuntimeServices(databaseType: WordPressPhpunitRecipeOptions["databaseType"], services: WorkspaceRecipeRuntimeService[] = []): WorkspaceRecipeRuntimeService[] {
if (databaseType !== undefined && databaseType !== "sqlite" && databaseType !== "mysql") {
throw new Error(`Unsupported PHPUnit database type: ${databaseType}`)
}
if (databaseType !== "mysql") {
return services
}
const mysqlIndex = services.findIndex((service) => service.kind === "mysql")
const canonicalOutputs = { host: "DB_HOST", port: "DB_PORT", username: "DB_USER", password: "DB_PASSWORD", database: "DB_NAME" }
if (mysqlIndex === -1) {
return [...services, { id: "wordpress-database", kind: "mysql", outputs: canonicalOutputs }]
}
return services.map((service, index) => index === mysqlIndex ? { ...service, outputs: { ...service.outputs, ...canonicalOutputs } } : service)
}
function normalizeRecipeSteps(steps: readonly WorkspaceRecipeStep[], label: string): WorkspaceRecipeStep[] {
return steps.map((step, index) => {
if (!step.command || typeof step.command !== "string") {
throw new Error(`${label}[${index}] requires command`)
}
return {
command: step.command,
...(step.args !== undefined ? { args: step.args } : {}),
...(step.metadata !== undefined ? { metadata: step.metadata } : {}),
...(step.allowFailure !== undefined ? { allowFailure: step.allowFailure } : {}),
...(step.advisory !== undefined ? { advisory: step.advisory } : {}),
}
})
}
export function buildWordPressBenchRecipe(options: WordPressBenchRecipeOptions): WorkspaceRecipe {
const pluginSlug = requiredPluginSlug(options.pluginSlug, "buildWordPressBenchRecipe")
const componentId = options.componentId?.trim() || pluginSlug
return {
schema: "wp-codebox/workspace-recipe/v1",
runtime: {
wp: options.wordpressVersion ?? DEFAULT_WORDPRESS_VERSION,
blueprint: blueprintWithWpConfigDefines(options.blueprint ?? {}, options.wpConfigDefines ?? {}),
},
inputs: {
extra_plugins: normalizeExtraPlugins(options.extra_plugins),
mounts: normalizeRecipeMounts(options.mounts, { defaultMode: "readonly" }),
},
workflow: {
...(options.prepareSteps && options.prepareSteps.length > 0 ? { before: normalizeRecipeSteps(options.prepareSteps, "prepareSteps") } : {}),
steps: [{
command: "wordpress.bench",
args: [
commandArg("component-id", componentId),
commandArg("plugin-slug", pluginSlug),
commandArg("iterations", positiveInteger(options.iterations, 3)),
commandArg("warmup", nonNegativeInteger(options.warmupIterations, 1)),
commandStringListArg("dependency-slugs", options.dependencySlugs ?? []),
commandJsonArg("env-json", options.env ?? {}),
commandJsonArg("bootstrap-files-json", options.bootstrapFiles ?? []),
commandJsonArg("workloads-json", options.workloads ?? []),
commandJsonArg("scenario-ids-json", normalizeScenarioIds(options.scenarioIds ?? [])),
commandJsonArg("lifecycle-json", options.lifecycle ?? {}),
commandJsonArg("reset-policy-json", options.resetPolicy ?? {}),
],
}, ...normalizeRecipeSteps(options.postSteps ?? [], "postSteps")],
},
}
}
function normalizeExtraPlugins(plugins: readonly WorkspaceRecipeExtraPlugin[] = []): WorkspaceRecipeExtraPlugin[] {
return plugins.map((plugin, index) => {
if (!plugin.source || typeof plugin.source !== "string") {
throw new Error(`Recipe extra plugin ${index} requires source`)
}
const normalized: WorkspaceRecipeExtraPlugin = {
source: plugin.source,
}
if (plugin.slug !== undefined) {
normalized.slug = plugin.slug
}
if (plugin.sourceRoot !== undefined) {
normalized.sourceRoot = plugin.sourceRoot
}
if (plugin.sourceSubpath !== undefined) {
normalized.sourceSubpath = plugin.sourceSubpath
}
if (plugin.originalSource !== undefined) {
normalized.originalSource = plugin.originalSource
}
if (plugin.pluginFile !== undefined) {
normalized.pluginFile = plugin.pluginFile
}
if (plugin.activate !== undefined) {
normalized.activate = plugin.activate
}
if (plugin.sha256 !== undefined) {
normalized.sha256 = plugin.sha256
}
if (plugin.loadAs !== undefined) {
normalized.loadAs = plugin.loadAs
}
if (plugin.composer !== undefined) {
normalized.composer = plugin.composer
}
return normalized
})
}
function blueprintWithWpConfigDefines(blueprint: unknown, defines: JsonObject): unknown {
const defineKeys = Object.keys(defines)
if (defineKeys.length === 0) {
return blueprint
}
if (!isPlainObject(blueprint)) {
return { steps: [{ step: "defineWpConfigConsts", consts: defines }] }
}
const existingSteps = Array.isArray(blueprint.steps) ? blueprint.steps : []
return {
...blueprint,
steps: [...existingSteps, { step: "defineWpConfigConsts", consts: defines }],
}
}
function blueprintWithMultisite(blueprint: unknown, multisite: boolean): unknown {
if (!multisite) {
return blueprint
}
if (!isPlainObject(blueprint)) {
return { steps: [{ step: "enableMultisite" }] }
}
const existingSteps = Array.isArray(blueprint.steps) ? blueprint.steps : []
if (existingSteps.some((step) => isPlainObject(step) && step.step === "enableMultisite")) {
return blueprint
}
return {
...blueprint,
steps: [{ step: "enableMultisite" }, ...existingSteps],
}
}
function multisitePreview(preview: RuntimePreviewSpec | undefined, multisite: boolean): RuntimePreviewSpec {
if (!multisite || preview?.siteUrl) {
return preview ?? {}
}
return {
...preview,
siteUrl: "http://localhost",
}
}
function requiredPluginSlug(value: string, caller: string): string {
const slug = value.trim()
if (!slug) {
throw new Error(`${caller} requires pluginSlug`)
}
return slug
}
function positiveInteger(value: number | undefined, fallback: number): number {
return value !== undefined && Number.isSafeInteger(value) && value > 0 ? value : fallback
}
function nonNegativeInteger(value: number | undefined, fallback: number): number {
return value !== undefined && Number.isSafeInteger(value) && value >= 0 ? value : fallback
}
function normalizeScenarioIds(values: readonly string[]): string[] {
return [...new Set(values.map((value) => value.trim()).filter(Boolean))]
}
function isPlainObject(value: unknown): value is JsonObject {
return Boolean(value) && typeof value === "object" && !Array.isArray(value)
}