-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecipe-sources.ts
More file actions
1320 lines (1160 loc) · 48.2 KB
/
Copy pathrecipe-sources.ts
File metadata and controls
1320 lines (1160 loc) · 48.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
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 { createHash } from "node:crypto"
import { cp, mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"
import { tmpdir } from "node:os"
import { basename, dirname, join, relative, resolve } from "node:path"
import { compileSourcePackage, composerManagedHostCommandConfig, composerManagedHostEnv, sourcePackagePathAllowed, type WorkspaceRecipeSourcePackage } from "@automattic/wp-codebox-core"
import type { MountSpec, WorkspaceRecipe, WorkspaceRecipeDependencyOverlay, WorkspaceRecipeExtraPlugin, WorkspaceRecipeRuntimeOverlay, WorkspaceRecipeStagedFile, WorkspaceRecipeWorkspace, WorkspaceRecipeWorkspacePreload, WorkspaceRecipeWorkspacePreloadRepository } from "@automattic/wp-codebox-core"
import { executeManagedHostCommand, resolvePluginEntrypointContract } from "@automattic/wp-codebox-core"
import { collectPreparedSourceCleanupPaths, DEFAULT_PREPARED_SOURCE_EXCLUDE_NAMES, localPreparedSourceProvenance, prepareLocalSourceStageSync, SANDBOX_WORKSPACE_ROOT, type PreparedSourceProvenance } from "@automattic/wp-codebox-core/internals"
import { registerRuntimeOverlayDescriptor, runtimeOverlayDescriptor } from "./runtime-overlay-registry.js"
import { evaluateSourcePolicy, sourcePolicySnapshot, type SourcePolicyIssue } from "./source-policy.js"
import { prepareZipSource } from "./zip-source.js"
export { ALLOW_NETWORK_DOWNLOADS_ENV, ALLOWED_DOWNLOAD_HOSTS_ENV, allowedDownloadHosts, isSha256, maxDownloadBytes, maxExtractedBytes, maxExtractedFiles, MAX_DOWNLOAD_BYTES_ENV, MAX_EXTRACTED_BYTES_ENV, MAX_EXTRACTED_FILES_ENV, REQUIRE_SOURCE_SHA256_ENV, sourceSha256Required } from "./source-policy.js"
const PHP_AI_CLIENT_RUNTIME_OVERLAY_TARGET = "/wordpress/wp-includes/php-ai-client"
export interface PreparedWorkspaceMount {
source: string
target: string
mode: "readonly" | "readwrite"
cleanupPaths: string[]
metadata: Record<string, unknown>
}
interface PreparedWorkspaceSource {
source: string
baselineSource: string
cleanupPaths: string[]
}
export type RecipeSourceType = "local" | "https_zip" | "wporg_plugin_zip"
export interface RecipeSourceProvenance {
kind: RecipeSourceType
original: string
resolvedUrl?: string
digest?: {
sha256: string
expected?: string
verified?: boolean
}
policy?: {
host: string
maxDownloadBytes: number
maxExtractedBytes: number
maxExtractedFiles: number
sha256Required: boolean
}
localPathCategory?: "recipe-relative" | "temporary-download" | "temporary-composer-autoload"
}
interface PreparedExternalSource {
source: string
cleanupPaths: string[]
provenance: RecipeSourceProvenance
}
export interface PreparedExtraPlugin {
source: string
slug: string
target: string
pluginFile: string
activate: boolean
loadAs: "plugin" | "mu-plugin"
cleanupPaths: string[]
provenance: RecipeSourceProvenance
metadata?: Record<string, unknown>
}
type BootActivePluginCandidate = Pick<PreparedExtraPlugin, "pluginFile" | "activate" | "loadAs">
export type RecipeStagedFileProvenance = PreparedSourceProvenance
export interface PreparedStagedFile {
source: string
originalSource: string
sourceRef: string
target: string
type: MountSpec["type"]
cleanupPaths: string[]
provenance: RecipeStagedFileProvenance
metadata: Record<string, unknown>
}
export interface SourcePackageProvenance {
schema: "wp-codebox/source-package-provenance/v1"
name: string
source: RecipeStagedFileProvenance
target: string
allow: string[]
deny: string[]
digest: { sha256: string }
materializedAt: string
}
export interface PreparedRuntimeOverlay {
source: string
target: string
type: "directory"
mode: "readonly"
cleanupPaths: string[]
metadata: Record<string, unknown>
}
export interface PreparedDependencyOverlay {
source: string
sourceRef: string
target: string
package: string
consumer: string
type: "directory"
mode: "readonly"
cleanupPaths: string[]
metadata: Record<string, unknown>
}
export interface ParsedRecipeSource {
type: RecipeSourceType
resolvedUrl: string
host: string
expectedSha256?: string
wporgSlug?: string
}
const PHP_SCOPER_VERSION = "0.18.17"
const PHP_SCOPER_URL = `https://github.com/humbug/php-scoper/releases/download/${PHP_SCOPER_VERSION}/php-scoper.phar`
export type RecipeSourcePolicyIssue = SourcePolicyIssue
export const evaluateRecipeSourcePolicy = evaluateSourcePolicy
function normalizedWorkspaceSeedExcludePath(value: string): string {
return value.replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "").replace(/\/+$/, "")
}
function workspaceSeedExcludeMatches(relativePath: string, excludePath: string): boolean {
const normalizedRelativePath = normalizedWorkspaceSeedExcludePath(relativePath)
const normalizedExcludePath = normalizedWorkspaceSeedExcludePath(excludePath)
if (!normalizedExcludePath) {
return false
}
if (normalizedExcludePath.endsWith("*")) {
return normalizedRelativePath.startsWith(normalizedExcludePath.slice(0, -1))
}
return normalizedRelativePath === normalizedExcludePath || normalizedRelativePath.startsWith(`${normalizedExcludePath}/`)
}
function shouldCopyWorkspaceSeedEntry(sourceRoot: string, entry: string, excludePaths: string[] = []): boolean {
const relativePath = relative(sourceRoot, entry)
if (!relativePath) {
return true
}
return !excludePaths.some((excludePath) => workspaceSeedExcludeMatches(relativePath, excludePath))
}
async function copyWorkspaceSeedDirectory(source: string, target: string, excludePaths: string[] = []): Promise<void> {
await cp(source, target, {
recursive: true,
filter: (entry) => shouldCopyWorkspaceSeedEntry(source, entry, excludePaths),
})
}
export async function prepareRecipeWorkspaces(recipe: WorkspaceRecipe, recipeDirectory: string): Promise<PreparedWorkspaceMount[]> {
const workspaces = recipe.inputs?.workspaces ?? []
const mounts: PreparedWorkspaceMount[] = []
for (const [index, workspace] of workspaces.entries()) {
const slug = workspace.seed.slug ?? basename(resolve(recipeDirectory, workspace.seed.source ?? `workspace-${index}`))
const prepared = await prepareRecipeWorkspace(workspace, recipeDirectory, slug)
const target = workspace.target ?? defaultWorkspaceTarget(workspace, slug)
mounts.push({
source: prepared.source,
target,
mode: workspace.mode ?? "readwrite",
cleanupPaths: prepared.cleanupPaths,
metadata: {
kind: "recipe-workspace",
index,
seed: workspace.seed,
baselineSource: prepared.baselineSource,
target,
workspaceRoot: SANDBOX_WORKSPACE_ROOT,
sourceMode: workspace.sourceMode ?? "repo-backed",
},
})
}
return mounts
}
export async function prepareRecipeWorkspacePreloads(recipe: WorkspaceRecipe): Promise<PreparedWorkspaceMount[]> {
const preloads = recipe.inputs?.workspace_preloads ?? []
const mounts: PreparedWorkspaceMount[] = []
for (const [preloadIndex, preload] of preloads.entries()) {
for (const [repositoryIndex, repository] of preload.payload.repositories.entries()) {
mounts.push(await prepareWorkspacePreloadRepository(preload, repository, preloadIndex, repositoryIndex))
}
}
return mounts
}
async function prepareWorkspacePreloadRepository(preload: WorkspaceRecipeWorkspacePreload, repository: WorkspaceRecipeWorkspacePreloadRepository, preloadIndex: number, repositoryIndex: number): Promise<PreparedWorkspaceMount> {
if (!/^[a-z0-9-]+$/.test(repository.name)) {
throw new Error(`Workspace preload repository name must be a slug: ${repository.name}`)
}
if (!workspacePreloadRepositoryUrlAllowed(repository.url)) {
throw new Error(`Workspace preload repository url must be an HTTPS or SSH Git URL: ${repository.url}`)
}
const root = await mkdtemp(join(tmpdir(), `wp-codebox-workspace-preload-${repository.name}-`))
const source = join(root, repository.name)
try {
await executeManagedHostCommand({ command: "git", args: ["clone", "--quiet", repository.url, source], cwd: root, allowedCwdRoots: [root], label: "clone workspace preload repository" })
if (repository.ref) {
await executeManagedHostCommand({ command: "git", args: ["checkout", "--quiet", repository.ref], cwd: source, allowedCwdRoots: [root], label: "checkout workspace preload repository ref" })
}
} catch (error) {
await rm(root, { recursive: true, force: true })
throw error
}
return {
source,
target: `${SANDBOX_WORKSPACE_ROOT}/${repository.name}`,
mode: "readwrite",
cleanupPaths: [root],
metadata: {
kind: "workspace-preload",
sourceMode: "repo-backed",
mountRole: "workspace-preload",
workspaceRef: repository.name,
repo: repository.url,
gitRef: repository.ref,
preload: {
type: preload.type,
slug: preload.slug,
source: preload.source,
schema: preload.payload.schema,
provenance: preload.provenance,
},
artifactRef: {
type: preload.type,
slug: preload.slug,
source: preload.source,
preloadIndex,
repositoryIndex,
},
},
}
}
function workspacePreloadRepositoryUrlAllowed(url: string): boolean {
return url.startsWith("https://") || /^git@[A-Za-z0-9._-]+:[A-Za-z0-9._/-]+\.git$/.test(url)
}
async function cleanupRecipeWorkspaces(workspaces: PreparedWorkspaceMount[]): Promise<void> {
await Promise.all(workspaces.flatMap((workspace) => workspace.cleanupPaths).map((path) => rm(path, { recursive: true, force: true })))
}
export async function cleanupRecipePreparedSources(workspaces: PreparedWorkspaceMount[], extraPlugins: PreparedExtraPlugin[], stagedFiles: PreparedStagedFile[] = [], overlays: PreparedRuntimeOverlay[] = [], dependencyOverlays: PreparedDependencyOverlay[] = []): Promise<void> {
const cleanupPaths = collectPreparedSourceCleanupPaths(extraPlugins, stagedFiles, overlays, dependencyOverlays)
await Promise.all([cleanupRecipeWorkspaces(workspaces), ...cleanupPaths.map((path) => rm(path, { recursive: true, force: true }))])
}
export async function prepareRecipeExtraPlugins(recipe: WorkspaceRecipe, recipeDirectory: string): Promise<PreparedExtraPlugin[]> {
const plugins: PreparedExtraPlugin[] = []
for (const plugin of recipeExtraPlugins(recipe)) {
const slug = recipeExtraPluginSlug(plugin)
const resolved = await prepareRecipeSource(plugin.source, recipeDirectory, slug, plugin.sha256)
const pluginFile = await resolveRecipeExtraPluginFile(plugin, recipeDirectory)
const loadAs = plugin.loadAs ?? "plugin"
const prepared = await prepareComposerAutoloadForPlugin(resolved, slug, plugin.source)
await assertPreparedPluginFileExists(prepared.source, pluginFile.slice(slug.length + 1), plugin.source)
plugins.push({
source: prepared.source,
slug,
target: pluginTarget(slug, loadAs),
pluginFile,
activate: plugin.activate !== false,
loadAs,
cleanupPaths: prepared.cleanupPaths,
provenance: prepared.provenance,
metadata: plugin.metadata ?? {},
})
}
return plugins
}
async function prepareComposerAutoloadForPlugin(prepared: PreparedExternalSource, slug: string, sourceRef: string): Promise<PreparedExternalSource> {
if (prepared.provenance.kind !== "local") {
return prepared
}
try {
const composerJson = await stat(join(prepared.source, "composer.json"))
if (!composerJson.isFile()) {
return prepared
}
} catch {
return prepared
}
try {
const autoload = await stat(join(prepared.source, "vendor", "autoload.php"))
if (autoload.isFile()) {
return prepared
}
} catch {
// Prepare a temporary copy below.
}
const stagingRoot = await mkdtemp(join(tmpdir(), `wp-codebox-plugin-${slug}-`))
const stagedSource = join(stagingRoot, slug)
await cp(prepared.source, stagedSource, { recursive: true })
try {
await executeManagedHostCommand({
...composerManagedHostCommandConfig({
cwd: stagedSource,
allowedCwdRoots: [stagingRoot],
label: "prepare Composer autoload for recipe extra plugin",
}),
cwd: stagedSource,
})
} catch (error) {
await rm(stagingRoot, { recursive: true, force: true })
const detail = error instanceof Error && "stderr" in error && typeof error.stderr === "string" && error.stderr.trim() ? error.stderr.trim() : error instanceof Error ? error.message : String(error)
throw new Error(`Recipe extra plugin source requires Composer autoload but could not be prepared: ${sourceRef}: ${detail}`)
}
return {
...prepared,
source: stagedSource,
cleanupPaths: [...prepared.cleanupPaths, stagingRoot],
provenance: {
...prepared.provenance,
localPathCategory: "temporary-composer-autoload",
},
}
}
export async function prepareRecipeDependencyOverlays(recipe: WorkspaceRecipe, recipeDirectory: string, extraPlugins: PreparedExtraPlugin[]): Promise<PreparedDependencyOverlay[]> {
const overlays: PreparedDependencyOverlay[] = []
for (const [index, overlay] of (recipe.inputs?.dependency_overlays ?? []).entries()) {
overlays.push(await prepareRecipeDependencyOverlay(overlay, recipeDirectory, extraPlugins, index))
}
return overlays
}
async function prepareRecipeDependencyOverlay(overlay: WorkspaceRecipeDependencyOverlay, recipeDirectory: string, extraPlugins: PreparedExtraPlugin[], index: number): Promise<PreparedDependencyOverlay> {
if (overlay.kind !== "composer-package") {
throw new Error(`Unsupported dependency overlay kind: ${overlay.kind}`)
}
if (!isComposerPackageName(overlay.package)) {
throw new Error(`Dependency overlay package must be a safe Composer package name: ${overlay.package}`)
}
const consumer = extraPlugins.find((plugin) => plugin.slug === overlay.consumer)
if (!consumer) {
throw new Error(`Dependency overlay consumer plugin was not found in inputs.extra_plugins: ${overlay.consumer}`)
}
const source = resolve(recipeDirectory, overlay.source)
await validateExistingDirectoryForOverlay(source, overlay.source)
const stagingRoot = await mkdtemp(join(tmpdir(), "wp-codebox-dependency-overlay-"))
const preparedSource = await prepareComposerBackedSource(source, stagingRoot, `dependency overlay ${overlay.package}`)
const target = `${consumer.target}/vendor/${composerPackageVendorPath(overlay.package)}`
const digest = await directoryContentDigest(preparedSource)
return {
source: preparedSource,
sourceRef: overlay.source,
target,
package: overlay.package,
consumer: overlay.consumer,
type: "directory",
mode: "readonly",
cleanupPaths: [stagingRoot],
metadata: {
kind: "dependency-overlay",
index,
overlayKind: overlay.kind,
package: overlay.package,
source: overlay.source,
consumer: overlay.consumer,
target,
digest: { sha256: digest },
...(overlay.metadata ? { userMetadata: overlay.metadata } : {}),
},
}
}
export async function prepareRecipeStagedFiles(recipe: WorkspaceRecipe, recipeDirectory: string): Promise<PreparedStagedFile[]> {
const stagedFiles: PreparedStagedFile[] = []
for (const [index, stagedFile] of (recipe.inputs?.stagedFiles ?? []).entries()) {
const originalSource = resolve(recipeDirectory, stagedFile.source)
const type = await stagedFileMountType(originalSource)
const stagingRoot = await mkdtemp(join(tmpdir(), "wp-codebox-staged-file-"))
const staged = prepareLocalSourceStageSync({
source: originalSource,
sourceRef: stagedFile.source,
targetRoot: stagingRoot,
recipeDirectory,
excludeNames: [],
})
const provenance = stagedFileProvenance(stagedFile, recipeDirectory)
stagedFiles.push({
source: staged.source,
originalSource,
sourceRef: stagedFile.source,
target: stagedFile.target,
type,
cleanupPaths: staged.cleanupPaths,
provenance,
metadata: {
kind: "staged-file",
index,
source: provenance,
},
})
}
for (const [index, sourcePackage] of (recipe.inputs?.sourcePackages ?? []).entries()) {
stagedFiles.push(await prepareRecipeSourcePackage(sourcePackage, recipeDirectory, index))
}
return stagedFiles
}
async function prepareRecipeSourcePackage(sourcePackage: WorkspaceRecipeSourcePackage, recipeDirectory: string, index: number): Promise<PreparedStagedFile> {
const compiled = compileSourcePackage(sourcePackage)
const originalSource = resolve(recipeDirectory, sourcePackage.source)
const sourceStat = await stat(originalSource)
if (!sourceStat.isDirectory()) {
throw new Error(`Recipe sourcePackages entries must point to directories: ${sourcePackage.source}`)
}
const stagingRoot = await mkdtemp(join(tmpdir(), "wp-codebox-source-package-"))
const stagedSource = join(stagingRoot, compiled.name)
await copySourcePackageDirectory(originalSource, stagedSource, sourcePackage.allow ?? [], sourcePackage.deny ?? [])
const digest = await directoryContentDigest(stagedSource)
const provenance = localPreparedSourceProvenance(sourcePackage.source, recipeDirectory)
const provenancePayload: SourcePackageProvenance = {
schema: "wp-codebox/source-package-provenance/v1",
name: compiled.name,
source: provenance,
target: compiled.stagedFile.target,
allow: sourcePackage.allow ?? [],
deny: sourcePackage.deny ?? [],
digest: { sha256: digest },
materializedAt: new Date().toISOString(),
}
await writeFile(join(stagedSource, ".wp-codebox-source-package.json"), `${JSON.stringify(provenancePayload, null, 2)}\n`)
return {
source: stagedSource,
originalSource,
sourceRef: sourcePackage.source,
target: compiled.stagedFile.target,
type: "directory",
cleanupPaths: [stagingRoot],
provenance,
metadata: {
kind: "source-package",
index,
name: compiled.name,
target: compiled.stagedFile.target,
source: provenance,
filters: { allow: sourcePackage.allow ?? [], deny: sourcePackage.deny ?? [] },
digest: { sha256: digest },
provenanceFile: ".wp-codebox-source-package.json",
...(sourcePackage.metadata ? { userMetadata: sourcePackage.metadata } : {}),
},
}
}
async function copySourcePackageDirectory(sourceRoot: string, targetRoot: string, allow: string[], deny: string[]): Promise<void> {
const excludedNames = new Set(DEFAULT_PREPARED_SOURCE_EXCLUDE_NAMES)
await cp(sourceRoot, targetRoot, {
recursive: true,
filter: (entry) => {
const relativePath = relative(sourceRoot, entry).replace(/\\/g, "/")
if (!relativePath) {
return true
}
if (excludedNames.has(basename(entry))) {
return false
}
return sourcePackagePathAllowed(relativePath, allow, deny)
},
})
}
export async function prepareRecipeRuntimeOverlays(recipe: WorkspaceRecipe, recipeDirectory: string): Promise<PreparedRuntimeOverlay[]> {
const overlays: PreparedRuntimeOverlay[] = []
for (const [index, overlay] of (recipe.runtime?.overlays ?? []).entries()) {
const descriptor = runtimeOverlayDescriptor(overlay)
if (!descriptor) {
throw new Error(`Unsupported runtime overlay: ${overlay.kind}/${overlay.library}/${overlay.strategy}`)
}
const prepared = descriptor.prepare
? await descriptor.prepare(overlay, recipeDirectory, index)
: await prepareDeclaredRuntimeOverlayPack(overlay, recipeDirectory, index, descriptor.defaultTarget)
overlays.push(prepared)
}
return overlays
}
async function prepareDeclaredRuntimeOverlayPack(overlay: WorkspaceRecipeRuntimeOverlay, recipeDirectory: string, index: number, defaultTarget: string): Promise<PreparedRuntimeOverlay> {
const source = resolve(recipeDirectory, overlay.source)
await validateExistingDirectoryForOverlay(source, overlay.source)
const target = overlay.target ?? defaultTarget
const digest = await directoryContentDigest(source)
return {
source,
target,
type: "directory",
mode: "readonly",
cleanupPaths: [],
metadata: {
kind: "runtime-overlay",
index,
overlayKind: overlay.kind,
library: overlay.library,
strategy: overlay.strategy,
source: overlay.source,
target,
preparedPath: source,
preparedPathKind: "local",
digest: { sha256: digest },
...(overlay.bundle ? { bundle: overlay.bundle } : {}),
...(overlay.metadata ? { userMetadata: overlay.metadata } : {}),
},
}
}
async function preparePhpAiClientOverlay(overlay: WorkspaceRecipeRuntimeOverlay, recipeDirectory: string, index: number): Promise<PreparedRuntimeOverlay> {
const source = resolve(recipeDirectory, overlay.source)
await validateExistingDirectoryForOverlay(source, overlay.source)
const stagingRoot = await mkdtemp(join(tmpdir(), "wp-codebox-overlay-php-ai-client-"))
const bundle = join(stagingRoot, "wp-includes", "php-ai-client")
const srcTarget = join(bundle, "src")
const thirdPartyTarget = join(bundle, "third-party")
await mkdir(srcTarget, { recursive: true })
await mkdir(thirdPartyTarget, { recursive: true })
const preparedSource = await prepareComposerBackedSource(source, stagingRoot, `runtime overlay ${overlay.kind}/${overlay.library}/${overlay.strategy}`)
const scopedRoot = await scopePhpAiClientSource(preparedSource, stagingRoot)
const packages = await composerInstalledPackagesFromSource(preparedSource)
const namespacePrefixes = dependencyNamespacePrefixes(packages)
await scopePhpAiClientSourceDependencyReferences(join(scopedRoot, "src"), namespacePrefixes)
await cp(join(scopedRoot, "src"), srcTarget, { recursive: true })
await copyScopedComposerDependencies(packages, scopedRoot, thirdPartyTarget)
await scopePhpAiClientSourceDependencyReferences(thirdPartyTarget, namespacePrefixes)
await prunePhpAiClientThirdParty(thirdPartyTarget)
await writePhpAiClientAutoload(bundle)
const digest = await directoryContentDigest(bundle)
return {
source: bundle,
target: overlay.target ?? PHP_AI_CLIENT_RUNTIME_OVERLAY_TARGET,
type: "directory",
mode: "readonly",
cleanupPaths: [stagingRoot],
metadata: {
kind: "runtime-overlay",
index,
overlayKind: overlay.kind,
library: overlay.library,
strategy: overlay.strategy,
source: overlay.source,
target: overlay.target ?? PHP_AI_CLIENT_RUNTIME_OVERLAY_TARGET,
preparedPath: bundle,
preparedPathKind: "ephemeral",
digest: { sha256: digest },
...(overlay.metadata ? { userMetadata: overlay.metadata } : {}),
},
}
}
registerRuntimeOverlayDescriptor({
kind: "bundled-library",
library: "php-ai-client",
strategy: "wordpress-scoped-bundle",
defaultTarget: PHP_AI_CLIENT_RUNTIME_OVERLAY_TARGET,
prepare: preparePhpAiClientOverlay,
})
async function prepareComposerBackedSource(source: string, stagingRoot: string, label: string): Promise<string> {
if (await pathIsDirectory(join(source, "vendor"))) {
return source
}
if (!await pathIsFile(join(source, "composer.json"))) {
throw new Error(`Composer-backed ${label} source has no vendor directory and no composer.json for dependency hydration: ${source}`)
}
const composer = await resolveComposerCommand()
if (!composer) {
throw new Error(`Composer-backed ${label} source has no vendor directory, and Composer is not available to hydrate dependencies. Run composer install in ${source}, or install Composer on PATH before running WP Codebox.`)
}
const staged = prepareLocalSourceStageSync({
source,
targetRoot: stagingRoot,
targetName: "composer-source",
cleanupRoot: false,
excludeNames: ["vendor"],
})
const hydratedSource = staged.source
try {
await executeManagedHostCommand({
...composerManagedHostCommandConfig({
cwd: hydratedSource,
allowedCwdRoots: [stagingRoot],
args: ["install", "--working-dir", hydratedSource, "--no-dev", "--no-interaction", "--no-progress", "--prefer-dist", "--classmap-authoritative"],
label: `hydrate Composer-backed ${label}`,
}),
command: composer,
cwd: hydratedSource,
})
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
throw new Error(`Composer-backed ${label} dependency hydration failed for ${source}. Run composer install in that checkout or inspect Composer output. ${message}`)
}
if (!await pathIsFile(join(hydratedSource, "vendor", "composer", "installed.json"))) {
throw new Error(`Composer-backed ${label} dependency hydration completed without vendor/composer/installed.json: ${source}`)
}
return hydratedSource
}
async function pathIsDirectory(path: string): Promise<boolean> {
try {
return (await stat(path)).isDirectory()
} catch {
return false
}
}
async function pathIsFile(path: string): Promise<boolean> {
try {
return (await stat(path)).isFile()
} catch {
return false
}
}
async function resolveComposerCommand(): Promise<string> {
try {
await executeManagedHostCommand({ command: "composer", args: ["--version"], cwd: process.cwd(), env: composerManagedHostEnv(), allowedCwdRoots: [process.cwd()], timeoutMs: 10_000, maxOutputBytes: 64 * 1024, label: "detect Composer" })
return "composer"
} catch {
return ""
}
}
async function validateExistingDirectoryForOverlay(source: string, sourceRef: string): Promise<void> {
try {
const result = await stat(source)
if (result.isDirectory()) {
return
}
} catch {
// Throw a stable message below.
}
throw new Error(`Runtime overlay source must be an existing directory: ${sourceRef}`)
}
async function scopePhpAiClientSource(source: string, stagingRoot: string): Promise<string> {
const scoperPath = await resolvePhpScoper(stagingRoot)
const configPath = join(stagingRoot, "scoper.inc.php")
const scopedRoot = join(stagingRoot, "scoped")
await writeFile(configPath, phpAiClientScoperConfig())
await executeManagedHostCommand({
command: "php",
args: [scoperPath, "add-prefix", "--working-dir", source, "--config", configPath, "--output-dir", scopedRoot, "--force", "--no-interaction"],
cwd: stagingRoot,
allowedCwdRoots: [stagingRoot, source],
maxOutputBytes: 1024 * 1024 * 10,
label: "scope PHP source",
})
return scopedRoot
}
async function resolvePhpScoper(stagingRoot: string): Promise<string> {
const configured = process.env.WP_CODEBOX_PHP_SCOPER_PHAR
if (configured) {
return configured
}
const scoperPath = join(stagingRoot, "php-scoper.phar")
await executeManagedHostCommand({ command: "curl", args: ["-fsSL", PHP_SCOPER_URL, "-o", scoperPath], cwd: stagingRoot, allowedCwdRoots: [stagingRoot], maxOutputBytes: 1024 * 1024, label: "download php-scoper" })
return scoperPath
}
function phpAiClientScoperConfig(): string {
return `<?php
use Isolated\\Symfony\\Component\\Finder\\Finder;
return array(
'prefix' => 'WordPress\\\\AiClientDependencies',
'finders' => array(
Finder::create()
->files()
->ignoreVCS( true )
->notName( '/LICENSE|.*\\.md|.*\\.dist|Makefile/' )
->exclude( array( 'composer', 'doc', 'test', 'test_old', 'tests', 'Tests', 'vendor-bin' ) )
->in( 'vendor' ),
Finder::create()
->files()
->ignoreVCS( true )
->name( '*.php' )
->in( 'src' ),
),
'exclude-namespaces' => array(
'WordPress\\\\AiClient',
),
'exclude-files' => array(),
'exclude-constants' => array(
'/^ABSPATH$/',
'/^WPINC$/',
),
'exclude-functions' => array(),
'patchers' => array(
static function ( string $file_path, string $prefix, string $contents ): string {
if ( false === strpos( $file_path, 'php-http/discovery' ) ) {
return $contents;
}
$external_namespaces = array(
'GuzzleHttp',
'Http\\\\Adapter',
'Http\\\\Client\\\\Curl',
'Http\\\\Client\\\\Socket',
'Http\\\\Client\\\\Buzz',
'Http\\\\Client\\\\React',
'Buzz',
'Nyholm',
'Laminas',
'Symfony\\\\Component\\\\HttpClient',
'Phalcon\\\\Http',
'Slim\\\\Psr7',
'Kriswallsmith',
);
foreach ( $external_namespaces as $ns ) {
$escaped_ns = preg_quote( $ns, '/' );
$escaped_prefix = preg_quote( $prefix, '/' );
$contents = preg_replace( '/([\\'\"])' . $escaped_prefix . '\\\\\\\\' . $escaped_ns . '/', '$1' . $ns, $contents );
$contents = preg_replace( '/([\\'\"])' . $escaped_prefix . '\\\\' . $escaped_ns . '/', '$1' . $ns, $contents );
}
return $contents;
},
),
);
`
}
async function composerInstalledPackagesFromSource(source: string): Promise<ComposerInstalledPackage[]> {
const installedPath = join(source, "vendor", "composer", "installed.json")
let installed: unknown
try {
installed = JSON.parse(await readFile(installedPath, "utf8"))
} catch (error) {
throw new Error(`php-ai-client overlay requires Composer dependencies at vendor/composer/installed.json: ${error instanceof Error ? error.message : String(error)}`)
}
return composerInstalledPackages(installed)
}
async function copyScopedComposerDependencies(packages: ComposerInstalledPackage[], scopedRoot: string, thirdPartyTarget: string): Promise<void> {
for (const pkg of packages) {
if (pkg.name === "wordpress/php-ai-client") {
continue
}
for (const [namespacePrefix, sourceDirs] of Object.entries(pkg.autoload?.["psr-4"] ?? {})) {
const namespacePath = namespacePrefix.replace(/\\/g, "/").replace(/\/+$/, "")
for (const sourceDir of Array.isArray(sourceDirs) ? sourceDirs : [sourceDirs]) {
const packageSource = join(scopedRoot, "vendor", pkg.name, String(sourceDir).replace(/\/+$/, ""))
try {
const result = await stat(packageSource)
if (!result.isDirectory()) {
continue
}
} catch {
continue
}
await cp(packageSource, join(thirdPartyTarget, namespacePath), { recursive: true })
}
}
}
}
function dependencyNamespacePrefixes(packages: ComposerInstalledPackage[]): string[] {
const prefixes = new Set<string>()
for (const pkg of packages) {
if (pkg.name === "wordpress/php-ai-client") {
continue
}
for (const prefix of Object.keys(pkg.autoload?.["psr-4"] ?? {})) {
if (prefix && !prefix.startsWith("WordPress\\AiClient\\")) {
prefixes.add(prefix)
}
}
}
return [...prefixes].sort((a, b) => b.length - a.length)
}
async function scopePhpAiClientSourceDependencyReferences(sourceDirectory: string, namespacePrefixes: string[]): Promise<void> {
for (const entry of await readdir(sourceDirectory, { withFileTypes: true })) {
const path = join(sourceDirectory, entry.name)
if (entry.isDirectory()) {
await scopePhpAiClientSourceDependencyReferences(path, namespacePrefixes)
continue
}
if (!entry.isFile() || !entry.name.endsWith(".php")) {
continue
}
const original = await readFile(path, "utf8")
const transformed = scopeNamespaceReferences(original, namespacePrefixes)
if (transformed !== original) {
await writeFile(path, transformed)
}
}
}
function scopeNamespaceReferences(contents: string, namespacePrefixes: string[]): string {
let transformed = contents
for (const namespacePrefix of namespacePrefixes) {
const normalized = namespacePrefix.replace(/\\+$/, "\\")
const namespaceName = normalized.replace(/\\+$/, "")
const scoped = `WordPress\\AiClientDependencies\\${normalized}`
const scopedNamespaceName = `WordPress\\AiClientDependencies\\${namespaceName}`
const escaped = escapeRegExp(normalized)
const escapedNamespaceName = escapeRegExp(namespaceName)
transformed = transformed
.replace(new RegExp(`namespace\\s+${escapedNamespaceName}\\s*;`, "g"), `namespace ${scopedNamespaceName};`)
.replace(new RegExp(`([^A-Za-z0-9_\\\\])\\\\${escaped}`, "g"), (_match, prefix: string) => `${prefix}\\${scoped}`)
.replace(new RegExp(`([^A-Za-z0-9_\\\\])${escaped}`, "g"), (_match, prefix: string) => `${prefix}${scoped}`)
}
return transformed
}
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
}
interface ComposerInstalledPackage {
name: string
autoload?: { "psr-4"?: Record<string, string | string[]> }
}
function composerInstalledPackages(installed: unknown): ComposerInstalledPackage[] {
if (!installed || typeof installed !== "object") {
throw new Error("Composer installed.json is not an object")
}
const data = installed as { packages?: unknown; [key: number]: unknown }
const packages = Array.isArray(data.packages) ? data.packages : Array.isArray(installed) ? installed : undefined
if (!packages) {
throw new Error("Composer installed.json format is unsupported")
}
return packages.filter((pkg): pkg is ComposerInstalledPackage => Boolean(pkg && typeof pkg === "object" && typeof (pkg as ComposerInstalledPackage).name === "string"))
}
async function prunePhpAiClientThirdParty(thirdPartyTarget: string): Promise<void> {
const removePaths = [
"Http/Discovery/Composer",
"Http/Client",
"Http/Promise",
"Http/Discovery/HttpClientDiscovery.php",
"Http/Discovery/HttpAsyncClientDiscovery.php",
"Http/Discovery/MessageFactoryDiscovery.php",
"Http/Discovery/UriFactoryDiscovery.php",
"Http/Discovery/StreamFactoryDiscovery.php",
"Http/Discovery/NotFoundException.php",
"Http/Discovery/Psr17Factory.php",
"Http/Discovery/Psr18Client.php",
"Http/Discovery/Strategy/MockClientStrategy.php",
"Psr/EventDispatcher/ListenerProviderInterface.php",
"Psr/EventDispatcher/StoppableEventInterface.php",
"Psr/SimpleCache/CacheException.php",
"Psr/SimpleCache/InvalidArgumentException.php",
]
await Promise.all(removePaths.map((path) => rm(join(thirdPartyTarget, path), { recursive: true, force: true })))
}
async function writePhpAiClientAutoload(bundle: string): Promise<void> {
await writeFile(join(bundle, "autoload.php"), `<?php
/**
* Autoloader for the bundled PHP AI Client library.
*
* Generated by WP Codebox runtime overlay preparation.
*/
spl_autoload_register(
static function ( $class_name ) {
$client_prefix = 'WordPress\\\\AiClient\\\\';
$client_prefix_len = 19;
$scoped_prefix = 'WordPress\\\\AiClientDependencies\\\\';
$scoped_prefix_len = 31;
$base_dir = __DIR__;
if ( 0 === strncmp( $class_name, $client_prefix, $client_prefix_len ) ) {
$relative_class = substr( $class_name, $client_prefix_len );
$file = $base_dir . '/src/' . str_replace( '\\\\', '/', $relative_class ) . '.php';
if ( file_exists( $file ) ) {
require $file;
}
return;
}
if ( 0 === strncmp( $class_name, $scoped_prefix, $scoped_prefix_len ) ) {
$relative_class = substr( $class_name, $scoped_prefix_len );
$file = $base_dir . '/third-party/' . str_replace( '\\\\', '/', $relative_class ) . '.php';
if ( file_exists( $file ) ) {
require $file;
}
}
}
);
`)
}
async function directoryContentDigest(directory: string): Promise<string> {
const hash = createHash("sha256")
await hashDirectory(directory, directory, hash)
return hash.digest("hex")
}
async function hashDirectory(root: string, directory: string, hash: ReturnType<typeof createHash>): Promise<void> {
const entries = await readdir(directory, { withFileTypes: true })
entries.sort((a, b) => a.name.localeCompare(b.name))
for (const entry of entries) {
const path = join(directory, entry.name)
const relativePath = relative(root, path).replace(/\\/g, "/")
if (entry.isDirectory()) {
hash.update(`dir:${relativePath}\n`)
await hashDirectory(root, path, hash)
} else if (entry.isFile()) {
hash.update(`file:${relativePath}\n`)
hash.update(await readFile(path))
hash.update("\n")
}
}
}
export async function stagedFileMountType(source: string): Promise<MountSpec["type"]> {
return recipeMountType(source)
}
export async function recipeMountType(source: string, explicitType?: MountSpec["type"]): Promise<MountSpec["type"]> {
if (explicitType === "directory" || explicitType === "file") {
return explicitType
}
const result = await stat(source)
if (result.isDirectory()) {
return "directory"
}
if (result.isFile()) {
return "file"
}
throw new Error(`Recipe mount source must be a file or directory: ${source}`)
}
export function stagedFileProvenance(stagedFile: WorkspaceRecipeStagedFile, recipeDirectory: string): RecipeStagedFileProvenance {
return localPreparedSourceProvenance(stagedFile.source, recipeDirectory)
}
async function assertPreparedPluginFileExists(sourceDirectory: string, pluginFileRelativeToSource: string, sourceRef: string): Promise<void> {
try {
const result = await stat(join(sourceDirectory, pluginFileRelativeToSource))
if (result.isFile()) {
return
}
} catch {
// Throw a stable message below.
}
throw new Error(`Recipe extra plugin source did not contain expected plugin file ${pluginFileRelativeToSource}: ${sourceRef}`)
}
async function prepareRecipeSource(sourceRef: string, recipeDirectory: string, slug: string, expectedSha256?: string): Promise<PreparedExternalSource> {
const source = recipeSource(sourceRef, expectedSha256)
if (source.type === "local") {
return {
source: resolve(recipeDirectory, sourceRef),
cleanupPaths: [],