| 6 | * |
| 7 | * The factories share URL normalization and format inference while their |
| 8 | * overloads keep synchronous and asynchronous callers correctly typed. |
| 9 | */ |
| 10 |
| 11 | import type { |
| 12 | ResolveHookContext, |
| 13 | ResolveFnOutput, |
| 14 | LoadHookContext, |
| 15 | LoadFnOutput, |
| 16 | ResolveHookSync, |
| 17 | LoadHookSync, |
| 18 | } from "node:module"; |
| 19 | import { createRequire, isBuiltin } from "node:module"; |
| 20 | import { resolve as resolvePath } from "node:path"; |
| 21 | import { pathToFileURL } from "node:url"; |
| 22 | import process from "node:process"; |
| 23 | import { DEFAULT_CDN, isHttpUrl } from "./constants.ts"; |
| 24 | import { isEsmShCdn, jsrToCdnUrl } from "./jsr.ts"; |
| 25 | import { tmpEnabled, urlToTmpPath, writeTmpFile, tmpPathToUrl } from "./tmp.ts"; |
| 26 | import { verifyModuleLock } from "./lock.ts"; |
| 27 | import type { CacheEntry } from "./cache.ts"; |
| 28 |
| 29 | /** |
| 30 | * Strip `npm:` and the optional version for local Node package resolution. |
| 31 | * npm:ms@2.1.3 → ms |
| 32 | * npm:@scope/pkg@1.0.0 → @scope/pkg |
| 33 | * npm:@scope/pkg@1.0.0/sub → @scope/pkg/sub |
| 34 | * npm:lodash-es → lodash-es |
| 35 | * The original version is kept when an uninstalled package falls back to a CDN. |
| 36 | */ |
| 37 | export function stripNpmSpecifier(specifier: string): string { |
| 38 | return specifier.slice(4).replace(/^(@[^/]+\/[^/@]+|[^/@]+)@[^/]+/, "$1"); |
| 39 | } |
| 40 |
| 41 | /** |
| 42 | * Recover the HTTP parent for normal URL imports, --tmp modules and CJS. |
| 43 | * Node's CJS loader mangles https://esm.sh/pkg into file:///cwd/https:/esm.sh/pkg; |
| 44 | * reconstructing it keeps transitive relative requires on the remote server. |
| 45 | */ |
| 46 | function getHttpParentUrl(parentURL: string | undefined): string | null { |
| 47 | if (!parentURL) return null; |
| 48 | if (isHttpUrl(parentURL)) return new URL(parentURL).href; |
| 49 | const temporaryUrl = tmpPathToUrl(parentURL); |
| 50 | if (temporaryUrl) return temporaryUrl; |
| 51 | // CJS normalizes https://host/path into file:///cwd/https:/host/path. |
| 52 | const match = parentURL.match(/\/(https?:)\/([^/].*)$/); |
| 53 | return match ? `${match[1]}//${match[2]}` : null; |
| 54 | } |
| 55 |
| 56 | /** Whether this Node version enables native TypeScript load formats by default. */ |
| 57 | const supportsTypeScriptFormat = (() => { |
| 58 | const [major = 0, minor = 0] = process.versions.node.split(".").map(Number); |
| 59 | return major > 22 || (major === 22 && minor >= 18); |
| 60 | })(); |
| 61 |
| 62 | /** |
| 63 | * Resolve the load format for TypeScript. Older Node versions cannot strip |
| 64 | * types, so fail explicitly rather than handing raw TypeScript to the JS parser. |
| 65 | * .cts must keep CommonJS semantics even when served with a TypeScript MIME type. |
| 66 | */ |
| 67 | function typeScriptFormat( |
| 68 | url: string, |
| 69 | commonjs: boolean, |
| 70 | supported: boolean, |
| 71 | ): string { |
| 72 | if (!supported) { |
| 73 | throw new Error( |
| 74 | `Cannot load remote TypeScript module ${url}: this Node version (${process.versions.node}) ` + |
| 75 | "does not support type stripping. Upgrade to Node 22.18+ or 24+.", |
| 76 | ); |
| 77 | } |
| 78 | return commonjs ? "commonjs-typescript" : "module-typescript"; |
| 79 | } |
| 80 |
| 81 | /** |
| 82 | * Infer the module format from Content-Type and the final URL's extension. |
| 83 | * tsSupported is injectable for tests and otherwise follows the running Node. |
| 84 | */ |
| 85 | export function inferFormat( |
| 86 | url: string, |
| 87 | contentType: string, |
| 88 | tsSupported = supportsTypeScriptFormat, |
| 89 | ): string { |
| 90 | const type = contentType.toLowerCase(); |
| 91 | const pathname = new URL(url).pathname; |
| 92 | if (type.includes("application/json")) return "json"; |
| 93 | if (type.includes("application/wasm")) return "wasm"; |
| 94 | if (pathname.endsWith(".cts")) |
| 95 | return typeScriptFormat(url, true, tsSupported); |
| 96 | if ( |
| 97 | type.includes("text/typescript") || |
| 98 | type.includes("application/typescript") |
| 99 | ) { |
| 100 | return typeScriptFormat(url, false, tsSupported); |
| 101 | } |
| 102 | if (pathname.endsWith(".json")) return "json"; |
| 103 | if (pathname.endsWith(".wasm")) return "wasm"; |
| 104 | if (pathname.endsWith(".cjs")) return "commonjs"; |
| 105 | if (/\.(?:ts|tsx|mts)$/.test(pathname)) |
| 106 | return typeScriptFormat(url, false, tsSupported); |
| 107 | return "module"; |
| 108 | } |
| 109 |
| 110 | type NextResolve = Parameters<ResolveHookSync>[2]; |
| 111 | type NextLoad = Parameters<LoadHookSync>[2]; |
| 112 | type ResolveHookAsync = ( |
| 113 | ...args: Parameters<ResolveHookSync> |
| 114 | ) => Promise<ResolveFnOutput>; |
| 115 | type LoadHookAsync = ( |
| 116 | ...args: Parameters<LoadHookSync> |
| 117 | ) => Promise<LoadFnOutput>; |
| 118 |
| 119 | /** Bare packages check node_modules first, then fall back to this CDN; npm: falls back too. */ |
| 120 | const cdnBase = process.env.URL_IMPORT_CDN; |
| 121 | /** A leading scheme excludes node:, data:, file:, npm: and other full URLs. */ |
| 122 | const SCHEME_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:/; |
| 123 | const projectParentUrl = (): string => |
| 124 | pathToFileURL(resolvePath(process.cwd(), "package.json")).href; |
| 125 | let resolvingLocalPackage = false; |
| 126 | // Hand the already-fetched source from resolve to load, including with --reload. |
| 127 | const pendingLoads = new Map<string, CacheEntry>(); |
| 128 |
| 129 | /** Relative and absolute-path imports resolve against the effective HTTP parent. */ |
| 130 | function isRelativeSpecifier(specifier: string): boolean { |
| 131 | return ( |
| 132 | specifier.startsWith("./") || |
| 133 | specifier.startsWith("../") || |
| 134 | specifier.startsWith("/") |
| 135 | ); |
| 136 | } |
| 137 |
| 138 | /** Package names such as ws or @scope/pkg/sub, excluding paths and URL schemes. */ |
| 139 | function isBareSpecifier(specifier: string): boolean { |
| 140 | return ( |
| 141 | !specifier.startsWith("#") && |
| 142 | !isRelativeSpecifier(specifier) && |
| 143 | !SCHEME_RE.test(specifier) |
| 144 | ); |
| 145 | } |
| 146 |
| 147 | function normalizeWindowsPath(url: string): string { |
| 148 | return process.platform === "win32" && /^[a-zA-Z]:[\\/]/.test(url) |
| 149 | ? pathToFileURL(url).href |
| 150 | : url; |
| 151 | } |
| 152 |
| 153 | /** Use require.resolve for npm: packages, anchored to a local caller or the project. */ |
| 154 | function resolveLocalPackage( |
| 155 | specifier: string, |
| 156 | context: ResolveHookContext, |
| 157 | nextResolve: NextResolve, |
| 158 | ): ResolveFnOutput { |
| 159 | const parentURL = |
| 160 | context.parentURL && !getHttpParentUrl(context.parentURL) |
| 161 | ? context.parentURL |
| 162 | : projectParentUrl(); |
| 163 | if (isBuiltin(specifier)) |
| 164 | return nextResolve(specifier, { ...context, parentURL }); |
| 165 | resolvingLocalPackage = true; |
| 166 | let resolved: string; |
| 167 | try { |
| 168 | resolved = createRequire(parentURL).resolve(specifier); |
| 169 | } finally { |
| 170 | resolvingLocalPackage = false; |
| 171 | } |
| 172 | if (isHttpUrl(resolved)) { |
| 173 | throw Object.assign( |
| 174 | new Error(`Cannot resolve local package "${specifier}"`), |
| 175 | { code: "MODULE_NOT_FOUND" }, |
| 176 | ); |
| 177 | } |
| 178 | return nextResolve(pathToFileURL(resolved).href, { ...context, parentURL }); |
| 179 | } |
| 180 |
| 181 | function validateImportAttributes( |
| 182 | url: string, |
| 183 | format: string, |
| 184 | context: ResolveHookContext | LoadHookContext, |
| 185 | ): void { |
| 186 | const attributes = context.importAttributes ?? {}; |
| 187 | for (const name of Object.keys(attributes)) { |
| 188 | if (name !== "type") { |
| 189 | throw Object.assign( |
| 190 | new TypeError(`Unsupported import attribute "${name}" for ${url}`), |
| 191 | { code: "ERR_IMPORT_ATTRIBUTE_UNSUPPORTED" }, |
| 192 | ); |
| 193 | } |
| 194 | } |
| 195 | if (attributes.type !== undefined && attributes.type !== "json") { |
| 196 | throw Object.assign( |
| 197 | new TypeError(`Unsupported import type "${attributes.type}" for ${url}`), |
| 198 | { code: "ERR_IMPORT_ATTRIBUTE_UNSUPPORTED" }, |
| 199 | ); |
| 200 | } |
| 201 | if (attributes.type === "json" && format !== "json") { |
| 202 | throw Object.assign( |
| 203 | new TypeError( |
| 204 | `Import type "json" is incompatible with ${format} for ${url}`, |
| 205 | ), |
| 206 | { code: "ERR_IMPORT_ATTRIBUTE_TYPE_INCOMPATIBLE" }, |
| 207 | ); |
| 208 | } |
| 209 | // Native require(JSON) omits importAttributes; ESM supplies an object even |
| 210 | // when empty. Conditions are user-configurable and cannot identify require. |
| 211 | if ( |
| 212 | format === "json" && |
| 213 | attributes.type === undefined && |
| 214 | context.importAttributes !== undefined |
| 215 | ) { |
| 216 | throw Object.assign( |
| 217 | new TypeError( |
| 218 | `JSON module ${url} requires an import attribute of type "json"`, |
| 219 | ), |
| 220 | { code: "ERR_IMPORT_ATTRIBUTE_MISSING" }, |
| 221 | ); |
| 222 | } |
| 223 | } |
| 224 |
| 225 | /** |
| 226 | * Create a resolve hook. Sync fetch functions produce sync hooks; async fetch |
| 227 | * functions produce async hooks. All HTTP paths follow redirects before Node |
| 228 | * chooses a module identity, so its relative imports use the final URL. |
| 229 | */ |
| 230 | export function createResolve( |
| 231 | fetchFn: (url: string) => CacheEntry, |
| 232 | mainUrl?: string, |
| 233 | ): ResolveHookSync; |
| 234 | export function createResolve( |
| 235 | fetchFn: (url: string) => Promise<CacheEntry>, |
| 236 | mainUrl?: string, |
| 237 | ): ResolveHookAsync; |
| 238 | export function createResolve( |
| 239 | fetchFn: (url: string) => CacheEntry | Promise<CacheEntry>, |
| 240 | mainUrl?: string, |
| 241 | ) { |
| 242 | const mainSpecifier = mainUrl |
| 243 | ? pathToFileURL(resolvePath(mainUrl)).href |
| 244 | : undefined; |
| 245 | let mainResolved = false; |
| 246 | return function resolve( |
| 247 | specifier: string, |
| 248 | context: ResolveHookContext, |
| 249 | nextResolve: NextResolve, |
| 250 | ): ResolveFnOutput | Promise<ResolveFnOutput> { |
| 251 | // Direct URLs, relative imports, CDN packages and the CLI entry share this path. |
| 252 | const resolveHttp = ( |
| 253 | url: string, |
| 254 | ): ResolveFnOutput | Promise<ResolveFnOutput> => { |
| 255 | const handleFetched = (entry: CacheEntry, synchronous: boolean): ResolveFnOutput => { |
| 256 | const format = inferFormat(entry.finalUrl, entry.contentType); |
| 257 | validateImportAttributes(entry.finalUrl, format, context); |
| 258 | // File URLs use Node's native CJS loader, which dispatches relative |
| 259 | // require() calls through sync hooks. |
| 260 | // Async hooks cannot intercept native require(), so retain their source path. |
| 261 | const commonjs = format === "commonjs" || format === "commonjs-typescript"; |
| 262 | if (tmpEnabled || (synchronous && commonjs)) { |
| 263 | verifyModuleLock(entry); |
| 264 | const temporaryPath = urlToTmpPath(entry.finalUrl, entry.contentType); |
| 265 | writeTmpFile(temporaryPath, entry.source); |
| 266 | return { |
| 267 | shortCircuit: true, |
| 268 | url: pathToFileURL(temporaryPath).href, |
| 269 | format, |
| 270 | }; |
| 271 | } |
| 272 | pendingLoads.set(entry.finalUrl, entry); |
| 273 | return { shortCircuit: true, url: entry.finalUrl, format }; |
| 274 | }; |
| 275 | const entry = fetchFn(url); |
| 276 | return entry instanceof Promise |
| 277 | ? entry.then((entry) => handleFetched(entry, false)) |
| 278 | : handleFetched(entry, true); |
| 279 | }; |
| 280 |
| 281 | // Redirect only this process's exact placeholder entry, never another |
| 282 | // parentless resolve (for example a Worker entry or a later preload). |
| 283 | if ( |
| 284 | mainUrl && |
| 285 | !mainResolved && |
| 286 | !context.parentURL && |
| 287 | specifier === mainSpecifier |
| 288 | ) { |
| 289 | mainResolved = true; |
| 290 | return resolveHttp(mainUrl); |
| 291 | } |
| 292 |
| 293 | // Installed npm: packages stay local; only MODULE_NOT_FOUND triggers a CDN fallback. |
| 294 | if (specifier.startsWith("npm:")) { |
| 295 | const bare = stripNpmSpecifier(specifier); |
| 296 | try { |
| 297 | return resolveLocalPackage(bare, context, nextResolve); |
| 298 | } catch (error) { |
| 299 | if ( |
| 300 | !( |
| 301 | error instanceof Error && |
| 302 | "code" in error && |
| 303 | error.code === "MODULE_NOT_FOUND" |
| 304 | ) |
| 305 | ) |
| 306 | throw error; |
| 307 | return resolveHttp((cdnBase ?? DEFAULT_CDN) + specifier.slice(4)); |
| 308 | } |
| 309 | } |
| 310 |
| 311 | // esm.sh is the only supported CDN with a /jsr/ endpoint. |
| 312 | if (specifier.startsWith("jsr:")) { |
| 313 | if (cdnBase && isEsmShCdn(cdnBase)) |
| 314 | return resolveHttp(jsrToCdnUrl(specifier, cdnBase)); |
| 315 | throw new Error( |
| 316 | `Cannot resolve "${specifier}": jsr: specifiers require --cdn=https://esm.sh/.`, |
| 317 | ); |
| 318 | } |
| 319 | if (isHttpUrl(specifier)) return resolveHttp(specifier); |
| 320 |
| 321 | const httpParent = getHttpParentUrl(context.parentURL); |
| 322 | if ( |
| 323 | cdnBase && |
| 324 | !resolvingLocalPackage && |
| 325 | isBareSpecifier(specifier) && |
| 326 | !isBuiltin(specifier) |
| 327 | ) { |
| 328 | // node_modules first; only a missing package falls back to the CDN. |
| 329 | // ESM resolution reports ERR_MODULE_NOT_FOUND, CJS reports MODULE_NOT_FOUND. |
| 330 | const localContext = |
| 331 | context.parentURL && !httpParent |
| 332 | ? context |
| 333 | : { ...context, parentURL: projectParentUrl() }; |
| 334 | try { |
| 335 | return nextResolve(specifier, localContext); |
| 336 | } catch (error) { |
| 337 | if ( |
| 338 | !( |
| 339 | error instanceof Error && |
| 340 | "code" in error && |
| 341 | (error.code === "MODULE_NOT_FOUND" || |
| 342 | error.code === "ERR_MODULE_NOT_FOUND") |
| 343 | ) |
| 344 | ) |
| 345 | throw error; |
| 346 | return resolveHttp(cdnBase + specifier); |
| 347 | } |
| 348 | } |
| 349 | if (httpParent && isRelativeSpecifier(specifier)) |
| 350 | return resolveHttp(new URL(specifier, httpParent).href); |
| 351 | // Native package resolution cannot use an HTTP parent. Keep its import/ |
| 352 | // require conditions but anchor it to the local project's node_modules. |
| 353 | if (httpParent) |
| 354 | return nextResolve(specifier, { |
| 355 | ...context, |
| 356 | parentURL: projectParentUrl(), |
| 357 | }); |
| 358 | return nextResolve(specifier, context); |
| 359 | }; |
| 360 | } |
| 361 |
| 362 | /** Create a load hook that supplies verified remote source bytes and their format. */ |
| 363 | export function createLoad(fetchFn: (url: string) => CacheEntry): LoadHookSync; |
| 364 | export function createLoad( |
| 365 | fetchFn: (url: string) => Promise<CacheEntry>, |
| 366 | ): LoadHookAsync; |
| 367 | export function createLoad( |
| 368 | fetchFn: (url: string) => CacheEntry | Promise<CacheEntry>, |
| 369 | ) { |
| 370 | return function load( |
| 371 | url: string, |
| 372 | context: LoadHookContext, |
| 373 | nextLoad: NextLoad, |
| 374 | ): LoadFnOutput | Promise<LoadFnOutput> { |
| 375 | if (!isHttpUrl(url)) { |
| 376 | // Importing a materialized .cts must enter the native CJS loader. It |
| 377 | // strips the original TypeScript bytes using the file's .cts extension. |
| 378 | // Native require() already selects that loader and keeps its TS format. |
| 379 | if ( |
| 380 | context.format === "commonjs-typescript" && |
| 381 | context.importAttributes !== undefined && |
| 382 | tmpPathToUrl(url) |
| 383 | ) { |
| 384 | return nextLoad(normalizeWindowsPath(url), { |
| 385 | ...context, |
| 386 | format: "commonjs", |
| 387 | }); |
| 388 | } |
| 389 | return nextLoad(normalizeWindowsPath(url), context); |
| 390 | } |
| 391 | const cached = pendingLoads.get(url); |
| 392 | pendingLoads.delete(url); |
| 393 | const handleFetched = (entry: CacheEntry): LoadFnOutput => { |
| 394 | verifyModuleLock(entry); |
| 395 | const format = inferFormat(entry.finalUrl, entry.contentType); |
| 396 | validateImportAttributes(entry.finalUrl, format, context); |
| 397 | return { shortCircuit: true, format, source: entry.source }; |
| 398 | }; |
| 399 | const entry = cached ?? fetchFn(url); |
| 400 | return entry instanceof Promise |
| 401 | ? entry.then(handleFetched) |
| 402 | : handleFetched(entry); |
| 403 | }; |
| 404 | } |
| 405 |