Skip to content

Commit 74af716

Browse files
authored
perf(startup): short-circuit dist-internal ESM resolution with explicit module format (#128541)
Node's ESM resolver runs getPackageScopeConfig() for every file: URL to pick a module format, and each call re-materializes package.json — re-parsing openclaw's 318-key exports map (~93µs/call, verified on Node 26.5.0). Across the ~17k module edges of a gateway boot that costs 1.3-2.6s CPU, showing up in profiles as package_json_reader.get (self time) or attributed inclusively under any registered resolve hook. Install a Module.registerHooks resolve fast path from the main-module entry points that resolves relative "./*.js" imports inside dist/ by URL join with format "module", skipping scope detection entirely. Behavior-identical: all 145 dist package.json files declare type module and dist contains no CJS-syntax .js files, so Node would conclude the same format. require() resolutions, bare specifiers, non-.js targets, out-of-dist parents, and dist-escaping ../ chains defer to default resolution; source checkouts and runtimes without registerHooks (Bun) are untouched. Measured (interleaved same-dist A/B, isolated OPENCLAW_STATE_DIR, macOS, Node 26.5.0): gateway boot user CPU 5.2s -> 2.9s, self-reported listening time 3.3-6.6s -> stable 2.1s.
1 parent 1f3c8b4 commit 74af716

4 files changed

Lines changed: 233 additions & 0 deletions

File tree

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
import { describe, expect, it } from "vitest";
2+
import { installDistEsmResolveFastPath } from "./entry.esm-resolve-fast-path.js";
3+
4+
type ResolveHook = (
5+
specifier: string,
6+
context: { parentURL?: string; conditions?: readonly string[] },
7+
nextResolve: (specifier: string) => { url: string },
8+
) => { url: string; format?: string | null; shortCircuit?: boolean };
9+
10+
const DIST_ROOT = "file:///opt/openclaw/dist/";
11+
12+
function installCapturedHook(entryFileUrl: string): ResolveHook {
13+
let hook: ResolveHook | undefined;
14+
const installed = installDistEsmResolveFastPath(entryFileUrl, {
15+
registerHooks: (options) => {
16+
hook = options.resolve as ResolveHook;
17+
return { deregister: () => {} };
18+
},
19+
});
20+
expect(installed).toBe(true);
21+
if (!hook) {
22+
throw new Error("resolve hook was not registered");
23+
}
24+
return hook;
25+
}
26+
27+
function runHook(
28+
hook: ResolveHook,
29+
specifier: string,
30+
context: { parentURL?: string; conditions?: readonly string[] } = {},
31+
) {
32+
const resolvedContext = {
33+
parentURL: "parentURL" in context ? context.parentURL : `${DIST_ROOT}entry.js`,
34+
conditions: context.conditions ?? ["node", "import"],
35+
};
36+
let deferred = false;
37+
const result = hook(specifier, resolvedContext, () => {
38+
deferred = true;
39+
return { url: "next:resolved" };
40+
});
41+
return { deferred, result };
42+
}
43+
44+
describe("installDistEsmResolveFastPath resolve hook", () => {
45+
const hook = installCapturedHook(`${DIST_ROOT}entry.js`);
46+
47+
it("short-circuits dist-internal relative .js imports with module format", () => {
48+
const direct = runHook(hook, "./chunk-abc.js");
49+
expect(direct.deferred).toBe(false);
50+
expect(direct.result).toStrictEqual({
51+
url: `${DIST_ROOT}chunk-abc.js`,
52+
format: "module",
53+
shortCircuit: true,
54+
});
55+
const fromExtension = runHook(hook, "../../plugin-entry.js", {
56+
parentURL: `${DIST_ROOT}extensions/telegram/index.js`,
57+
});
58+
expect(fromExtension.result.url).toBe(`${DIST_ROOT}plugin-entry.js`);
59+
});
60+
61+
it("defers require() resolutions to the default CJS path", () => {
62+
expect(runHook(hook, "./chunk.js", { conditions: ["node", "require"] }).deferred).toBe(true);
63+
});
64+
65+
it("defers bare, absolute, and non-.js specifiers", () => {
66+
for (const specifier of [
67+
"openclaw/plugin-sdk/plugin-entry",
68+
"node:path",
69+
"/opt/openclaw/dist/chunk.js",
70+
"./chunk.mjs",
71+
"./chunk.cjs",
72+
"./manifest.json",
73+
"./chunk.js?query",
74+
".js",
75+
]) {
76+
expect(runHook(hook, specifier).deferred, specifier).toBe(true);
77+
}
78+
});
79+
80+
it("defers parents outside the dist root and missing parents", () => {
81+
expect(runHook(hook, "./chunk.js", { parentURL: "file:///opt/other/entry.js" }).deferred).toBe(
82+
true,
83+
);
84+
expect(runHook(hook, "./chunk.js", { parentURL: undefined }).deferred).toBe(true);
85+
});
86+
87+
it("defers relative targets that escape the dist root", () => {
88+
expect(runHook(hook, "../outside/chunk.js").deferred).toBe(true);
89+
});
90+
});
91+
92+
describe("installDistEsmResolveFastPath gating", () => {
93+
it("registers one hook per dist root and stays idempotent", () => {
94+
let registered = 0;
95+
const registerHooks = () => {
96+
registered += 1;
97+
return { deregister: () => {} };
98+
};
99+
const root = "file:///opt/openclaw-idempotent/dist/";
100+
expect(installDistEsmResolveFastPath(`${root}entry.js`, { registerHooks })).toBe(true);
101+
expect(installDistEsmResolveFastPath(`${root}index.js`, { registerHooks })).toBe(true);
102+
expect(registered).toBe(1);
103+
});
104+
105+
it("declines outside dist layouts and without registerHooks support", () => {
106+
let registered = 0;
107+
const registerHooks = () => {
108+
registered += 1;
109+
return { deregister: () => {} };
110+
};
111+
expect(
112+
installDistEsmResolveFastPath("file:///opt/openclaw/src/entry.ts", { registerHooks }),
113+
).toBe(false);
114+
expect(registered).toBe(0);
115+
expect(
116+
installDistEsmResolveFastPath("file:///opt/openclaw-two/dist/entry.js", {
117+
registerHooks: undefined,
118+
}),
119+
).toBe(false);
120+
});
121+
});

‎src/entry.esm-resolve-fast-path.ts‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
/**
2+
* Short-circuits Node's ESM resolution for dist-internal relative imports.
3+
*
4+
* Node's default resolver calls getPackageScopeConfig() for every file: URL to
5+
* pick a module format, and each call re-materializes the package.json
6+
* `exports` map. With openclaw's 300+ subpath exports that costs ~0.1ms per
7+
* resolution and multiple seconds across the ~15k module edges of a gateway
8+
* boot. Every built dist file is ESM (all dist package.json files declare
9+
* "type": "module"), so a relative "./chunk.js" import inside dist can resolve
10+
* by URL join with format "module" without consulting the package scope at
11+
* all. This hook removes only resolver cost; the resolved URL and format are
12+
* byte-identical to Node's default resolution.
13+
*/
14+
import Module from "node:module";
15+
16+
type SyncResolveResult = { url: string; format?: string | null; shortCircuit?: boolean };
17+
type SyncResolveContext = { parentURL?: string; conditions?: readonly string[] };
18+
type SyncResolveHook = (
19+
specifier: string,
20+
context: SyncResolveContext,
21+
nextResolve: (specifier: string, context?: SyncResolveContext) => SyncResolveResult,
22+
) => SyncResolveResult;
23+
type RegisterModuleHooks = (options: { resolve?: SyncResolveHook }) => { deregister: () => void };
24+
25+
// SAFETY: Module.registerHooks ships in every supported Node runtime but is missing from the bundled type declarations; the optional member keeps callers probing before use (Bun lacks it).
26+
const moduleWithHooks = Module as typeof Module & {
27+
registerHooks?: RegisterModuleHooks;
28+
};
29+
30+
const installedDistRootUrls = new Set<string>();
31+
32+
/**
33+
* Resolves a dist-internal relative ESM specifier to its final file URL, or
34+
* returns null when the specifier must go through Node's default resolution.
35+
* Only relative ".js" specifiers whose parent and target both live under the
36+
* dist root qualify; require() resolutions stay on the default path because
37+
* the CJS loader does not pay the eager format-detection cost this bypasses.
38+
*/
39+
function resolveDistEsmFastPathUrl(params: {
40+
specifier: string;
41+
parentUrl: string | undefined;
42+
conditions: readonly string[] | undefined;
43+
distRootUrl: string;
44+
}): string | null {
45+
const { specifier, parentUrl } = params;
46+
if (
47+
specifier.charCodeAt(0) !== 46 /* "." */ ||
48+
!specifier.endsWith(".js") ||
49+
parentUrl === undefined ||
50+
!parentUrl.startsWith(params.distRootUrl) ||
51+
params.conditions?.includes("require") === true ||
52+
(specifier.charCodeAt(1) !== 47 /* "/" */ &&
53+
(specifier.charCodeAt(1) !== 46 /* "." */ || specifier.charCodeAt(2) !== 47))
54+
) {
55+
return null;
56+
}
57+
let resolved: string;
58+
try {
59+
resolved = new URL(specifier, parentUrl).href;
60+
} catch {
61+
return null;
62+
}
63+
// "../" chains can leave the built output tree; those targets may live in a
64+
// different package scope, so they keep Node's default format detection.
65+
return resolved.startsWith(params.distRootUrl) ? resolved : null;
66+
}
67+
68+
/**
69+
* Installs the dist-relative ESM resolve fast path for a built entry file.
70+
* No-ops (returns false) outside a dist layout — source checkouts run through
71+
* tsx/vitest resolvers that must keep owning ".js" specifier rewrites — and
72+
* on runtimes without Module.registerHooks.
73+
*/
74+
export function installDistEsmResolveFastPath(
75+
entryFileUrl: string,
76+
deps: { registerHooks?: RegisterModuleHooks | undefined } = {},
77+
): boolean {
78+
const registerHooks =
79+
"registerHooks" in deps ? deps.registerHooks : moduleWithHooks.registerHooks;
80+
if (typeof registerHooks !== "function") {
81+
return false;
82+
}
83+
const distRootUrl = new URL("./", entryFileUrl).href;
84+
if (!distRootUrl.endsWith("/dist/")) {
85+
return false;
86+
}
87+
if (installedDistRootUrls.has(distRootUrl)) {
88+
return true;
89+
}
90+
registerHooks({
91+
resolve(specifier, context, nextResolve) {
92+
const url = resolveDistEsmFastPathUrl({
93+
specifier,
94+
parentUrl: context.parentURL,
95+
conditions: context.conditions,
96+
distRootUrl,
97+
});
98+
if (url !== null) {
99+
return { url, format: "module", shortCircuit: true };
100+
}
101+
return nextResolve(specifier, context);
102+
},
103+
});
104+
installedDistRootUrls.add(distRootUrl);
105+
return true;
106+
}

‎src/entry.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
resolveEntryInstallRoot,
2525
respawnWithoutOpenClawCompileCacheIfNeeded,
2626
} from "./entry.compile-cache.js";
27+
import { installDistEsmResolveFastPath } from "./entry.esm-resolve-fast-path.js";
2728
import { buildCliRespawnPlan, runCliRespawnPlan } from "./entry.respawn.js";
2829
import { tryHandleRootVersionFastPath } from "./entry.version-fast-path.js";
2930
import { normalizeEnv } from "./infra/env.js";
@@ -119,6 +120,7 @@ if (
119120
} else {
120121
const entryFile = fileURLToPath(import.meta.url);
121122
const installRoot = resolveEntryInstallRoot(entryFile);
123+
installDistEsmResolveFastPath(import.meta.url);
122124
process.title = "openclaw";
123125
ensureOpenClawExecMarkerOnProcess();
124126
installProcessWarningFilter();

‎src/index.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
} from "./cli/failure-output.js";
1111
import { isJsonOutputModeActive } from "./cli/json-output-mode.js";
1212
import { runCliWithExitFinalization } from "./cli/one-shot-exit.js";
13+
import { installDistEsmResolveFastPath } from "./entry.esm-resolve-fast-path.js";
1314
import { tryHandleRootVersionFastPath } from "./entry.version-fast-path.js";
1415
import { formatUncaughtError } from "./infra/errors.js";
1516
import { runFatalErrorHooks } from "./infra/fatal-error-hooks.js";
@@ -76,6 +77,9 @@ export async function runLegacyCliEntry(
7677
const isMain = isMainModule({
7778
currentFile: fileURLToPath(import.meta.url),
7879
});
80+
if (isMain) {
81+
installDistEsmResolveFastPath(import.meta.url);
82+
}
7983
const handledRootVersion = isMain && tryHandleRootVersionFastPath(process.argv);
8084

8185
if (!isMain) {

0 commit comments

Comments
 (0)