(
url: string,
context: {},
defaultGetFormat: typeof getFormat
)
| 288 | } |
| 289 | |
| 290 | async function getFormat( |
| 291 | url: string, |
| 292 | context: {}, |
| 293 | defaultGetFormat: typeof getFormat |
| 294 | ): Promise<{ format: NodeLoaderHooksFormat }> { |
| 295 | const defer = (overrideUrl: string = url) => |
| 296 | defaultGetFormat(overrideUrl, context, defaultGetFormat); |
| 297 | |
| 298 | // See: https://github.com/nodejs/node/discussions/41711 |
| 299 | // nodejs will likely implement a similar fallback. Till then, we can do our users a favor and fallback today. |
| 300 | async function entrypointFallback( |
| 301 | cb: () => ReturnType<typeof getFormat> |
| 302 | ): ReturnType<typeof getFormat> { |
| 303 | try { |
| 304 | return await cb(); |
| 305 | } catch (getFormatError) { |
| 306 | if (!rememberIsProbablyEntrypoint.has(url)) throw getFormatError; |
| 307 | return { format: 'commonjs' }; |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | const parsed = parseUrl(url); |
| 312 | |
| 313 | if (!isFileUrlOrNodeStyleSpecifier(parsed)) { |
| 314 | return entrypointFallback(defer); |
| 315 | } |
| 316 | |
| 317 | const { pathname } = parsed; |
| 318 | assert( |
| 319 | pathname !== null, |
| 320 | 'ESM getFormat() hook: URL should never have null pathname' |
| 321 | ); |
| 322 | |
| 323 | const nativePath = fileURLToPath(url); |
| 324 | |
| 325 | let nodeSays: { format: NodeLoaderHooksFormat }; |
| 326 | |
| 327 | // If file has extension not understood by node, then ask node how it would treat the emitted extension. |
| 328 | // E.g. .mts compiles to .mjs, so ask node how to classify an .mjs file. |
| 329 | const ext = extname(nativePath); |
| 330 | const tsNodeIgnored = tsNodeService.ignored(nativePath); |
| 331 | const nodeEquivalentExt = extensions.nodeEquivalents.get(ext); |
| 332 | if (nodeEquivalentExt && !tsNodeIgnored) { |
| 333 | nodeSays = await entrypointFallback(() => |
| 334 | defer(formatUrl(pathToFileURL(nativePath + nodeEquivalentExt))) |
| 335 | ); |
| 336 | } else { |
| 337 | try { |
| 338 | nodeSays = await entrypointFallback(defer); |
| 339 | } catch (e) { |
| 340 | if ( |
| 341 | e instanceof Error && |
| 342 | tsNodeIgnored && |
| 343 | extensions.nodeDoesNotUnderstand.includes(ext) |
| 344 | ) { |
| 345 | e.message += |
| 346 | `\n\n` + |
| 347 | `Hint:\n` + |
no test coverage detected
searching dependent graphs…