| 6 | * |
| 7 | * Usage: |
| 8 | * node --import node-url-import/register ./app.mjs |
| 9 | * node --import node-url-import/register ./app.cjs # Node 24+ only |
| 10 | */ |
| 11 |
| 12 | import module from "node:module"; |
| 13 | import process from "node:process"; |
| 14 | import { resolve as resolvePath } from "node:path"; |
| 15 | import { isHttpUrl } from "./constants.ts"; |
| 16 |
| 17 | // Internal remote-entry handoff: Node normalizes argv[1] as a local path, so |
| 18 | // preserve the original URL (including query/fragment) for the resolve hook. |
| 19 | let mainUrl = process.env.URL_IMPORT_MAIN; |
| 20 | const mainCandidates = process.env.URL_IMPORT_MAIN_CANDIDATES; |
| 21 | // Internal entry metadata must not be inherited by later Workers or children. |
| 22 | delete process.env.URL_IMPORT_MAIN; |
| 23 | delete process.env.URL_IMPORT_MAIN_CANDIDATES; |
| 24 | if (mainCandidates) { |
| 25 | const candidates: Record<string, string> = JSON.parse(mainCandidates); |
| 26 | // Node has parsed its flags. Exclude the CLI's injected --import pair; |
| 27 | // HTTP-valued options and eval arguments must not become remote mains. |
| 28 | const index = process.execArgv.length - 2; |
| 29 | const target = candidates[candidates[index] === "--" ? index + 1 : index]; |
| 30 | if (target && isHttpUrl(target) && resolvePath(target) === process.argv[1]) { |
| 31 | mainUrl = target; |
| 32 | } |
| 33 | } |
| 34 |
| 35 | export const importMetaUrl = import.meta.url; |
| 36 |
| 37 | if (typeof module.registerHooks === "function") { |
| 38 | // Node 22.15+: synchronous hooks that intercept both import and require |
| 39 | const { createResolve, createLoad } = await import("./hooks.ts"); |
| 40 | const { fetchModuleSync } = await import("./sync-fetch.ts"); |
| 41 | module.registerHooks({ |
| 42 | resolve: createResolve(fetchModuleSync, mainUrl), |
| 43 | load: createLoad(fetchModuleSync), |
| 44 | }); |
| 45 | } else { |
| 46 | // Node 18.19+ / 20.6+: async hooks via module.register() (ESM only) |
| 47 | const loaderUrl = new URL( |
| 48 | import.meta.url.endsWith(".ts") ? "./loader.ts" : "./loader.js", |
| 49 | import.meta.url, |
| 50 | ); |
| 51 | module.register(loaderUrl, import.meta.url, { data: { mainUrl } }); |
| 52 | } |
| 53 |