diff --git a/package.json b/package.json index 07aa186dc9..082b24d255 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ "bili-proxy": "./dist/index.js" }, "scripts": { - "build": "tsup", + "build": "tsup && node scripts/check-dist-import-annotations.mjs", "registry:snapshot": "node scripts/update-registry-snapshot.mjs", "codex-models:snapshot": "node scripts/update-codex-models-snapshot.mjs", "typecheck": "tsc --noEmit --project tsconfig.build.json", diff --git a/scripts/check-dist-import-annotations.mjs b/scripts/check-dist-import-annotations.mjs new file mode 100644 index 0000000000..ebe69b1509 --- /dev/null +++ b/scripts/check-dist-import-annotations.mjs @@ -0,0 +1,58 @@ +// Build gate: fail if any relative-specifier import()/require() call text +// survives into dist. All module code is bundled inline (splitting: false), +// so a relative specifier in dist is always anomalous — either an unresolved +// dynamic import (broken under every host) or a JSDoc `{import('...')}` type +// annotation that leaked out of the bundler. The second class is what kills +// the opencode plugin lane: opencode's plugin loader resolves those +// annotations as real files and dies with ENOENT before the plugin loads +// (Node ignores them, which is why the defect shipped silently). See the +// issue filed from #1234. + +import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs"; +import path from "node:path"; +import process from "node:process"; +import { fileURLToPath } from "node:url"; + +const RELATIVE_CALL = /(?:import|require)\(\s*['"]\.{1,2}\/[^'"]*['"][^)]*\)/g; + +export function findRelativeImportRefs(text) { + const hits = []; + let m; + RELATIVE_CALL.lastIndex = 0; + while ((m = RELATIVE_CALL.exec(text)) !== null) { + hits.push(m[0]); + } + return hits; +} + +export function checkDistImportAnnotations(distDir) { + const violations = []; + const walk = (dir) => { + for (const name of readdirSync(dir)) { + const full = path.join(dir, name); + const st = statSync(full); + if (st.isDirectory()) { walk(full); continue; } + if (!name.endsWith(".js")) continue; + const refs = findRelativeImportRefs(readFileSync(full, "utf8")); + if (refs.length > 0) violations.push({ file: full, refs }); + } + }; + walk(distDir); + return violations; +} + +const invoked = process.argv[1]; +// Realpath both sides: Node resolves entry-point symlinks, so argv[1] can differ from import.meta.url +const isMain = !!invoked && realpathSync(fileURLToPath(import.meta.url)) === realpathSync(invoked); +if (isMain) { + const distDir = process.argv[2] ?? "dist"; + const violations = checkDistImportAnnotations(distDir); + if (violations.length > 0) { + for (const v of violations) { + console.error(`dist-import-annotations: ${v.file}: ${v.refs.slice(0, 5).join(" ")}${v.refs.length > 5 ? ` … (+${v.refs.length - 5})` : ""}`); + } + console.error(`dist-import-annotations: FAIL — ${violations.reduce((n, v) => n + v.refs.length, 0)} relative import()/require() ref(s) across ${violations.length} file(s). These break host loaders that resolve JSDoc import() annotations as files (opencode) and indicate unresolved bundling.`); + process.exit(1); + } + console.log("dist-import-annotations: OK"); +} diff --git a/tests/dist-import-annotations.test.ts b/tests/dist-import-annotations.test.ts new file mode 100644 index 0000000000..77c199a844 --- /dev/null +++ b/tests/dist-import-annotations.test.ts @@ -0,0 +1,48 @@ +// Build-gate tests (scripts/check-dist-import-annotations.mjs): the gate must +// catch surviving JSDoc import() annotations and real relative dynamic +// imports, while passing bare specifiers, node: builtins, and clean bundles. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { findRelativeImportRefs, checkDistImportAnnotations } from "../scripts/check-dist-import-annotations.mjs"; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +test("findRelativeImportRefs catches JSDoc-style and real relative calls", () => { + const bad = [ + "/** @param {import('./client.js')} client */ function f() {}", + "const x = require('../core/request.js');", + "const y = import(\"./shared.js\").then((m) => m.f);", + "import( './spaced.js' )", + ].join("\n"); + const refs = findRelativeImportRefs(bad); + assert.equal(refs.length, 4); +}); + +test("findRelativeImportRefs passes bare specifiers, node: builtins, clean code", () => { + const good = [ + "const z = await import('zod');", + "await import('node:fs');", + 'require("crypto")', + "class C { constructor() {} }", + "export { a as b } from \"./other\";", + ].join("\n"); + assert.deepEqual(findRelativeImportRefs(good), []); +}); + +test("checkDistImportAnnotations walks dist recursively and reports per file", () => { + const root = mkdtempSync(path.join(tmpdir(), "bc-distgate-")); + try { + mkdirSync(path.join(root, "agent"), { recursive: true }); + writeFileSync(path.join(root, "index.js"), "export default 1;\n"); + writeFileSync(path.join(root, "agent", "opencode-native.js"), "var a = {import('./client.js')};\n"); + writeFileSync(path.join(root, "agent", "map-ignored.js.map"), JSON.stringify({ sourcesContent: ["{import('./x.js')}"] })); + const violations = checkDistImportAnnotations(root); + assert.equal(violations.length, 1); + assert.ok(violations[0].file.endsWith(path.join("agent", "opencode-native.js"))); + assert.equal(violations[0].refs.length, 1); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/tsup.config.ts b/tsup.config.ts index f7d6aa75c7..80023e7030 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -5,6 +5,20 @@ export default defineConfig({ format: ["esm"], target: "node20", platform: "node", + // Non-minified esbuild output KEEPS JSDoc comments attached to class + // members (verified empirically against esbuild bundled with tsup 8.x): + // undici ships class-body JSDoc like `@param {import('./client.js')}` and + // those annotations survive into dist verbatim. Node's ESM loader ignores + // them, but opencode's plugin loader resolves them as REAL files and dies + // with ENOENT → the whole plugin fails to load (silent dead lane; see the + // issue filed from #1234). minifyWhitespace makes esbuild drop all + // non-legal comments while keeping code structure intact (no identifier + // mangling, no syntax rewriting); legal/license footers stay via the + // default legalComments. scripts/check-dist-import-annotations.mjs fails + // the build if any relative import()/require() text ever reappears. + esbuildOptions(options) { + options.minifyWhitespace = true; + }, outDir: "dist", clean: true, sourcemap: true,