From e0b581c008da4236ac5c2f2ae3bfce1ab64aef44 Mon Sep 17 00:00:00 2001 From: Hiroki Osame Date: Sun, 30 Jun 2024 11:39:40 +0900 Subject: [PATCH] test: assert package can be loaded relative to data url --- src/cjs/api/module-resolve-filename.ts | 29 +++++++++++++++++++------- tests/specs/api.ts | 5 ++++- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/src/cjs/api/module-resolve-filename.ts b/src/cjs/api/module-resolve-filename.ts index 154cf68b7..f95582f38 100644 --- a/src/cjs/api/module-resolve-filename.ts +++ b/src/cjs/api/module-resolve-filename.ts @@ -169,19 +169,32 @@ export const createResolveFilename = ( request = interopCjsExports(request); - if (parent?.filename) { - const filePath = getOriginalFilePath(parent.filename); - if (filePath) { - parent.filename = filePath.split('?')[0]; - } - } - // Strip query string const requestAndQuery = request.split('?'); const searchParams = new URLSearchParams(requestAndQuery[1]); - // Inherit parent namespace if it exists if (parent?.filename) { + const filePath = getOriginalFilePath(parent.filename); + if (filePath) { + const newFilename = filePath.split('?')[0]; + + /** + * Can't delete the old cache entry because there's an assertion + * https://github.com/nodejs/node/blob/v20.15.0/lib/internal/modules/esm/translators.js#L347 + */ + // delete Module._cache[parent.filename]; + + parent.filename = newFilename; + // @ts-expect-error - private property + parent.path = path.dirname(newFilename); + // https://github.com/nodejs/node/blob/v20.15.0/lib/internal/modules/esm/translators.js#L383 + // @ts-expect-error - private property + parent.paths = Module._nodeModulePaths(parent.path); + + Module._cache[newFilename] = parent as NodeModule; + } + + // Inherit parent namespace if it exists const parentQuery = new URLSearchParams(parent.filename.split('?')[1]); const parentNamespace = parentQuery.get('namespace'); if (parentNamespace) { diff --git a/tests/specs/api.ts b/tests/specs/api.ts index fd11668c6..946f07b0e 100644 --- a/tests/specs/api.ts +++ b/tests/specs/api.ts @@ -27,6 +27,9 @@ const tsFiles = { `, cjs: { + node_modules: { + 'pkg/index.js': 'module.exports = 1', + }, 'exports-no.cts': ` // Supports decorators const log = (target, key, descriptor) => descriptor; @@ -36,7 +39,7 @@ const tsFiles = { } console.log("cts loaded" as string) `, - 'exports-yes.cts': 'module.exports = require("./reexport.cjs") as string', + 'exports-yes.cts': 'module.exports = require("./reexport.cjs") as string; require("pkg");', 'esm-syntax.js': 'export const esmSyntax = "esm syntax"', 'reexport.cjs': ` exports.cjsReexport = "cjsReexport";