File size: 28,710 Bytes
4c76b0d | 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 | // Plugin SDK package guardrail tests cover package export and contract drift checks.
import fs from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { beforeAll, describe, expect, it } from "vitest";
import {
deprecatedBarrelPluginSdkEntrypoints,
deprecatedPublicPluginSdkEntrypoints,
packagedPrivatePluginSdkRuntimeEntrypoints,
privateLocalOnlyPluginSdkEntrypoints,
pluginSdkEntrypoints,
publicPluginOwnedSdkEntrypoints,
publicPluginSdkEntrypoints,
supportedBundledFacadeSdkEntrypoints,
} from "../../../scripts/lib/plugin-sdk-entries.mts";
import { expectNoReaddirSyncDuring } from "../../test-utils/fs-scan-assertions.js";
import {
listGitTrackedFiles,
toRepoPath,
toRepoRelativePath as toRepoRelativePathFromRoot,
} from "../../test-utils/repo-files.js";
const ROOT_DIR = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
const REPO_ROOT = resolve(ROOT_DIR, "..");
const SDK_SUBPATH_DOC_FILE = "docs/plugins/sdk-subpaths.md";
const PUBLIC_CONTRACT_REFERENCE_FILES = [
"docs/plugins/architecture.md",
"src/plugins/contracts/plugin-sdk-subpaths.test.ts",
] as const;
const TYPED_PUBLIC_CONTRACT_REFERENCE_FILES = [
"docs/plugins/sdk-entrypoints.md",
"docs/plugins/sdk-entrypoints/tool-policy-and-sandbox.md",
"docs/plugins/sdk-entrypoints/package-entries.md",
"docs/plugins/sdk-entrypoints/define-tool-plugin.md",
"docs/plugins/sdk-entrypoints/define-plugin-entry.md",
"docs/plugins/sdk-entrypoints/native-providers.md",
"docs/plugins/sdk-entrypoints/define-channel-plugin-entry.md",
"docs/plugins/sdk-entrypoints/define-setup-plugin-entry.md",
"docs/plugins/sdk-entrypoints/registration-mode.md",
] as const;
const PLUGIN_SDK_SUBPATH_PATTERN = /openclaw\/plugin-sdk\/([a-z0-9][a-z0-9-]*)\b/g;
const BUNDLED_PLUGIN_FACADE_LOADER_PATTERN =
/\bload(?:Activated)?BundledPluginPublicSurfaceModuleSync\b/;
const PRIVATE_BUNDLED_SDK_SURFACE_PATTERN =
/\b(?:Private helper surface|Narrow plugin-sdk surface for the bundled|Narrow .*runtime exports used by the bundled)\b/i;
const GENERIC_CORE_HELPER_FILES = ["src/polls.ts", "src/poll-params.ts"] as const;
const GENERIC_CORE_PLUGIN_OWNER_NAME_PATTERN =
/\b(?:imessage|discord|feishu|googlechat|matrix|mattermost|msteams|slack|telegram|whatsapp|zalo|zalouser)\b/gi;
const DEPRECATED_EXTENSION_SDK_SPECIFIERS = new Set([
"openclaw/plugin-sdk",
// Bundled code uses the canonical channel-config-schema subpath; the
// primitives/legacy shells stay export-compatible for third parties only.
"openclaw/plugin-sdk/channel-config-primitives",
"openclaw/plugin-sdk/channel-config-schema-legacy",
"openclaw/plugin-sdk/compat",
"openclaw/plugin-sdk/test-utils",
]);
const DEPRECATED_TEST_ALIAS_SPECIFIERS = new Set(["openclaw/plugin-sdk/test-utils"]);
const DEPRECATED_TEST_ALIAS_ALLOWED_REFERENCE_FILES = new Set([
"src/plugins/compat/registry.ts",
"src/plugins/contracts/plugin-sdk-package-contract-guardrails.test.ts",
]);
const MATRIX_RUNTIME_DEPS = [
"@matrix-org/matrix-sdk-crypto-wasm",
"@matrix-org/matrix-sdk-crypto-nodejs",
"fake-indexeddb",
"matrix-js-sdk",
"music-metadata",
] as const;
const trackedFilesByRoot = new Map<string, readonly string[] | null>();
function toRepoRelativePath(filePath: string): string {
return toRepoRelativePathFromRoot(REPO_ROOT, filePath);
}
function isSkippedTrackedPath(repoRelativePath: string): boolean {
return repoRelativePath
.split("/")
.some((part) => part === "dist" || part === "node_modules" || part === ".git");
}
function isCodeFile(filePath: string): boolean {
return /\.(?:[cm]?ts|tsx|mts|cts)$/.test(filePath);
}
function listTrackedFiles(root: string): string[] | null {
const relativeRoot = toRepoRelativePath(root);
if (!relativeRoot || relativeRoot.startsWith("..")) {
return null;
}
if (trackedFilesByRoot.has(relativeRoot)) {
const files = trackedFilesByRoot.get(relativeRoot);
return files ? [...files] : null;
}
const trackedFiles = listGitTrackedFiles({ repoRoot: REPO_ROOT, pathspecs: relativeRoot });
if (!trackedFiles) {
trackedFilesByRoot.set(relativeRoot, null);
return null;
}
const files = trackedFiles
.filter((line) => line.length > 0 && !isSkippedTrackedPath(line))
.map((line) => resolve(REPO_ROOT, line))
.filter((filePath) => fs.existsSync(filePath))
.toSorted();
trackedFilesByRoot.set(relativeRoot, files);
return [...files];
}
function listTrackedCodeFiles(root: string): string[] | null {
const files = listTrackedFiles(root);
return files?.filter(isCodeFile) ?? null;
}
function collectPluginSdkPackageExports(): string[] {
const packageJson = JSON.parse(fs.readFileSync(resolve(REPO_ROOT, "package.json"), "utf8")) as {
exports?: Record<string, unknown>;
};
const exports = packageJson.exports ?? {};
const subpaths: string[] = [];
for (const key of Object.keys(exports)) {
if (key === "./plugin-sdk") {
subpaths.push("index");
continue;
}
if (!key.startsWith("./plugin-sdk/")) {
continue;
}
subpaths.push(key.slice("./plugin-sdk/".length));
}
return subpaths.toSorted();
}
function collectTypedPluginSdkPackageExports(): Set<string> {
const packageJson = JSON.parse(fs.readFileSync(resolve(REPO_ROOT, "package.json"), "utf8")) as {
exports?: Record<string, unknown>;
};
const typedSubpaths = new Set<string>();
for (const [key, value] of Object.entries(packageJson.exports ?? {})) {
if (
key.startsWith("./plugin-sdk/") &&
value &&
typeof value === "object" &&
"types" in value &&
typeof value.types === "string"
) {
typedSubpaths.add(key.slice("./plugin-sdk/".length));
}
}
return typedSubpaths;
}
function collectPackExcludedPluginSdkDeclarations(): Set<string> {
const packageJson = readRootPackageJson();
return new Set(
(packageJson.files ?? [])
.map((entry) => /^!dist\/plugin-sdk\/([a-z0-9][a-z0-9-]*)\.d\.ts$/u.exec(entry)?.[1])
.filter((subpath): subpath is string => Boolean(subpath)),
);
}
function collectPluginSdkSubpathReferences(
files: readonly string[] = PUBLIC_CONTRACT_REFERENCE_FILES,
) {
const references: Array<{ file: string; subpath: string }> = [];
for (const file of files) {
const source = fs.readFileSync(resolve(REPO_ROOT, file), "utf8");
for (const match of source.matchAll(PLUGIN_SDK_SUBPATH_PATTERN)) {
const subpath = match[1];
if (!subpath) {
continue;
}
references.push({ file, subpath });
}
}
return references;
}
function collectDocumentedSdkSubpaths(): Set<string> {
const source = fs.readFileSync(resolve(REPO_ROOT, SDK_SUBPATH_DOC_FILE), "utf8");
return new Set(
[...source.matchAll(/`plugin-sdk\/([a-z0-9][a-z0-9-]*)`/g)]
.map((match) => match[1])
.filter((subpath): subpath is string => Boolean(subpath)),
);
}
function collectBundledPluginIds(): string[] {
const trackedFiles = listTrackedFiles(resolve(REPO_ROOT, "extensions"));
if (trackedFiles) {
return [
...new Set(
trackedFiles
.map((file) => toRepoRelativePath(file).split("/"))
.filter((parts) => parts.length > 2)
.map((parts) => parts[1])
.filter((pluginId): pluginId is string => Boolean(pluginId)),
),
].toSorted((a, b) => b.length - a.length || a.localeCompare(b));
}
return fs
.readdirSync(resolve(REPO_ROOT, "extensions"), { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
.toSorted((a, b) => b.length - a.length || a.localeCompare(b));
}
function collectPluginOwnedSdkEntrypoints(): string[] {
const pluginIds = collectBundledPluginIds();
return pluginSdkEntrypoints
.filter((entrypoint) =>
pluginIds.some(
(pluginId) => entrypoint === pluginId || entrypoint.startsWith(`${pluginId}-`),
),
)
.toSorted();
}
function collectClassificationOverlaps(classifications: Record<string, readonly string[]>) {
const seen = new Map<string, string[]>();
for (const [classification, entrypoints] of Object.entries(classifications)) {
for (const entrypoint of entrypoints) {
const current = seen.get(entrypoint) ?? [];
current.push(classification);
seen.set(entrypoint, current);
}
}
return [...seen.entries()]
.filter(([, matches]) => matches.length > 1)
.map(([entrypoint, matches]) => `${entrypoint}: ${matches.toSorted().join(", ")}`)
.toSorted();
}
function collectBundledFacadeSdkEntrypoints(): string[] {
const entrypoints: string[] = [];
for (const entrypoint of pluginSdkEntrypoints) {
const filePath = resolve(REPO_ROOT, "src/plugin-sdk", `${entrypoint}.ts`);
const source = fs.readFileSync(filePath, "utf8");
if (BUNDLED_PLUGIN_FACADE_LOADER_PATTERN.test(source)) {
entrypoints.push(entrypoint);
}
}
return entrypoints.toSorted();
}
function collectPrivateBundledSdkSurfaceEntrypoints(): string[] {
const entrypoints: string[] = [];
for (const entrypoint of pluginSdkEntrypoints) {
const filePath = resolve(REPO_ROOT, "src/plugin-sdk", `${entrypoint}.ts`);
const source = fs.readFileSync(filePath, "utf8");
if (PRIVATE_BUNDLED_SDK_SURFACE_PATTERN.test(source)) {
entrypoints.push(entrypoint);
}
}
return entrypoints.toSorted();
}
function collectGenericCoreOwnerNameLeaks(): Array<{ file: string; match: string }> {
const leaks: Array<{ file: string; match: string }> = [];
for (const file of GENERIC_CORE_HELPER_FILES) {
const source = fs.readFileSync(resolve(REPO_ROOT, file), "utf8");
for (const match of source.matchAll(GENERIC_CORE_PLUGIN_OWNER_NAME_PATTERN)) {
const ownerName = match[0];
if (!ownerName) {
continue;
}
leaks.push({ file, match: ownerName });
}
}
return leaks;
}
function readRootPackageJson(): {
dependencies?: Record<string, string>;
optionalDependencies?: Record<string, string>;
files?: string[];
} {
return JSON.parse(fs.readFileSync(resolve(REPO_ROOT, "package.json"), "utf8")) as {
dependencies?: Record<string, string>;
optionalDependencies?: Record<string, string>;
files?: string[];
};
}
function readMatrixPackageJson(): {
dependencies?: Record<string, string>;
optionalDependencies?: Record<string, string>;
} {
return JSON.parse(
fs.readFileSync(resolve(REPO_ROOT, "extensions/matrix/package.json"), "utf8"),
) as {
dependencies?: Record<string, string>;
optionalDependencies?: Record<string, string>;
};
}
function collectRuntimeDependencySpecs(packageJson: {
dependencies?: Record<string, string>;
optionalDependencies?: Record<string, string>;
}): Map<string, string> {
return new Map([
...Object.entries(packageJson.dependencies ?? {}),
...Object.entries(packageJson.optionalDependencies ?? {}),
]);
}
function collectExtensionFiles(dir: string): string[] {
const trackedFiles = listTrackedCodeFiles(dir);
if (trackedFiles) {
return trackedFiles;
}
const entries = fs.readdirSync(dir, { withFileTypes: true });
const files: string[] = [];
for (const entry of entries) {
if (entry.name === "dist" || entry.name === "node_modules") {
continue;
}
const nextPath = join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...collectExtensionFiles(nextPath));
continue;
}
if (!entry.isFile() || !/\.(?:[cm]?ts|tsx|mts|cts)$/.test(entry.name)) {
continue;
}
files.push(nextPath);
}
return files;
}
function isExtensionTestOrSupportPath(repoRelativePath: string): boolean {
return (
/(?:^|\/)(?:__tests__|tests|test-support)(?:\/|$)/.test(repoRelativePath) ||
/(?:^|\/)test-support\.[cm]?tsx?$/.test(repoRelativePath) ||
/(?:^|\/)test-helpers\.[cm]?tsx?$/.test(repoRelativePath) ||
/(?:^|\/)test-harness\.[cm]?tsx?$/.test(repoRelativePath) ||
/(?:^|\/)test-runtime\.[cm]?tsx?$/.test(repoRelativePath) ||
/\.test-support\.[cm]?tsx?$/.test(repoRelativePath) ||
/\.test-helpers\.[cm]?tsx?$/.test(repoRelativePath) ||
/\.test-harness\.[cm]?tsx?$/.test(repoRelativePath) ||
/\.test\.[cm]?tsx?$/.test(repoRelativePath)
);
}
function collectExtensionCoreImportLeaks(): Array<{ file: string; specifier: string }> {
const leaks: Array<{ file: string; specifier: string }> = [];
const importPattern = /\b(?:import|export)\b[\s\S]*?\bfrom\s*["']((?:\.\.\/)+src\/[^"']+)["']/g;
for (const file of collectExtensionFiles(resolve(REPO_ROOT, "extensions"))) {
const repoRelativePath = toRepoRelativePath(file);
if (isExtensionTestOrSupportPath(repoRelativePath)) {
continue;
}
const extensionRootMatch = /^(.*?\/extensions\/[^/]+)/.exec(toRepoPath(file));
const extensionRoot = extensionRootMatch?.[1];
const source = fs.readFileSync(file, "utf8");
for (const match of source.matchAll(importPattern)) {
const specifier = match[1];
if (!specifier) {
continue;
}
const resolvedSpecifier = toRepoPath(resolve(dirname(file), specifier));
if (extensionRoot && resolvedSpecifier.startsWith(`${extensionRoot}/`)) {
continue;
}
leaks.push({
file: repoRelativePath,
specifier,
});
}
}
return leaks;
}
function collectExtensionTestHelperImportLeaks(): Array<{ file: string; specifier: string }> {
const leaks: Array<{ file: string; specifier: string }> = [];
const importPatterns = [
/\b(?:import|export)\b[\s\S]*?\bfrom\s*["']((?:\.\.\/)+test\/helpers\/[^"']+)["']/g,
/\bimport\s*\(\s*["']((?:\.\.\/)+test\/helpers\/[^"']+)["']\s*\)/g,
/\bvi\.(?:mock|doMock)\s*\(\s*["']((?:\.\.\/)+test\/helpers\/[^"']+)["']/g,
];
for (const file of collectExtensionFiles(resolve(REPO_ROOT, "extensions"))) {
const repoRelativePath = toRepoRelativePath(file);
if (isExtensionTestOrSupportPath(repoRelativePath)) {
continue;
}
const source = fs.readFileSync(file, "utf8");
for (const importPattern of importPatterns) {
for (const match of source.matchAll(importPattern)) {
const specifier = match[1];
if (!specifier) {
continue;
}
leaks.push({
file: repoRelativePath,
specifier,
});
}
}
}
return leaks;
}
function collectDeprecatedExtensionSdkImports(): Array<{ file: string; specifier: string }> {
const leaks: Array<{ file: string; specifier: string }> = [];
const importPatterns = [
/\b(?:import|export)\b[\s\S]*?\bfrom\s*["'](openclaw\/plugin-sdk(?:\/[a-z0-9][a-z0-9-]*)?)["']/g,
/\bimport\s*\(\s*["'](openclaw\/plugin-sdk(?:\/[a-z0-9][a-z0-9-]*)?)["']\s*\)/g,
/\bvi\.(?:mock|doMock)\s*\(\s*["'](openclaw\/plugin-sdk(?:\/[a-z0-9][a-z0-9-]*)?)["']/g,
];
for (const file of collectExtensionFiles(resolve(REPO_ROOT, "extensions"))) {
const repoRelativePath = toRepoRelativePath(file);
const source = fs.readFileSync(file, "utf8");
for (const importPattern of importPatterns) {
for (const match of source.matchAll(importPattern)) {
const specifier = match[1];
if (!specifier || !DEPRECATED_EXTENSION_SDK_SPECIFIERS.has(specifier)) {
continue;
}
leaks.push({
file: repoRelativePath,
specifier,
});
}
}
}
return leaks;
}
function collectCodeFiles(dir: string): string[] {
const trackedFiles = listTrackedCodeFiles(dir);
if (trackedFiles) {
return trackedFiles;
}
const files: string[] = [];
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (entry.name === "dist" || entry.name === "node_modules" || entry.name === ".git") {
continue;
}
const nextPath = join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...collectCodeFiles(nextPath));
continue;
}
if (!entry.isFile() || !/\.(?:[cm]?ts|tsx|mts|cts)$/.test(entry.name)) {
continue;
}
files.push(nextPath);
}
return files;
}
function collectDeprecatedTestAliasImports(): string[] {
const leaks: Array<{ file: string; specifier: string }> = [];
const importPatterns = [
/\b(?:import|export)\b[\s\S]*?\bfrom\s*["'](openclaw\/plugin-sdk\/test-utils)["']/g,
/\bimport\s*\(\s*["'](openclaw\/plugin-sdk\/test-utils)["']\s*\)/g,
/\bvi\.(?:mock|doMock)\s*\(\s*["'](openclaw\/plugin-sdk\/test-utils)["']/g,
];
for (const root of ["src", "test", "extensions", "packages"]) {
for (const file of collectCodeFiles(resolve(REPO_ROOT, root))) {
const repoRelativePath = toRepoRelativePath(file);
if (DEPRECATED_TEST_ALIAS_ALLOWED_REFERENCE_FILES.has(repoRelativePath)) {
continue;
}
const source = fs.readFileSync(file, "utf8");
for (const importPattern of importPatterns) {
for (const match of source.matchAll(importPattern)) {
const specifier = match[1];
if (!specifier || !DEPRECATED_TEST_ALIAS_SPECIFIERS.has(specifier)) {
continue;
}
leaks.push({
file: repoRelativePath,
specifier,
});
}
}
}
}
return leaks.map((entry) => `${entry.file}: ${entry.specifier}`).toSorted();
}
function collectWorkspaceCodeFiles(): string[] {
const files: string[] = [];
for (const root of ["src", "test", "extensions", "packages", "scripts"]) {
const dir = resolve(REPO_ROOT, root);
if (fs.existsSync(dir)) {
files.push(...collectCodeFiles(dir));
}
}
return files;
}
function hasWildcardReexport(entrypoint: string): boolean {
const source = fs.readFileSync(resolve(REPO_ROOT, "src/plugin-sdk", `${entrypoint}.ts`), "utf8");
return /^\s*export\s+(?:type\s+)?\*\s+from\s+["'][^"']+["']/mu.test(source);
}
function collectExtensionProductionSdkSubpathImports(subpaths: ReadonlySet<string>): string[] {
const imports = new Set<string>();
const importPatterns = [
/\b(?:import|export)\b[\s\S]*?\bfrom\s*["']openclaw\/plugin-sdk\/([a-z0-9][a-z0-9-]*)["']/g,
/\bimport\s*\(\s*["']openclaw\/plugin-sdk\/([a-z0-9][a-z0-9-]*)["']\s*\)/g,
/\bvi\.(?:mock|doMock)\s*\(\s*["']openclaw\/plugin-sdk\/([a-z0-9][a-z0-9-]*)["']/g,
];
for (const file of collectExtensionFiles(resolve(REPO_ROOT, "extensions"))) {
const repoRelativePath = toRepoRelativePath(file);
if (isExtensionTestOrSupportPath(repoRelativePath)) {
continue;
}
const source = fs.readFileSync(file, "utf8");
for (const importPattern of importPatterns) {
for (const match of source.matchAll(importPattern)) {
const subpath = match[1];
if (subpath && subpaths.has(subpath)) {
imports.add(`${repoRelativePath}: openclaw/plugin-sdk/${subpath}`);
}
}
}
}
return [...imports].toSorted();
}
describe("plugin-sdk package contract guardrails", () => {
let deprecatedTestAliasImports: string[] = [];
beforeAll(() => {
deprecatedTestAliasImports = collectDeprecatedTestAliasImports();
});
it("lists package guardrail scan inputs from git without walking roots", () => {
expectNoReaddirSyncDuring(() => {
const pluginIds = collectBundledPluginIds();
const extensionFiles = collectExtensionFiles(resolve(REPO_ROOT, "extensions"));
const workspaceFiles = collectWorkspaceCodeFiles();
expect(pluginIds.length).toBeGreaterThan(0);
expect(extensionFiles.length).toBeGreaterThan(0);
expect(workspaceFiles.length).toBeGreaterThan(extensionFiles.length);
});
});
it("keeps plugin-sdk entrypoint metadata unique", () => {
const counts = new Map<string, number>();
for (const entrypoint of pluginSdkEntrypoints) {
counts.set(entrypoint, (counts.get(entrypoint) ?? 0) + 1);
}
const duplicates = [...counts.entries()]
.filter(([, count]) => count > 1)
.map(([entrypoint]) => entrypoint)
.toSorted();
expect(duplicates).toStrictEqual([]);
});
it("keeps package.json exports aligned with built plugin-sdk entrypoints", () => {
const packageExports = collectPluginSdkPackageExports();
const typedPackageExports = collectTypedPluginSdkPackageExports();
expect(packageExports).toEqual(
[...publicPluginSdkEntrypoints, ...packagedPrivatePluginSdkRuntimeEntrypoints].toSorted(),
);
expect([...typedPackageExports].toSorted()).toEqual([...publicPluginSdkEntrypoints].toSorted());
});
it("keeps Vitest-backed SDK test helpers local-only", () => {
const localOnly = new Set(privateLocalOnlyPluginSdkEntrypoints);
expect(
["plugin-test-contracts", "provider-test-contracts"].every((entrypoint) =>
localOnly.has(entrypoint),
),
).toBe(true);
});
it("keeps configured local-origin fetch helpers out of deprecated infra-runtime", () => {
const source = fs.readFileSync(resolve(REPO_ROOT, "src/plugin-sdk/infra-runtime.ts"), "utf8");
expect(source).not.toMatch(/export\s+\*\s+from\s+["']\.\.\/infra\/net\/fetch-guard\.js["']/);
expect(source).not.toContain("fetchConfiguredLocalOriginWithSsrFGuard");
expect(source).not.toContain("GuardedFetchConfiguredLocalOriginOptions");
});
it("keeps configured local-origin fetch helpers out of the public SSRF runtime", async () => {
const ssrfRuntime = await import("../../plugin-sdk/ssrf-runtime.js");
expect(ssrfRuntime).not.toHaveProperty("fetchConfiguredLocalOriginWithSsrFGuard");
});
it("keeps memory provenance mutation out of the packaged Memory Core facade", async () => {
const memoryCoreRuntime = await import("../../plugin-sdk/memory-core-host-runtime-core.js");
expect(memoryCoreRuntime).not.toHaveProperty("recordMemoryArtifactWriteProvenance");
});
it("keeps bundled plugin SDK compatibility subpaths explicitly classified", () => {
const entrypoints = new Set(pluginSdkEntrypoints);
const supported = new Set<string>(supportedBundledFacadeSdkEntrypoints);
const localOnly = new Set<string>(privateLocalOnlyPluginSdkEntrypoints);
const unknownSupported = [...supported].filter((entrypoint) => !entrypoints.has(entrypoint));
const unknownLocalOnly = [...localOnly].filter((entrypoint) => !entrypoints.has(entrypoint));
const unclassifiedBundledFacades = collectBundledFacadeSdkEntrypoints().filter(
(entrypoint) => !supported.has(entrypoint) && !localOnly.has(entrypoint),
);
const unclassifiedPrivateSurfaces = collectPrivateBundledSdkSurfaceEntrypoints().filter(
(entrypoint) => !localOnly.has(entrypoint),
);
expect({
unknownSupported,
unknownLocalOnly,
unclassifiedBundledFacades,
unclassifiedPrivateSurfaces,
}).toEqual({
unknownSupported: [],
unknownLocalOnly: [],
unclassifiedBundledFacades: [],
unclassifiedPrivateSurfaces: [],
});
});
it("keeps plugin-owned SDK subpaths explicitly classified and documented", () => {
const entrypoints = new Set(pluginSdkEntrypoints);
const supported = new Set<string>(supportedBundledFacadeSdkEntrypoints);
const publicOwned = new Set<string>(publicPluginOwnedSdkEntrypoints);
const localOnly = new Set<string>(privateLocalOnlyPluginSdkEntrypoints);
const documented = collectDocumentedSdkSubpaths();
const pluginOwnedEntrypoints = collectPluginOwnedSdkEntrypoints();
const classified = new Set([...supported, ...publicOwned, ...localOnly]);
const unknownPublicOwned = [...publicOwned].filter(
(entrypoint) => !entrypoints.has(entrypoint),
);
const classificationOverlaps = collectClassificationOverlaps({
supported: supportedBundledFacadeSdkEntrypoints,
publicOwned: publicPluginOwnedSdkEntrypoints,
localOnly: privateLocalOnlyPluginSdkEntrypoints,
});
const unclassifiedPluginOwned = pluginOwnedEntrypoints.filter(
(entrypoint) => !classified.has(entrypoint),
);
const undocumentedPluginOwned = pluginOwnedEntrypoints.filter(
(entrypoint) => !documented.has(entrypoint),
);
expect({
unknownPublicOwned,
classificationOverlaps,
unclassifiedPluginOwned,
undocumentedPluginOwned,
}).toEqual({
unknownPublicOwned: [],
classificationOverlaps: [],
unclassifiedPluginOwned: [],
undocumentedPluginOwned: [],
});
});
it("keeps curated public plugin-sdk references on exported built subpaths", () => {
const entrypoints = new Set(pluginSdkEntrypoints);
const exports = new Set(collectPluginSdkPackageExports());
const localOnly = new Set(privateLocalOnlyPluginSdkEntrypoints);
const failures: string[] = [];
for (const reference of collectPluginSdkSubpathReferences()) {
const missingFrom: string[] = [];
if (!entrypoints.has(reference.subpath)) {
missingFrom.push("scripts/lib/plugin-sdk-entrypoints.json");
}
if (!exports.has(reference.subpath) && !localOnly.has(reference.subpath)) {
missingFrom.push("package.json exports");
}
if (missingFrom.length === 0) {
continue;
}
failures.push(
`${reference.file} references openclaw/plugin-sdk/${reference.subpath}, but ${reference.subpath} is missing from ${missingFrom.join(" and ")}`,
);
}
expect(failures).toStrictEqual([]);
});
it("keeps SDK entrypoint guide imports on typed public package exports", () => {
const publicEntrypoints = new Set(publicPluginSdkEntrypoints);
const typedExports = collectTypedPluginSdkPackageExports();
const excludedDeclarations = collectPackExcludedPluginSdkDeclarations();
const failures = collectPluginSdkSubpathReferences(TYPED_PUBLIC_CONTRACT_REFERENCE_FILES)
.filter(
({ subpath }) =>
!publicEntrypoints.has(subpath) ||
!typedExports.has(subpath) ||
excludedDeclarations.has(subpath),
)
.map(
({ file, subpath }) =>
`${file} references openclaw/plugin-sdk/${subpath}, but its declaration is not included in the typed public package`,
);
expect(failures).toStrictEqual([]);
});
it("keeps deprecated public SDK subpaths unused by extension production code", () => {
const publicEntrypoints = new Set(publicPluginSdkEntrypoints);
const unknownDeprecated = deprecatedPublicPluginSdkEntrypoints.filter(
(entrypoint) => !publicEntrypoints.has(entrypoint),
);
const extensionImports = collectExtensionProductionSdkSubpathImports(
new Set<string>(deprecatedPublicPluginSdkEntrypoints),
);
expect({ unknownDeprecated, extensionImports }).toEqual({
unknownDeprecated: [],
extensionImports: [],
});
});
it("keeps deprecated SDK barrels explicit and buildable", () => {
const entrypoints = new Set(pluginSdkEntrypoints);
const unknownDeprecatedBarrels = deprecatedBarrelPluginSdkEntrypoints.filter(
(entrypoint) => !entrypoints.has(entrypoint),
);
const nonBarrels = deprecatedBarrelPluginSdkEntrypoints.filter(
(entrypoint) => !hasWildcardReexport(entrypoint),
);
expect({ unknownDeprecatedBarrels, nonBarrels }).toEqual({
unknownDeprecatedBarrels: [],
nonBarrels: [],
});
});
it("keeps Matrix dependencies local to the Matrix plugin", () => {
const rootPackageJson = readRootPackageJson();
const rootRuntimeDeps = collectRuntimeDependencySpecs(rootPackageJson);
const matrixPackageJson = readMatrixPackageJson();
const matrixRuntimeDeps = collectRuntimeDependencySpecs(matrixPackageJson);
expect(rootPackageJson.files).toContain("!dist/extensions/matrix/**");
for (const dep of MATRIX_RUNTIME_DEPS) {
expect(matrixRuntimeDeps.get(dep)).toBeTypeOf("string");
expect(matrixRuntimeDeps.get(dep)).not.toBe("");
expect(rootRuntimeDeps.has(dep)).toBe(false);
}
expect(rootRuntimeDeps.has("@openclaw/plugin-package-contract")).toBe(false);
});
it("keeps extension sources on public sdk or local package seams", () => {
expect(collectExtensionCoreImportLeaks()).toStrictEqual([]);
});
it("keeps extension production sources off repo test helpers", () => {
expect(collectExtensionTestHelperImportLeaks()).toStrictEqual([]);
});
it("keeps extension sources off deprecated plugin-sdk compatibility imports", () => {
expect(collectDeprecatedExtensionSdkImports()).toStrictEqual([]);
});
it("keeps real tests off the deprecated plugin-sdk test-utils alias", () => {
expect(deprecatedTestAliasImports).toStrictEqual([]);
});
it("keeps generic core poll helpers free of plugin owner names", () => {
expect(collectGenericCoreOwnerNameLeaks()).toStrictEqual([]);
});
});
|