diff --git a/NativeScript/runtime/ModuleInternal.h b/NativeScript/runtime/ModuleInternal.h index 29ad542e..700af73d 100644 --- a/NativeScript/runtime/ModuleInternal.h +++ b/NativeScript/runtime/ModuleInternal.h @@ -101,15 +101,21 @@ class ModuleInternal { private: static void RequireCallback(const v8::FunctionCallbackInfo& info); + // The global require's native half in debug builds: RequireCallback plus a + // one-time warning per ES module that passes it a relative specifier. + static void DebugGlobalRequireCallback( + const v8::FunctionCallbackInfo& info); static void CreateRequireCallback( const v8::FunctionCallbackInfo& info); // A require bound to `dirName`, whose ES module loads evaluate under // `options`. The options ride along as trailing arguments to the require // factory, so nothing about them is ambient — and they are resolved once at - // mint time, never per require() call. + // mint time, never per require() call. `requireInternal` defaults to the + // RequireCallback function every module-scoped require shares. v8::Local GetRequireFunction( v8::Isolate* isolate, const std::string& dirName, - const ModuleEvaluationOptions& options); + const ModuleEvaluationOptions& options, + v8::Local requireInternal = v8::Local()); v8::Local LoadImpl(v8::Isolate* isolate, const std::string& moduleName, const std::string& baseDir, bool& isData, diff --git a/NativeScript/runtime/ModuleInternal.mm b/NativeScript/runtime/ModuleInternal.mm index f957a3e6..a8d7b186 100644 --- a/NativeScript/runtime/ModuleInternal.mm +++ b/NativeScript/runtime/ModuleInternal.mm @@ -173,8 +173,21 @@ static bool IsHttpModulePath(const std::string& path) { // Use shortened path for global require function to avoid V8 parsing issues std::string globalRequirePath = "/app"; + // The bound directory cannot tell the global require apart (a CommonJS + // module in the app root is bound to "/app" too), so debug builds give it a + // native half of its own. + Local globalRequireInternal; + if (RuntimeConfig.IsDebug) { + globalRequireInternal = + FunctionTemplate::New(isolate, DebugGlobalRequireCallback, + External::New(isolate, this, v8::kExternalPointerTypeTagDefault)) + ->GetFunction(context) + .ToLocalChecked(); + } + Local globalRequire = GetRequireFunction( - isolate, globalRequirePath, RequireEvaluationOptions(ModuleEvaluationPolicy::kSyncStrict)); + isolate, globalRequirePath, RequireEvaluationOptions(ModuleEvaluationPolicy::kSyncStrict), + globalRequireInternal); bool success = global->Set(context, tns::ToV8String(isolate, "require"), globalRequire).FromMaybe(false); if (!success) { @@ -360,10 +373,12 @@ throw NativeScriptException( } Local ModuleInternal::GetRequireFunction(Isolate* isolate, const std::string& dirName, - const ModuleEvaluationOptions& options) { + const ModuleEvaluationOptions& options, + Local requireInternal) { Local requireFuncFactory = requireFactoryFunction_->Get(isolate); Local context = isolate->GetCurrentContext(); - Local requireInternalFunc = this->requireFunction_->Get(isolate); + Local requireInternalFunc = + requireInternal.IsEmpty() ? this->requireFunction_->Get(isolate) : requireInternal; Local args[6]{ requireInternalFunc, tns::ToV8String(isolate, dirName.c_str()), @@ -453,6 +468,75 @@ throw NativeScriptException( return "type " + std::string(typeName) + " (" + rendered + ")"; } +namespace { +// The ES modules (by registry key) already warned about a relative specifier +// passed to the global require. Keyed by registry key rather than script id so +// an HMR recompile of the same module does not warn again. +struct GlobalRequireWarningState { + robin_hood::unordered_set warnedModuleKeys; +}; +} // namespace + +// The specifiers the resolver joins onto the bound directory. Exactly "./" is +// left out: every require resolves it to the app's main entry. +static bool IsDirectoryRelativeSpecifier(const std::string& specifier) { + return specifier == "." || specifier == ".." || specifier.rfind("../", 0) == 0 || + (specifier.rfind("./", 0) == 0 && specifier != "./"); +} + +// Never runs JS and never throws: it may only add a log line to a require(). +static void WarnIfRelativeGlobalRequireFromEsModule(Isolate* isolate, Local specifierValue, + int requireFactoryScriptId) { + if (!specifierValue->IsString()) { + return; + } + const std::string specifier = tns::ToString(isolate, specifierValue); + if (!IsDirectoryRelativeSpecifier(specifier)) { + return; + } + + // The require() closure is the top frame; the caller is the first frame + // from any other script. + HandleScope handleScope(isolate); + Local stack = StackTrace::CurrentStackTrace(isolate, 3); + int callerScriptId = v8::Message::kNoScriptIdInfo; + for (int i = 0; i < stack->GetFrameCount(); i++) { + int scriptId = stack->GetFrame(isolate, i)->GetScriptId(); + if (scriptId != requireFactoryScriptId) { + callerScriptId = scriptId; + break; + } + } + if (callerScriptId == v8::Message::kNoScriptIdInfo) { + return; + } + + const std::string moduleKey = LookupModuleKeyForScriptId(isolate, callerScriptId); + if (moduleKey.empty()) { + return; + } + auto* state = Caches::StateFor(isolate); + if (state == nullptr || !state->warnedModuleKeys.insert(moduleKey).second) { + return; + } + + Log(@"NativeScript: require(\"%s\") in ES module %s resolves against the app root, not the " + @"module's folder. Use createRequire(import.meta.url) from \"ns:module\" (from a module " + @"loaded over http(s): createRequire with an app file path).", + specifier.c_str(), tns::ReportedModuleUrl(moduleKey).c_str()); +} + +void ModuleInternal::DebugGlobalRequireCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + if (info.Length() > 0) { + ModuleInternal* moduleInternal = static_cast( + info.Data().As()->Value(v8::kExternalPointerTypeTagDefault)); + WarnIfRelativeGlobalRequireFromEsModule( + isolate, info[0], moduleInternal->requireFactoryFunction_->Get(isolate)->ScriptId()); + } + RequireCallback(info); +} + void ModuleInternal::RequireCallback(const FunctionCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); diff --git a/NativeScript/runtime/ModuleInternalCallbacks.h b/NativeScript/runtime/ModuleInternalCallbacks.h index 86bb5e84..ec4758d2 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.h +++ b/NativeScript/runtime/ModuleInternalCallbacks.h @@ -96,6 +96,11 @@ void RemoveModuleFromRegistry(v8::Isolate* isolate, std::string LookupModuleKeyForModule(v8::Isolate* isolate, v8::Local mod); +// The registry key of the live source-text module compiled as script +// `scriptId` (a StackFrame's GetScriptId()), or empty when no registered ES +// module has that script. A linear scan of the registry: diagnostics only. +std::string LookupModuleKeyForScriptId(v8::Isolate* isolate, int scriptId); + // Record `mod` in the identity-hash index under `canonicalKey`. Call alongside // every registry insert performed outside ModuleInternalCallbacks.mm. void IndexModuleForIsolate(v8::Isolate* isolate, diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 6b226d2a..4f2a0016 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -353,6 +353,28 @@ void IndexRegisteredModule(ModuleLoaderState& state, const std::string& key, return FindKeyForModule(*state, isolate, mod); } +std::string LookupModuleKeyForScriptId(v8::Isolate* isolate, int scriptId) { + auto* state = ModuleLoaderStateFor(isolate); + if (state == nullptr) { + return std::string(); + } + for (const auto& entry : state->registry) { + if (entry.second.IsEmpty()) { + continue; + } + v8::Local mod = entry.second.Get(isolate); + // ScriptId() aborts on anything else. + if (!mod->IsSourceTextModule() || mod->GetStatus() == v8::Module::kErrored) { + continue; + } + if (mod->ScriptId() == scriptId) { + std::string key = FindKeyForModule(*state, isolate, mod); + return key.empty() ? entry.first : key; + } + } + return std::string(); +} + namespace { // The single module request in the facade source, and the source itself. Both // match Node's required_module_facade_source_string so the semantics (live diff --git a/TestRunner/app/tests/CreateRequireTests.js b/TestRunner/app/tests/CreateRequireTests.js index 91e70412..8af80ee0 100644 --- a/TestRunner/app/tests/CreateRequireTests.js +++ b/TestRunner/app/tests/CreateRequireTests.js @@ -323,6 +323,86 @@ describe("createRequire", function () { }); }); +// An ES module has no require of its own, so a bare `require` in one is the +// global require, bound to the app root. Debug builds log a one-time warning +// per ES module for a relative specifier passed to it; the fixtures split the +// callers so each one's warning (or its absence) shows up separately in the +// device log. +describe("the global require in an ES module", function () { + var fixtures = "~/tests/esm/global-require/sub/"; + + function withModule(name, done, fn) { + import(fixtures + name).then(function (mod) { + fn(mod); + done(); + }).catch(function (e) { + expect("rejected: " + ((e && e.message) || e)).toBe("resolved"); + done(); + }); + } + + function errorOf(fn) { + try { + fn(); + } catch (e) { + return String((e && e.message) || e); + } + return ""; + } + + function expectResolvedAgainstAppRoot(message, specifier) { + expect(message).toContain("Cannot find module '" + specifier + "'"); + expect(message).toMatch(/Base directory: [^\n]*\/app\n/); + expect(message).not.toContain("global-require/sub"); + } + + it("resolves a relative specifier against the app root, not the module's folder", + function (done) { + withModule("relative.mjs", done, function (mod) { + expectResolvedAgainstAppRoot( + errorOf(function () { mod.load("./global-require-sibling.js"); }), + "global-require-sibling.js"); + // Repeated and different relative specifiers behave the same. + expectResolvedAgainstAppRoot( + errorOf(function () { mod.load("./global-require-sibling.js"); }), + "global-require-sibling.js"); + expect(errorOf(function () { mod.load("../sub/global-require-sibling.js"); })) + .toContain("Cannot find module"); + }); + }); + + it("resolves a non-relative specifier as any other require does", function (done) { + withModule("non-relative.mjs", done, function (mod) { + expect(mod.load("~/tests/esm/global-require/sub/global-require-sibling.js").tag) + .toBe("global-require-sibling"); + expect(mod.load("ns:module")).toBe(require("ns:module")); + }); + }); + + it("leaves createRequire(import.meta.url) resolving against the module's folder", + function (done) { + withModule("create-require.mjs", done, function (mod) { + expect(mod.load("./global-require-sibling.js").tag).toBe("global-require-sibling"); + }); + }); + + it("resolves against the app root from a classic script an ES module created", + function (done) { + withModule("classic-caller.mjs", done, function (mod) { + expectResolvedAgainstAppRoot( + errorOf(function () { mod.load("./global-require-from-classic.js"); }), + "global-require-from-classic.js"); + }); + }); + + it("resolves against the app root from a CommonJS module", function () { + var caller = require("./esm/global-require/sub/commonjs-caller.js"); + expectResolvedAgainstAppRoot( + errorOf(function () { caller.load("./global-require-from-commonjs.js"); }), + "global-require-from-commonjs.js"); + }); +}); + // `~` marks the app root; the separator after it is optional. describe("app-root specifiers", function () { it("resolves ~/path", function () { diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index 2d59a12d..9565285b 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -2098,6 +2098,32 @@ describe("HTTP ESM Loader", function() { done(); }); }); + + it("leaves the global require resolving relative specifiers against the app root", + function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + import(origin + "/esm/global-require.mjs").then(function (mod) { + var message = ""; + try { + mod.load("./global-require-from-http.js"); + } catch (e) { + message = String((e && e.message) || e); + } + expect(message).toContain("Cannot find module 'global-require-from-http.js'"); + expect(message).toMatch(/Base directory: [^\n]*\/app\n/); + expect(mod.load("~/tests/esm/global-require/sub/global-require-sibling.js").tag) + .toBe("global-require-sibling"); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); }); describe("an import-map entry keyed by a file module's own URL", function () { diff --git a/TestRunner/app/tests/esm/global-require/sub/classic-caller.mjs b/TestRunner/app/tests/esm/global-require/sub/classic-caller.mjs new file mode 100644 index 00000000..3907e50e --- /dev/null +++ b/TestRunner/app/tests/esm/global-require/sub/classic-caller.mjs @@ -0,0 +1,3 @@ +// The require() call sits in a classic script (a Function body) that this ES +// module merely creates and exports. +export const load = new Function("specifier", "return require(specifier);"); diff --git a/TestRunner/app/tests/esm/global-require/sub/commonjs-caller.js b/TestRunner/app/tests/esm/global-require/sub/commonjs-caller.js new file mode 100644 index 00000000..d3c195c3 --- /dev/null +++ b/TestRunner/app/tests/esm/global-require/sub/commonjs-caller.js @@ -0,0 +1,4 @@ +// A CommonJS module calling the global require rather than its own. +exports.load = function (specifier) { + return globalThis.require(specifier); +}; diff --git a/TestRunner/app/tests/esm/global-require/sub/create-require.mjs b/TestRunner/app/tests/esm/global-require/sub/create-require.mjs new file mode 100644 index 00000000..7ae85e4e --- /dev/null +++ b/TestRunner/app/tests/esm/global-require/sub/create-require.mjs @@ -0,0 +1,7 @@ +import { createRequire } from "ns:module"; + +const moduleRequire = createRequire(import.meta.url); + +export function load(specifier) { + return moduleRequire(specifier); +} diff --git a/TestRunner/app/tests/esm/global-require/sub/global-require-sibling.js b/TestRunner/app/tests/esm/global-require/sub/global-require-sibling.js new file mode 100644 index 00000000..14493e70 --- /dev/null +++ b/TestRunner/app/tests/esm/global-require/sub/global-require-sibling.js @@ -0,0 +1 @@ +exports.tag = "global-require-sibling"; diff --git a/TestRunner/app/tests/esm/global-require/sub/non-relative.mjs b/TestRunner/app/tests/esm/global-require/sub/non-relative.mjs new file mode 100644 index 00000000..d9c5566c --- /dev/null +++ b/TestRunner/app/tests/esm/global-require/sub/non-relative.mjs @@ -0,0 +1,5 @@ +// The global require, reached from an ES module that only ever passes it +// non-relative specifiers. +export function load(specifier) { + return require(specifier); +} diff --git a/TestRunner/app/tests/esm/global-require/sub/relative.mjs b/TestRunner/app/tests/esm/global-require/sub/relative.mjs new file mode 100644 index 00000000..54117b55 --- /dev/null +++ b/TestRunner/app/tests/esm/global-require/sub/relative.mjs @@ -0,0 +1,4 @@ +// An ES module has no require of its own: `require` here is the global one. +export function load(specifier) { + return require(specifier); +} diff --git a/TestRunnerTests/TestRunnerTests.swift b/TestRunnerTests/TestRunnerTests.swift index 079459ae..167cd555 100644 --- a/TestRunnerTests/TestRunnerTests.swift +++ b/TestRunnerTests/TestRunnerTests.swift @@ -157,6 +157,14 @@ class TestRunnerTests: XCTestCase { return } + // A served ES module whose `load(spec)` calls the global require. + if path == "/esm/global-require.mjs" { + let body = "export function load(spec) { return require(spec); }\n" + startResponse("200 OK", [("Content-Type", "application/javascript; charset=utf-8")]) + sendBody(body.data(using: .utf8) ?? Data()) + return + } + // ── MIME-gate routes ────────────────────────────── if path == "/esm/html-fallback.mjs" { // The SPA-fallback shape: an unknown path answered with the diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index e9fa668f..e5536278 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -1022,6 +1022,14 @@ The "id" argument must be of type string. Received `` follows Node's `determineSpecificType`: `undefined`, `null`, `type number (42)`, `an instance of Object`, `function foo`, and so on. +An ES module has no `require` of its own; the global `require` is available +there for compatibility and resolves a relative specifier (`./x`, `../x`) +against the app root, whichever module calls it. An ES module that needs +module-relative resolution uses `createRequire(import.meta.url)`, or, when it +was loaded over http(s), `createRequire` with an app file path. Debug builds +log a warning once per ES module that passes a relative specifier to the +global `require`. + ### `require()` of an ES module `require()` of an ES module works, under Node's `require(esm)` rule: the graph diff --git a/types/ns-module.d.ts b/types/ns-module.d.ts index c5efd298..e4e036c0 100644 --- a/types/ns-module.d.ts +++ b/types/ns-module.d.ts @@ -110,6 +110,9 @@ declare module "ns:module" { * * `require.resolve`, `require.cache` and `require.main` are not * implemented and are absent from the returned function. + * + * In an ES module, `createRequire(import.meta.url)` is the module-relative + * `require`: the global one resolves relative specifiers against the app root. */ export function createRequire( filenameOrURL: string | URL,