|
| 1 | +// Composes explicitly selected source plugins into a custom core distribution. |
| 2 | +import fs from "node:fs/promises"; |
| 3 | +import path from "node:path"; |
| 4 | +import { isDeepStrictEqual } from "node:util"; |
| 5 | +import { satisfies, valid } from "semver"; |
| 6 | +import { validateBundledPackageDependencyAlignment } from "../package-source-dependencies.mjs"; |
| 7 | +import { |
| 8 | + collectBundledPluginBuildEntries, |
| 9 | + collectRootPackageExcludedExtensionDirs, |
| 10 | + DOCKER_SELECTED_PLUGIN_BUILD_IDS_ENV, |
| 11 | + NON_PACKAGED_BUNDLED_PLUGIN_DIRS, |
| 12 | +} from "./bundled-plugin-build-entries.mjs"; |
| 13 | +import { assertRealOutputRoot } from "./output-root-guard.mjs"; |
| 14 | +import { |
| 15 | + PACKAGE_DIST_INVENTORY_RELATIVE_PATH, |
| 16 | + PACKAGE_INSTALL_GUARD_RELATIVE_PATH, |
| 17 | +} from "./package-dist-inventory-contract.mts"; |
| 18 | + |
| 19 | +type PackageJson = { |
| 20 | + name: string; |
| 21 | + version: string; |
| 22 | + files: string[]; |
| 23 | + dependencies?: Record<string, string>; |
| 24 | + optionalDependencies?: Record<string, string>; |
| 25 | + peerDependencies?: Record<string, string>; |
| 26 | + peerDependenciesMeta?: Record<string, { optional?: boolean }>; |
| 27 | +}; |
| 28 | + |
| 29 | +export function resolvePackageBundledPlugins(sourceDir: string, pluginIds: string[]) { |
| 30 | + const ids = [...new Set(pluginIds)].toSorted(); |
| 31 | + if (ids.length === 0) { |
| 32 | + return []; |
| 33 | + } |
| 34 | + const entries = collectBundledPluginBuildEntries({ |
| 35 | + cwd: sourceDir, |
| 36 | + env: { [DOCKER_SELECTED_PLUGIN_BUILD_IDS_ENV]: ids.join(",") }, |
| 37 | + }); |
| 38 | + const excluded = collectRootPackageExcludedExtensionDirs({ cwd: sourceDir }); |
| 39 | + return ids.map((id) => { |
| 40 | + const entry = entries.find((candidate) => candidate.id === id); |
| 41 | + if (!entry?.hasPackageJson || !excluded.has(id) || NON_PACKAGED_BUNDLED_PLUGIN_DIRS.has(id)) { |
| 42 | + throw new Error( |
| 43 | + `--bundle-plugin requires a source plugin excluded from the core package: ${id}`, |
| 44 | + ); |
| 45 | + } |
| 46 | + return entry; |
| 47 | + }); |
| 48 | +} |
| 49 | + |
| 50 | +/** Called under the canonical packer's source lifecycle lock, before bundling workspace deps. */ |
| 51 | +export async function preparePackageBundledPlugins(sourceDir: string, pluginIds: string[]) { |
| 52 | + const selected = resolvePackageBundledPlugins(sourceDir, pluginIds); |
| 53 | + if (selected.length === 0) { |
| 54 | + return async () => {}; |
| 55 | + } |
| 56 | + assertRealOutputRoot(path.join(sourceDir, "dist")); |
| 57 | + const packagePath = path.join(sourceDir, "package.json"); |
| 58 | + const original = await fs.readFile(packagePath, "utf8"); |
| 59 | + const packageJson = JSON.parse(original) as PackageJson; |
| 60 | + for (const { id, sourceEntries } of selected) { |
| 61 | + const sourcePackage = JSON.parse( |
| 62 | + await fs.readFile(path.join(sourceDir, "extensions", id, "package.json"), "utf8"), |
| 63 | + ) as PackageJson; |
| 64 | + const pluginRoot = path.join(sourceDir, "dist", "extensions", id); |
| 65 | + const builtPackage = JSON.parse( |
| 66 | + await fs.readFile(path.join(pluginRoot, "package.json"), "utf8"), |
| 67 | + ) as PackageJson; |
| 68 | + const manifest = JSON.parse( |
| 69 | + await fs.readFile(path.join(pluginRoot, "openclaw.plugin.json"), "utf8"), |
| 70 | + ) as { id: string }; |
| 71 | + if ( |
| 72 | + manifest.id !== id || |
| 73 | + (["name", "version", "dependencies", "optionalDependencies"] as const).some( |
| 74 | + (key) => !isDeepStrictEqual(builtPackage[key], sourcePackage[key]), |
| 75 | + ) |
| 76 | + ) { |
| 77 | + throw new Error( |
| 78 | + `Built plugin ${id} does not match source metadata; rebuild before packaging`, |
| 79 | + ); |
| 80 | + } |
| 81 | + for (const entry of sourceEntries) { |
| 82 | + await fs.access(path.join(pluginRoot, entry.replace(/\.[^.]+$/u, ".js"))); |
| 83 | + } |
| 84 | + for (const section of ["dependencies", "optionalDependencies"] as const) { |
| 85 | + const dependencies = sourcePackage[section] ?? {}; |
| 86 | + for (const [name, spec] of Object.entries(dependencies)) { |
| 87 | + if (valid(spec) !== spec) { |
| 88 | + throw new Error( |
| 89 | + `Selected plugin ${id} requires an exact dependency pin: ${name}@${spec}`, |
| 90 | + ); |
| 91 | + } |
| 92 | + } |
| 93 | + for (const existing of [packageJson.dependencies, packageJson.optionalDependencies]) { |
| 94 | + validateBundledPackageDependencyAlignment({ |
| 95 | + bundledDependencies: dependencies, |
| 96 | + bundledPackageLabel: `selected plugin ${id}`, |
| 97 | + rootDependencies: { ...dependencies, ...existing }, |
| 98 | + }); |
| 99 | + } |
| 100 | + packageJson[section] = { ...packageJson[section], ...dependencies }; |
| 101 | + } |
| 102 | + } |
| 103 | + // A required dependency must not remain optional when another selected owner needs it. |
| 104 | + for (const name of Object.keys(packageJson.dependencies ?? {})) { |
| 105 | + delete packageJson.optionalDependencies?.[name]; |
| 106 | + } |
| 107 | + for (const { id, packageJson: metadata } of selected) { |
| 108 | + const plugin = metadata as PackageJson; |
| 109 | + for (const [name, range] of Object.entries(plugin.peerDependencies ?? {})) { |
| 110 | + const version = |
| 111 | + name === packageJson.name |
| 112 | + ? packageJson.version |
| 113 | + : (packageJson.dependencies?.[name] ?? packageJson.optionalDependencies?.[name]); |
| 114 | + if ( |
| 115 | + (!version && !plugin.peerDependenciesMeta?.[name]?.optional) || |
| 116 | + (version && !satisfies(version, range)) |
| 117 | + ) { |
| 118 | + throw new Error(`Selected plugin ${id} requires peer ${name}@${range} in the distribution`); |
| 119 | + } |
| 120 | + } |
| 121 | + } |
| 122 | + const exclusions = new Set(selected.map(({ id }) => `!dist/extensions/${id}/**`)); |
| 123 | + packageJson.files = packageJson.files.filter((entry) => !exclusions.has(entry)); |
| 124 | + const snapshots = await Promise.all( |
| 125 | + ["package.json", PACKAGE_DIST_INVENTORY_RELATIVE_PATH, PACKAGE_INSTALL_GUARD_RELATIVE_PATH].map( |
| 126 | + async (relativePath) => { |
| 127 | + const target = path.join(sourceDir, relativePath); |
| 128 | + const bytes = await fs.readFile(target).catch((error: unknown) => { |
| 129 | + if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) { |
| 130 | + throw error; |
| 131 | + } |
| 132 | + return null; |
| 133 | + }); |
| 134 | + return { target, bytes }; |
| 135 | + }, |
| 136 | + ), |
| 137 | + ); |
| 138 | + const cleanup = async (preparationFailure?: { cause: unknown }) => { |
| 139 | + const results = await Promise.allSettled( |
| 140 | + snapshots.map(({ target, bytes }) => |
| 141 | + bytes === null ? fs.rm(target, { force: true }) : fs.writeFile(target, bytes), |
| 142 | + ), |
| 143 | + ); |
| 144 | + const failures = results.filter((result) => result.status === "rejected"); |
| 145 | + if (failures.length) { |
| 146 | + throw new AggregateError( |
| 147 | + [ |
| 148 | + ...(preparationFailure ? [preparationFailure.cause] : []), |
| 149 | + ...failures.map((result) => result.reason), |
| 150 | + ], |
| 151 | + "Selected plugin package cleanup failed", |
| 152 | + preparationFailure, |
| 153 | + ); |
| 154 | + } |
| 155 | + }; |
| 156 | + try { |
| 157 | + await fs.writeFile(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`); |
| 158 | + // Inventory must see the custom manifest before pack, or postinstall would prune the plugin. |
| 159 | + const { writePackageDistInventoryForPublish } = await import("./package-dist-inventory.ts"); |
| 160 | + await writePackageDistInventoryForPublish(sourceDir); |
| 161 | + return cleanup; |
| 162 | + } catch (error) { |
| 163 | + await cleanup({ cause: error }); |
| 164 | + throw error; |
| 165 | + } |
| 166 | +} |
0 commit comments