-
-
Notifications
You must be signed in to change notification settings - Fork 80.7k
Expand file tree
/
Copy pathfacade-loader.ts
More file actions
291 lines (267 loc) · 9.78 KB
/
Copy pathfacade-loader.ts
File metadata and controls
291 lines (267 loc) · 9.78 KB
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
// Facade loader helpers resolve plugin public API modules from source, dist, or installed roots.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { openRootFileSync } from "../infra/boundary-file-read.js";
import { resolveBundledPluginsDir } from "../plugins/bundled-dir.js";
import { shouldRejectHardlinkedPluginFiles } from "../plugins/hardlink-policy.js";
import {
getCachedPluginModuleLoader,
type PluginModuleLoaderCache,
type PluginModuleLoaderFactory,
} from "../plugins/plugin-module-loader-cache.js";
import { resolveLoaderPackageRoot } from "../plugins/sdk-alias.js";
import { resolveBundledFacadeModuleLocation } from "./facade-resolution-shared.js";
const CURRENT_MODULE_PATH = fileURLToPath(import.meta.url);
const moduleLoaders: PluginModuleLoaderCache = new Map();
const loadedFacadeModules = new Map<string, unknown>();
const loadedFacadePluginIds = new Set<string>();
let facadeLoaderSourceTransformFactory: PluginModuleLoaderFactory | undefined;
let cachedOpenClawPackageRoot: string | undefined;
function getOpenClawPackageRoot() {
if (cachedOpenClawPackageRoot) {
return cachedOpenClawPackageRoot;
}
cachedOpenClawPackageRoot =
resolveLoaderPackageRoot({
modulePath: fileURLToPath(import.meta.url),
moduleUrl: import.meta.url,
}) ?? fileURLToPath(new URL("../..", import.meta.url));
return cachedOpenClawPackageRoot;
}
function resolveFacadeModuleLocation(params: {
dirName: string;
artifactBasename: string;
env?: NodeJS.ProcessEnv;
}): { modulePath: string; boundaryRoot: string } | null {
const bundledPluginsDir = resolveBundledPluginsDir(params.env ?? process.env);
return resolveBundledFacadeModuleLocation({
...params,
currentModulePath: CURRENT_MODULE_PATH,
packageRoot: getOpenClawPackageRoot(),
bundledPluginsDir,
});
}
function getModuleLoader(modulePath: string) {
return getCachedPluginModuleLoader({
cache: moduleLoaders,
modulePath,
importerUrl: import.meta.url,
preferBuiltDist: true,
loaderFilename: import.meta.url,
...(facadeLoaderSourceTransformFactory
? { createLoader: facadeLoaderSourceTransformFactory }
: {}),
});
}
function createLazyFacadeValueLoader<T>(load: () => T): () => T {
let loaded = false;
let value: T;
return () => {
if (!loaded) {
value = load();
loaded = true;
}
return value;
};
}
function createLazyFacadeProxyValue<T extends object>(params: {
load: () => T;
target: object;
}): T {
const resolve = createLazyFacadeValueLoader(params.load);
return new Proxy(params.target, {
defineProperty(_target, property, descriptor) {
return Reflect.defineProperty(resolve(), property, descriptor);
},
deleteProperty(_target, property) {
return Reflect.deleteProperty(resolve(), property);
},
get(_target, property, receiver) {
return Reflect.get(resolve(), property, receiver);
},
getOwnPropertyDescriptor(_target, property) {
return Reflect.getOwnPropertyDescriptor(resolve(), property);
},
getPrototypeOf() {
return Reflect.getPrototypeOf(resolve());
},
has(_target, property) {
return Reflect.has(resolve(), property);
},
isExtensible() {
return Reflect.isExtensible(resolve());
},
ownKeys() {
return Reflect.ownKeys(resolve());
},
preventExtensions() {
return Reflect.preventExtensions(resolve());
},
set(_target, property, value, receiver) {
return Reflect.set(resolve(), property, value, receiver);
},
setPrototypeOf(_target, prototype) {
return Reflect.setPrototypeOf(resolve(), prototype);
},
}) as T;
}
/** Create an object proxy that loads the underlying facade only on first property access. */
export function createLazyFacadeObjectValue<T extends object>(load: () => T): T {
return createLazyFacadeProxyValue({ load, target: {} });
}
/** Create an array proxy that loads the underlying facade only on first array access. */
export function createLazyFacadeArrayValue<T extends readonly unknown[]>(load: () => T): T {
return createLazyFacadeProxyValue({ load, target: [] });
}
/** Resolved public-surface module path plus the filesystem root it must stay within. */
export type FacadeModuleLocation = {
modulePath: string;
boundaryRoot: string;
};
function isPathAtOrInside(target: string, root: string): boolean {
const resolvedRoot = path.resolve(root);
const resolvedTarget = path.resolve(target);
return resolvedTarget === resolvedRoot || resolvedTarget.startsWith(resolvedRoot + path.sep);
}
// Registry-resolved locations can point at installed plugin roots, which must
// reject hardlinked artifacts (see hardlink-policy.ts); core-shipped roots keep
// hardlinks allowed for bundled dist/Nix layouts.
function resolveFacadeBoundaryOpenParams(boundaryRoot: string): {
boundaryLabel: string;
rejectHardlinks: boolean;
} {
if (isPathAtOrInside(boundaryRoot, getOpenClawPackageRoot())) {
return { boundaryLabel: "OpenClaw package root", rejectHardlinks: false };
}
const bundledDir = resolveBundledPluginsDir();
if (bundledDir && isPathAtOrInside(boundaryRoot, bundledDir)) {
return { boundaryLabel: "bundled plugin directory", rejectHardlinks: false };
}
return {
boundaryLabel: "plugin root",
rejectHardlinks: shouldRejectHardlinkedPluginFiles({ origin: "global", rootDir: boundaryRoot }),
};
}
/** Load and cache a facade module after verifying it is inside its declared boundary root. */
export function loadFacadeModuleAtLocationSync<T extends object>(params: {
location: FacadeModuleLocation;
trackedPluginId: string | (() => string);
loadModule?: (modulePath: string) => T;
}): T {
const location = params.location;
const cached = loadedFacadeModules.get(location.modulePath);
if (cached) {
return cached as T;
}
const opened = openRootFileSync({
absolutePath: location.modulePath,
rootPath: location.boundaryRoot,
...resolveFacadeBoundaryOpenParams(location.boundaryRoot),
});
if (!opened.ok) {
throw new Error(`Unable to open bundled plugin public surface ${location.modulePath}`, {
cause: opened.error,
});
}
fs.closeSync(opened.fd);
const sentinel = {} as T;
loadedFacadeModules.set(location.modulePath, sentinel);
let loaded: T;
try {
loaded =
params.loadModule?.(location.modulePath) ??
(getModuleLoader(location.modulePath)(location.modulePath) as T);
Object.assign(sentinel, loaded);
loadedFacadePluginIds.add(
typeof params.trackedPluginId === "function"
? params.trackedPluginId()
: params.trackedPluginId,
);
} catch (err) {
loadedFacadeModules.delete(location.modulePath);
throw err;
}
return sentinel;
}
/** Resolve and synchronously load a bundled plugin public surface by plugin dir and artifact name. */
// oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- Dynamic facade loaders use caller-supplied module surface types.
export function loadBundledPluginPublicSurfaceModuleSync<T extends object>(params: {
dirName: string;
artifactBasename: string;
trackedPluginId?: string | (() => string);
env?: NodeJS.ProcessEnv;
}): T {
const location = resolveFacadeModuleLocation(params);
if (!location) {
throw new Error(
`Unable to resolve bundled plugin public surface ${params.dirName}/${params.artifactBasename}`,
);
}
return loadFacadeModuleAtLocationSync({
location,
trackedPluginId: params.trackedPluginId ?? params.dirName,
});
}
/** Resolve and asynchronously import a bundled plugin public surface with sync-loader fallback. */
export async function loadBundledPluginPublicSurfaceModule<T extends object>(params: {
dirName: string;
artifactBasename: string;
trackedPluginId?: string | (() => string);
}): Promise<T> {
const location = resolveFacadeModuleLocation(params);
if (!location) {
throw new Error(
`Unable to resolve bundled plugin public surface ${params.dirName}/${params.artifactBasename}`,
);
}
const preparedLocation = location;
const cached = loadedFacadeModules.get(preparedLocation.modulePath);
if (cached) {
return cached as T;
}
const opened = openRootFileSync({
absolutePath: preparedLocation.modulePath,
rootPath: preparedLocation.boundaryRoot,
...resolveFacadeBoundaryOpenParams(preparedLocation.boundaryRoot),
});
if (!opened.ok) {
throw new Error(`Unable to open bundled plugin public surface ${preparedLocation.modulePath}`, {
cause: opened.error,
});
}
fs.closeSync(opened.fd);
try {
const loaded = (await import(pathToFileURL(preparedLocation.modulePath).href)) as T;
loadedFacadeModules.set(preparedLocation.modulePath, loaded);
loadedFacadePluginIds.add(
typeof params.trackedPluginId === "function"
? params.trackedPluginId()
: (params.trackedPluginId ?? params.dirName),
);
return loaded;
} catch {
return loadFacadeModuleAtLocationSync({
location: preparedLocation,
trackedPluginId: params.trackedPluginId ?? params.dirName,
});
}
}
/** List plugin ids whose public facades have been loaded in this process. */
export function listImportedBundledPluginFacadeIds(): string[] {
return [...loadedFacadePluginIds].toSorted((left, right) => left.localeCompare(right));
}
/** Reset facade module caches and test loader overrides. */
export function resetFacadeLoaderStateForTest(): void {
loadedFacadeModules.clear();
loadedFacadePluginIds.clear();
moduleLoaders.clear();
facadeLoaderSourceTransformFactory = undefined;
cachedOpenClawPackageRoot = undefined;
}
/** Override source transform loader creation for facade-loader tests. */
export function setFacadeLoaderSourceTransformFactoryForTest(
factory: PluginModuleLoaderFactory | undefined,
): void {
facadeLoaderSourceTransformFactory = factory;
}