Skip to content

Commit 83e75f5

Browse files
authored
fix(tooling): preserve compiled plugin loading in source Gateways (#135077)
Select the documented ESM-only tsx preload so compiled dependencies keep their import export conditions. Preserve existing cache policy and regression-test wrapper/direct preload module identity, TypeScript aliases, and CommonJS callers. Fixes #134864.
1 parent 4fb5d93 commit 83e75f5

5 files changed

Lines changed: 91 additions & 6 deletions

File tree

‎docs/reference/test.md‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -178,9 +178,15 @@ reconcile dependencies before the remote wrapper starts.
178178

179179
## Core commands
180180

181-
Maintained JavaScript tooling wrappers and root package commands use tsx's
182-
in-process transform cache. They skip its shared disk cache before the loader
183-
starts, and child tooling inherits that policy. This cache policy does not clean
181+
Maintained JavaScript tooling wrappers and root package commands load TypeScript
182+
through `scripts/tsx.mjs`, using tsx's ESM entry. This preserves native loading of
183+
compiled ESM plugins and their import-only dependencies, including when loaded
184+
through `require()`. Source TypeScript imports and tsconfig path aliases remain
185+
available.
186+
187+
These launchers retain tsx's in-process transform cache and Node's module cache.
188+
They skip tsx's shared disk cache before the loader starts, and child tooling
189+
inherits that policy. This cache policy does not clean
184190
existing temporary directories, Node or Vitest caches, or other global caches. Standalone
185191
`pnpm ui:build` keeps native startup and applies the same preload to its post-build
186192
validators; it does not require `TSX_DISABLE_CACHE` in the invoking shell. Raw

‎scripts/lib/tsx-cli-shim.mjs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,9 @@ function resolveTsxImport(checkoutRoot) {
4141
].filter(Boolean)) {
4242
try {
4343
const require = createRequire(path.join(candidateRoot, "package.json"));
44-
const importUrl = pathToFileURL(require.resolve("tsx")).href;
44+
// Keep compiled ESM native: tsx's CJS hook rewrites its import-only
45+
// dependency edges into require() calls with incompatible export conditions.
46+
const importUrl = pathToFileURL(require.resolve("tsx/esm")).href;
4547
const selectedModulesDir =
4648
candidateRoot === hydratedTsxRoot
4749
? path.dirname(candidateRoot)

‎test/scripts/direct-run-entrypoints.test-support.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { copyFileSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
22
import { tmpdir } from "node:os";
33
import path from "node:path";
4+
import { pathToFileURL } from "node:url";
45
import { inspect } from "node:util";
56
import { runNodeScript } from "../helpers/run-node-script.js";
67

@@ -26,6 +27,51 @@ export const TSX_SHIM_WRAPPERS = [
2627
"scripts/perf/summarize-cpuprofile.mjs",
2728
] as const;
2829

30+
export function writeEsmPluginFixture(fixtureRoot: string) {
31+
const pluginRoot = path.join(fixtureRoot, "compiled-plugin");
32+
const dependencyRoot = path.join(pluginRoot, "node_modules", "import-only");
33+
mkdirSync(dependencyRoot, { recursive: true });
34+
writeFileSync(path.join(pluginRoot, "package.json"), JSON.stringify({ type: "module" }));
35+
writeFileSync(
36+
path.join(dependencyRoot, "package.json"),
37+
JSON.stringify({ type: "module", exports: { import: "./index.js" } }),
38+
);
39+
writeFileSync(path.join(dependencyRoot, "index.js"), 'export const value = "import-only";');
40+
const pluginPath = path.join(pluginRoot, "index.js");
41+
writeFileSync(
42+
pluginPath,
43+
`export { value } from "import-only";
44+
globalThis.pluginEvaluations = (globalThis.pluginEvaluations ?? 0) + 1;
45+
export const instance = {};
46+
`,
47+
);
48+
writeFileSync(
49+
path.join(pluginRoot, "loader.cjs"),
50+
'module.exports = { load: () => require("./index.js") };',
51+
);
52+
return `
53+
import assert from "node:assert/strict";
54+
import { createRequire } from "node:module";
55+
import { parseBoolean } from "@openclaw/normalization-core/boolean-coercion";
56+
enum Transformed { Value = "transformed" }
57+
try {
58+
const require = createRequire(${JSON.stringify(pathToFileURL(pluginPath).href)});
59+
const loader = require("./loader.cjs");
60+
const first = loader.load();
61+
const imported = await import(${JSON.stringify(pathToFileURL(pluginPath).href)});
62+
assert.strictEqual(loader.load(), first);
63+
assert.strictEqual(imported.instance, first.instance);
64+
assert.strictEqual(require("./loader.cjs"), loader);
65+
assert.strictEqual(require(${JSON.stringify(path.resolve("packages/normalization-core/src/boolean-coercion.ts"))}).parseBoolean, parseBoolean);
66+
console.log(JSON.stringify({ value: first.value, evaluations: globalThis.pluginEvaluations,
67+
transformed: Transformed.Value, sourceAlias: parseBoolean(" TRUE ") }));
68+
} catch (error) {
69+
console.error(error.code + ": " + error.message);
70+
process.exitCode = 1;
71+
}
72+
`;
73+
}
74+
2975
export async function withShimFixture<T>(
3076
wrapper: (typeof TSX_SHIM_WRAPPERS)[number],
3177
run: (paths: {

‎test/scripts/direct-run-entrypoints.test.ts‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
formatShimResult,
2525
TSX_SHIM_WRAPPERS,
2626
withShimFixture,
27+
writeEsmPluginFixture,
2728
} from "./direct-run-entrypoints.test-support.js";
2829

2930
const DIRECT_RUN_SCRIPTS = [
@@ -111,7 +112,7 @@ function writeTsxFixture(modulesDir: string, marker: string) {
111112
mkdirSync(packageDir, { recursive: true });
112113
writeFileSync(
113114
path.join(packageDir, "package.json"),
114-
JSON.stringify({ name: "tsx", type: "module", exports: "./loader.mjs" }),
115+
JSON.stringify({ name: "tsx", type: "module", exports: { "./esm": "./loader.mjs" } }),
115116
);
116117
writeFileSync(
117118
path.join(packageDir, "loader.mjs"),
@@ -165,6 +166,36 @@ function expectShimLoader(result: Awaited<ReturnType<typeof runShimFixture>>, lo
165166
}
166167

167168
describe("script direct-run entrypoints", () => {
169+
it.each(["wrapper", "preload"])(
170+
"loads compiled ESM through require from the %s with import-only dependencies",
171+
async (entrypoint) => {
172+
await withShimFixture(TSX_SHIM_WRAPPERS[0], async (fixture) => {
173+
const { fixtureRoot, implementationPath, wrapperPath, runNode } = fixture;
174+
writeFileSync(implementationPath, writeEsmPluginFixture(fixtureRoot));
175+
const env: NodeJS.ProcessEnv = {
176+
...process.env,
177+
PNPM_CONFIG_MODULES_DIR: path.dirname(
178+
path.dirname(createRequire(import.meta.url).resolve("tsx/package.json")),
179+
),
180+
};
181+
delete env.NODE_OPTIONS;
182+
const args =
183+
entrypoint === "wrapper"
184+
? [wrapperPath]
185+
: ["--import", "./scripts/tsx.mjs", implementationPath];
186+
const result = await runNode(args, env, process.cwd());
187+
expect(result.error, formatShimResult(result)).toBeUndefined();
188+
expect(result.status, formatShimResult(result)).toBe(0);
189+
expect(JSON.parse(result.stdout)).toEqual({
190+
value: "import-only",
191+
evaluations: 1,
192+
transformed: "transformed",
193+
sourceAlias: true,
194+
});
195+
});
196+
},
197+
);
198+
168199
it.each([false, true])(
169200
"preserves preloads when forking into another cwd (equals=%s)",
170201
async (equals) => {

‎test/scripts/release-preflight.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ describe("scripts/release-preflight.mjs", () => {
192192
const result = runIsolatedPreflight(["--macos-versions-only", "--check"]);
193193

194194
expect(result.status).toBe(1);
195-
expect(result.stderr).toContain("Cannot find module 'tsx'");
195+
expect(result.stderr).toContain("Cannot find module 'tsx/esm'");
196196
expect(result.stderr).toContain("[release-preflight] FAILED (exit 1)");
197197
});
198198

0 commit comments

Comments
 (0)