-
-
Notifications
You must be signed in to change notification settings - Fork 80.7k
Expand file tree
/
Copy pathplugin-module-loader-cache.ts
More file actions
298 lines (284 loc) · 10.5 KB
/
Copy pathplugin-module-loader-cache.ts
File metadata and controls
298 lines (284 loc) · 10.5 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
292
293
294
295
296
297
298
import { createRequire } from "node:module";
import path from "node:path";
import { pathToFileURL } from "node:url";
import type { createJiti } from "jiti";
import { toSafeImportPath } from "../shared/import-specifier.js";
import { tryNativeRequireJavaScriptModule } from "./native-module-require.js";
import { PluginLruCache } from "./plugin-cache-primitives.js";
import {
buildPluginLoaderJitiOptions,
createPluginLoaderModuleCacheKey,
resolvePluginLoaderModuleConfig,
type PluginSdkResolutionPreference,
} from "./sdk-alias.js";
export type PluginModuleLoader = ReturnType<typeof createJiti>;
export type PluginModuleLoaderFactory = typeof createJiti;
export type PluginModuleLoaderCache = Pick<
PluginLruCache<PluginModuleLoader>,
"clear" | "get" | "set" | "size"
>;
export type ResolvePluginModuleLoaderCacheEntryParams = {
modulePath: string;
importerUrl: string;
argvEntry?: string;
preferBuiltDist?: boolean;
loaderFilename?: string;
aliasMap?: Record<string, string>;
tryNative?: boolean;
pluginSdkResolution?: PluginSdkResolutionPreference;
cacheScopeKey?: string;
sharedCacheScopeKey?: string;
};
export type PluginModuleLoaderCacheEntry = {
loaderFilename: string;
aliasMap: Record<string, string>;
tryNative: boolean;
cacheKey: string;
scopedCacheKey: string;
};
export type PluginModuleLoaderStatsSnapshot = {
calls: number;
nativeHits: number;
nativeMisses: number;
sourceTransformForced: number;
sourceTransformFallbacks: number;
topSourceTransformTargets: Array<{ target: string; count: number }>;
};
const DEFAULT_PLUGIN_MODULE_LOADER_CACHE_ENTRIES = 128;
const MAX_TRACKED_SOURCE_TRANSFORM_TARGETS = 24;
const requireForJiti = createRequire(import.meta.url);
let createJitiLoaderFactory: PluginModuleLoaderFactory | undefined;
const pluginModuleLoaderStats = {
calls: 0,
nativeHits: 0,
nativeMisses: 0,
sourceTransformForced: 0,
sourceTransformFallbacks: 0,
sourceTransformTargets: new Map<string, number>(),
};
function recordSourceTransformTarget(target: string): void {
const current = pluginModuleLoaderStats.sourceTransformTargets.get(target) ?? 0;
pluginModuleLoaderStats.sourceTransformTargets.set(target, current + 1);
if (pluginModuleLoaderStats.sourceTransformTargets.size <= MAX_TRACKED_SOURCE_TRANSFORM_TARGETS) {
return;
}
let leastUsedTarget: string | undefined;
let leastUsedCount = Number.POSITIVE_INFINITY;
for (const [candidate, count] of pluginModuleLoaderStats.sourceTransformTargets) {
if (count < leastUsedCount) {
leastUsedTarget = candidate;
leastUsedCount = count;
}
}
if (leastUsedTarget) {
pluginModuleLoaderStats.sourceTransformTargets.delete(leastUsedTarget);
}
}
export function getPluginModuleLoaderStats(): PluginModuleLoaderStatsSnapshot {
return {
calls: pluginModuleLoaderStats.calls,
nativeHits: pluginModuleLoaderStats.nativeHits,
nativeMisses: pluginModuleLoaderStats.nativeMisses,
sourceTransformForced: pluginModuleLoaderStats.sourceTransformForced,
sourceTransformFallbacks: pluginModuleLoaderStats.sourceTransformFallbacks,
topSourceTransformTargets: [...pluginModuleLoaderStats.sourceTransformTargets]
.toSorted((left, right) => right[1] - left[1] || left[0].localeCompare(right[0]))
.slice(0, 8)
.map(([target, count]) => ({ target, count })),
};
}
export function resetPluginModuleLoaderStatsForTest(): void {
pluginModuleLoaderStats.calls = 0;
pluginModuleLoaderStats.nativeHits = 0;
pluginModuleLoaderStats.nativeMisses = 0;
pluginModuleLoaderStats.sourceTransformForced = 0;
pluginModuleLoaderStats.sourceTransformFallbacks = 0;
pluginModuleLoaderStats.sourceTransformTargets.clear();
}
function loadCreateJitiLoaderFactory(): PluginModuleLoaderFactory {
if (createJitiLoaderFactory) {
return createJitiLoaderFactory;
}
const loaded = requireForJiti("jiti") as { createJiti?: PluginModuleLoaderFactory };
if (typeof loaded.createJiti !== "function") {
throw new Error("jiti module did not export createJiti");
}
createJitiLoaderFactory = loaded.createJiti;
return createJitiLoaderFactory;
}
export function createPluginModuleLoaderCache(
maxEntries = DEFAULT_PLUGIN_MODULE_LOADER_CACHE_ENTRIES,
): PluginModuleLoaderCache {
return new PluginLruCache<PluginModuleLoader>(maxEntries);
}
function toSourceTransformImportPath(specifier: string): string {
if (process.platform === "win32" && path.isAbsolute(specifier)) {
return pathToFileURL(specifier).href;
}
return toSafeImportPath(specifier);
}
function resolveDefaultPluginModuleLoaderConfig(
params: ResolvePluginModuleLoaderCacheEntryParams,
): ReturnType<typeof resolvePluginLoaderModuleConfig> {
return resolvePluginLoaderModuleConfig({
modulePath: params.modulePath,
argv1: params.argvEntry ?? process.argv[1],
moduleUrl: params.importerUrl,
...(params.preferBuiltDist ? { preferBuiltDist: true } : {}),
...(params.pluginSdkResolution ? { pluginSdkResolution: params.pluginSdkResolution } : {}),
});
}
export function resolvePluginModuleLoaderCacheEntry(
params: ResolvePluginModuleLoaderCacheEntryParams,
): PluginModuleLoaderCacheEntry {
const loaderFilename = toSafeImportPath(params.loaderFilename ?? params.modulePath);
const hasAliasOverride = Boolean(params.aliasMap);
const hasTryNativeOverride = typeof params.tryNative === "boolean";
const defaultConfig =
hasAliasOverride || hasTryNativeOverride
? resolveDefaultPluginModuleLoaderConfig(params)
: null;
const canReuseDefaultCacheKey =
defaultConfig !== null &&
(!hasAliasOverride || params.aliasMap === defaultConfig.aliasMap) &&
(!hasTryNativeOverride || params.tryNative === defaultConfig.tryNative);
const resolved = defaultConfig
? {
tryNative: params.tryNative ?? defaultConfig.tryNative,
aliasMap: params.aliasMap ?? defaultConfig.aliasMap,
cacheKey: canReuseDefaultCacheKey ? defaultConfig.cacheKey : undefined,
}
: resolveDefaultPluginModuleLoaderConfig(params);
const { tryNative, aliasMap } = resolved;
const cacheKey =
resolved.cacheKey ??
createPluginLoaderModuleCacheKey({
tryNative,
aliasMap,
});
const scopedCacheKey = `${loaderFilename}::${
params.sharedCacheScopeKey ??
(params.cacheScopeKey ? `${params.cacheScopeKey}::${cacheKey}` : cacheKey)
}`;
return {
loaderFilename,
aliasMap,
tryNative,
cacheKey,
scopedCacheKey,
};
}
function createLazySourceTransformLoader(params: {
loaderFilename: string;
aliasMap: Record<string, string>;
sourceTransformTryNative: boolean;
createLoader?: PluginModuleLoaderFactory;
}): () => PluginModuleLoader {
let loadWithSourceTransform: PluginModuleLoader | undefined;
return () => {
if (loadWithSourceTransform) {
return loadWithSourceTransform;
}
const jitiLoader = (params.createLoader ?? loadCreateJitiLoaderFactory())(
params.loaderFilename,
{
...buildPluginLoaderJitiOptions(params.aliasMap),
tryNative: params.sourceTransformTryNative,
},
);
loadWithSourceTransform = new Proxy(jitiLoader, {
apply(target, thisArg, argArray) {
const [first, ...rest] = argArray as [unknown, ...unknown[]];
if (typeof first === "string") {
return Reflect.apply(target, thisArg, [
toSourceTransformImportPath(first),
...rest,
] as never) as never;
}
return Reflect.apply(target, thisArg, argArray as never) as never;
},
});
return loadWithSourceTransform;
};
}
function createPluginModuleLoader(params: {
loaderFilename: string;
aliasMap: Record<string, string>;
tryNative: boolean;
createLoader?: PluginModuleLoaderFactory;
}): PluginModuleLoader {
const getLoadWithSourceTransform = createLazySourceTransformLoader({
...params,
sourceTransformTryNative: params.tryNative,
});
// When the caller has explicitly opted out of native loading (for example
// `bundled-capability-runtime` in Vitest+dist mode, which depends on
// jiti's alias rewriting to surface a narrow SDK slice), route every
// target through jiti so those alias rewrites still apply.
if (!params.tryNative) {
return ((target: string, ...rest: unknown[]) => {
pluginModuleLoaderStats.calls += 1;
pluginModuleLoaderStats.sourceTransformForced += 1;
recordSourceTransformTarget(target);
return (getLoadWithSourceTransform() as (t: string, ...a: unknown[]) => unknown)(
target,
...rest,
);
}) as PluginModuleLoader;
}
// Otherwise prefer native require() for already-compiled JS artifacts
// (the bundled plugin public surfaces shipped in dist/). jiti's transform
// pipeline provides no value for output that is already plain JS and adds
// several seconds of per-load overhead on slower hosts. jiti still runs
// for TS / TSX sources and for the small set of require(esm) /
// async-module fallbacks `tryNativeRequireJavaScriptModule` declines to
// handle.
return ((target: string, ...rest: unknown[]) => {
pluginModuleLoaderStats.calls += 1;
const native = tryNativeRequireJavaScriptModule(target, {
allowWindows: true,
aliasMap: params.aliasMap,
fallbackOnMissingDependency: true,
fallbackOnNativeError: true,
});
if (native.ok) {
pluginModuleLoaderStats.nativeHits += 1;
return native.moduleExport;
}
pluginModuleLoaderStats.nativeMisses += 1;
pluginModuleLoaderStats.sourceTransformFallbacks += 1;
recordSourceTransformTarget(target);
return (getLoadWithSourceTransform() as (t: string, ...a: unknown[]) => unknown)(
target,
...rest,
);
}) as PluginModuleLoader;
}
export function getCachedPluginModuleLoader(
params: ResolvePluginModuleLoaderCacheEntryParams & {
cache: PluginModuleLoaderCache;
createLoader?: PluginModuleLoaderFactory;
},
): PluginModuleLoader {
const cacheEntry = resolvePluginModuleLoaderCacheEntry(params);
const cached = params.cache.get(cacheEntry.scopedCacheKey);
if (cached) {
return cached;
}
const loader = createPluginModuleLoader({
loaderFilename: cacheEntry.loaderFilename,
aliasMap: cacheEntry.aliasMap,
tryNative: cacheEntry.tryNative,
...(params.createLoader ? { createLoader: params.createLoader } : {}),
});
params.cache.set(cacheEntry.scopedCacheKey, loader);
return loader;
}
export function getCachedPluginSourceModuleLoader(
params: Omit<Parameters<typeof getCachedPluginModuleLoader>[0], "tryNative">,
): PluginModuleLoader {
return getCachedPluginModuleLoader({
...params,
tryNative: false,
});
}