From 3b0c44e2d3e2690e9e4e193b714f93c7d4edafa3 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 1 Dec 2026 22:28:07 -0300 Subject: [PATCH 01/13] test(runtime): pin the spelling of the module URLs dev tooling emits Records what the loader does today for the URL shapes dev servers emit, both as registry keys (with and without a tooling-shaped canonicalization vocabulary) and as loaded modules reached from a file module directly and through an import-map entry: import.meta.url, getLoadedModuleUrls(), the request target the server saw, and eviction by invalidateModules. Ports NativeScript/ios@3fcad404 (part of NativeScript/ios#609). --- .../app/esm/tooling-url/static-importer.mjs | 1 + .../assets/app/tests/testEsmHttpLoader.js | 91 ++++++++++++++++ .../src/main/assets/app/tests/testNsModule.js | 101 ++++++++++++++++++ 3 files changed, 193 insertions(+) create mode 100644 test-app/app/src/main/assets/app/esm/tooling-url/static-importer.mjs diff --git a/test-app/app/src/main/assets/app/esm/tooling-url/static-importer.mjs b/test-app/app/src/main/assets/app/esm/tooling-url/static-importer.mjs new file mode 100644 index 000000000..d4c10436f --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/tooling-url/static-importer.mjs @@ -0,0 +1 @@ +export * as dep from "ns-tooling-url-static"; diff --git a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js index 51966949d..e7fe55e1b 100644 --- a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js +++ b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js @@ -1436,6 +1436,97 @@ describe("HTTP ESM Loader", function () { }); }); }); + + // The spelling of these URLs is what dev tooling compares module URLs + // against, so it must survive every route into the loader byte for byte. + describe("module URLs in the shapes dev tooling emits", function () { + useHttpTimeout(); + + var nsModule = require("ns:module"); + + afterEach(function () { + nsModule.configureLoader({ importMap: { imports: {} } }); + }); + + // Each module reports the request target the server saw and its own + // import.meta.url. + function expectSpelledAsWritten(ns, url) { + var target = url.slice(url.indexOf("/", url.indexOf("://") + 3)); + var q = target.indexOf("?"); + expect(ns.url).toBe(url); + expect(ns.path).toBe(q < 0 ? target : target.slice(0, q)); + expect(ns.query).toBe(q < 0 ? "" : target.slice(q + 1)); + expect(nsModule.getLoadedModuleUrls()).toContain(url); + } + + function expectEvicted(urls) { + nsModule.invalidateModules(urls); + var loaded = nsModule.getLoadedModuleUrls(); + urls.forEach(function (url) { + expect(loaded).not.toContain(url); + }); + } + + it("keeps them as written when a file module imports them", function (done) { + var written = origin.replace("127.0.0.1", "LOCALHOST"); + var base = origin + "/esm/resolve/tooling-direct"; + var urls = [ + base + "/ns/m/src/app.ts?v=abc", + base + "/ns/core/index.js", + base + "/ns/node/x", + base + "/ns/m/node_modules/pkg/index.js", + base + "/ns/asm?path=%2Fsrc%2FApp.vue&mode=inline", + base + "/ns/asm?path=/src/App.vue&mode=inline", + base + "/ns/sfc/src/App.vue?vue&type=script", + base + "/ns/m/q.js?b=2&a=1", + base + "/@ng/component?c=x&t=1", + base + "/@id/__x00__virtual:thing", + base + "/@fs/Users/me/proj/x.ts", + written + "/esm/resolve/tooling-direct/ns/m/upper.js?v=1", + ]; + Promise.all(urls.map(function (url) { + return import(url); + })).then(function (namespaces) { + namespaces.forEach(function (ns, i) { + expectSpelledAsWritten(ns, urls[i]); + }); + expectEvicted(urls); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("keeps them as written when an import-map entry targets them", function (done) { + var written = origin.replace("127.0.0.1", "LOCALHOST"); + var base = origin + "/esm/resolve/tooling-mapped"; + var dynamicUrl = base + "/ns/m/src/dynamic.ts?v=abc"; + var staticUrl = base + "/ns/asm?path=%2Fsrc%2FApp.vue&mode=inline"; + var upperUrl = written + "/esm/resolve/tooling-mapped/ns/m/upper.js?b=2&a=1"; + nsModule.configureLoader({ + importMap: { + imports: { + "ns-tooling-url-dynamic": dynamicUrl, + "ns-tooling-url-static": staticUrl, + "ns-tooling-url-upper": upperUrl, + }, + }, + }); + Promise.all([ + import("ns-tooling-url-dynamic"), + import("~/esm/tooling-url/static-importer.mjs"), + import("ns-tooling-url-upper"), + ]).then(function (namespaces) { + expectSpelledAsWritten(namespaces[0], dynamicUrl); + expectSpelledAsWritten(namespaces[1].dep, staticUrl); + expectSpelledAsWritten(namespaces[2], upperUrl); + expectEvicted([dynamicUrl, staticUrl, upperUrl]); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + }); }); // A bare `@` is not a specifier the runtime knows: it resolves through the diff --git a/test-app/app/src/main/assets/app/tests/testNsModule.js b/test-app/app/src/main/assets/app/tests/testNsModule.js index b3597024e..1af659732 100644 --- a/test-app/app/src/main/assets/app/tests/testNsModule.js +++ b/test-app/app/src/main/assets/app/tests/testNsModule.js @@ -47,6 +47,8 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () { return require("ns:module").canonicalizeHttpUrlKey; } + // A registered key is canonicalized again whenever it is looked up, so a key + // must be a fixed point. function checkKey(input, expected) { var canon = getCanon(); if (typeof canon !== "function") { @@ -54,8 +56,77 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () { return; } expect(canon(input)).toBe(expected); + expect(canon(expected)).toBe(expected); } + // [input, key with no vocabulary, key under TOOLING_VOCABULARY] + var TOOLING_URLS = [ + ["http://h:5173/ns/m/src/app.ts?v=abc", + "http://h:5173/ns/m/src/app.ts?v=abc", + "http://h:5173/ns/m/src/app.ts"], + ["http://h:5173/ns/core/index.js", + "http://h:5173/ns/core/index.js", + "http://h:5173/ns/core/index.js"], + ["http://h:5173/ns/node/x", + "http://h:5173/ns/node/x", + "http://h:5173/ns/node/x"], + ["http://h:5173/ns/m/node_modules/pkg/index.js?v=abc", + "http://h:5173/ns/m/node_modules/pkg/index.js?v=abc", + "http://h:5173/ns/m/node_modules/pkg/index.js"], + ["http://h:5173/ns/asm?path=%2Fsrc%2FApp.vue&mode=inline", + "http://h:5173/ns/asm?path=%2Fsrc%2FApp.vue&mode=inline", + "http://h:5173/ns/asm?mode=inline&path=%2Fsrc%2FApp.vue"], + ["http://h:5173/ns/asm?path=/src/App.vue&mode=inline", + "http://h:5173/ns/asm?path=/src/App.vue&mode=inline", + "http://h:5173/ns/asm?mode=inline&path=/src/App.vue"], + ["http://h:5173/ns/sfc/src/App.vue?vue&type=script", + "http://h:5173/ns/sfc/src/App.vue?vue&type=script", + "http://h:5173/ns/sfc/src/App.vue?type=script&vue"], + ["http://h:5173/ns/m/q.js?b=2&a=1", + "http://h:5173/ns/m/q.js?b=2&a=1", + "http://h:5173/ns/m/q.js?a=1&b=2"], + ["http://h:5173/@ng/component?c=x&t=1", + "http://h:5173/@ng/component?c=x&t=1", + "http://h:5173/@ng/component?c=x&t=1"], + ["http://h:5173/@id/__x00__virtual:thing?import", + "http://h:5173/@id/__x00__virtual:thing?import", + "http://h:5173/@id/__x00__virtual:thing"], + ["http://h:5173/@fs/Users/me/proj/x.ts?t=1", + "http://h:5173/@fs/Users/me/proj/x.ts?t=1", + "http://h:5173/@fs/Users/me/proj/x.ts"], + ["http://h:5173/node_modules/.vite/deps/pkg.js?v=abc", + "http://h:5173/node_modules/.vite/deps/pkg.js?v=abc", + "http://h:5173/node_modules/.vite/deps/pkg.js"], + ["http://MyMac.local:5173/ns/m/app.js?v=1", + "http://MyMac.local:5173/ns/m/app.js?v=1", + "http://MyMac.local:5173/ns/m/app.js"], + ["http://MyMac.local:5173/ns/m/app.js?", + "http://MyMac.local:5173/ns/m/app.js?", + "http://MyMac.local:5173/ns/m/app.js"], + ["http://MyMac.local:5173/ns/m/app.js#", + "http://MyMac.local:5173/ns/m/app.js", + "http://MyMac.local:5173/ns/m/app.js"], + ["http://h:80/ns/m/app.js?v=1", + "http://h:80/ns/m/app.js?v=1", + "http://h:80/ns/m/app.js"], + ["http://192.168.1.20:5173/ns/m/app.js?v=1", + "http://192.168.1.20:5173/ns/m/app.js?v=1", + "http://192.168.1.20:5173/ns/m/app.js"], + ["http://[::1]:5173/ns/m/app.js?v=1", + "http://[::1]:5173/ns/m/app.js?v=1", + "http://[::1]:5173/ns/m/app.js"], + // The URL parser rejects a zone id; the key keeps the URL as written. + ["http://[fe80::1%25en0]:5173/ns/m/app.js?v=1#x", + "http://[fe80::1%25en0]:5173/ns/m/app.js?v=1", + "http://[fe80::1%25en0]:5173/ns/m/app.js"], + ]; + + var TOOLING_VOCABULARY = { + stripParams: ["t", "v", "import"], + forPathPrefixes: ["/ns/", "/@id/", "/@fs/", "/node_modules/.vite/"], + preserveQueryFor: ["/@ng/component"], + }; + it("is exposed as a function in debug builds", function () { var canon = getCanon(); if (typeof canon !== "function") { @@ -89,6 +160,36 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () { checkKey("https://cdn.example.com/lib.js?token=abc#frag", "https://cdn.example.com/lib.js?token=abc"); }); + + it("keeps the URLs dev tooling emits as written", function () { + TOOLING_URLS.forEach(function (row) { + checkKey(row[0], row[1]); + }); + }); + }); + + describe("with a tooling-shaped vocabulary", function () { + beforeEach(function () { + if (typeof getCanon() !== "function") { + return; + } + require("ns:module").configureLoader({ canonicalization: TOOLING_VOCABULARY }); + }); + + afterEach(function () { + if (typeof getCanon() !== "function") { + return; + } + require("ns:module").configureLoader({ + canonicalization: { stripParams: [], forPathPrefixes: [], preserveQueryFor: [] }, + }); + }); + + it("keys the URLs dev tooling emits", function () { + TOOLING_URLS.forEach(function (row) { + checkKey(row[0], row[2]); + }); + }); }); // The canonicalization vocabulary is per-isolate loader state, so each spec From 77e9f7bfe2ac1b55b6fe868def28f2f402316c98 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 1 Dec 2026 22:28:31 -0300 Subject: [PATCH 02/13] refactor(runtime): one shared unit for the loader's module URL helpers IsHttpRegistryKey, ParseModuleUrl and the written-authority rule move out of ModuleInternalCallbacks.cpp into ModuleUrl, which also gains NormalizeHttpModuleUrl: the spelling the loader gives an absolute http(s) module URL, falling back to the input itself for an HTTP-prefixed string the URL parser rejects. HttpLoader's string repair of the same name, which the next commits retire, becomes RepairLegacyHttpModuleUrl. ParseModuleUrl now rebuilds the written-authority href by replacing only the authority inside the parser's href. Rebuilding from the pathname, search and hash getters lost a bare trailing '?' or '#', so the re-parse check failed and the parser's lowercased host replaced the written one. Ports NativeScript/ios@ae45c1ff (part of NativeScript/ios#609). --- .../assets/app/tests/testEsmHttpLoader.js | 14 +++ test-app/runtime/CMakeLists.txt | 1 + .../runtime/src/main/cpp/CallbackHandlers.cpp | 2 +- test-app/runtime/src/main/cpp/HttpLoader.cpp | 2 +- test-app/runtime/src/main/cpp/HttpLoader.h | 2 +- .../runtime/src/main/cpp/ModuleInternal.cpp | 8 +- .../src/main/cpp/ModuleInternalCallbacks.cpp | 89 +-------------- test-app/runtime/src/main/cpp/ModuleUrl.cpp | 103 ++++++++++++++++++ test-app/runtime/src/main/cpp/ModuleUrl.h | 37 +++++++ 9 files changed, 164 insertions(+), 94 deletions(-) create mode 100644 test-app/runtime/src/main/cpp/ModuleUrl.cpp create mode 100644 test-app/runtime/src/main/cpp/ModuleUrl.h diff --git a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js index e7fe55e1b..c326e6215 100644 --- a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js +++ b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js @@ -536,6 +536,20 @@ describe("HTTP ESM Loader", function () { }); }); + it("keeps the importer's origin as written when the query or fragment is empty", + function (done) { + var written = origin.replace("127.0.0.1", "LOCALHOST"); + importer(written, "authority-empty").then(function (mod) { + return Promise.all([mod.load("./query.mjs?"), mod.load("./hash.mjs#")]); + }).then(function (mods) { + expect(mods[0].url).toBe(written + "/esm/resolve/authority-empty/query.mjs?"); + expect(mods[1].url).toBe(written + "/esm/resolve/authority-empty/hash.mjs"); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + it("normalizes a specifier the way the WHATWG URL parser does", function (done) { importer(origin, "norm").then(function (mod) { return Promise.all([ diff --git a/test-app/runtime/CMakeLists.txt b/test-app/runtime/CMakeLists.txt index d5937c294..a17a37bef 100644 --- a/test-app/runtime/CMakeLists.txt +++ b/test-app/runtime/CMakeLists.txt @@ -243,6 +243,7 @@ add_library( src/main/cpp/ModuleBinding.cpp src/main/cpp/ModuleInternal.cpp src/main/cpp/ModuleInternalCallbacks.cpp + src/main/cpp/ModuleUrl.cpp src/main/cpp/NativeScriptAssert.cpp src/main/cpp/NativeScriptException.cpp src/main/cpp/NativeScriptPlatform.cpp diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index 11d31a1f0..f0cbe3881 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -1813,7 +1813,7 @@ void CallbackHandlers::NewThreadCallback(const v8::FunctionCallbackInfo context, const string& path) { const bool isHttpModule = IsHttpModulePath(path); if (isHttpModule || IsESModule(path)) { if (isHttpModule) { - TNS_DEBUG(Esm, "run-module http-esm begin %s", NormalizeHttpModuleUrl(path).c_str()); + TNS_DEBUG(Esm, "run-module http-esm begin %s", RepairLegacyHttpModuleUrl(path).c_str()); } // The entry runs before this thread's event loop does, so its graph can // only make progress from the pump inside LoadESModule. LoadESModule(isolate, path, BootEntryEvaluationOptions(isHttpModule)); if (isHttpModule) { - TNS_DEBUG(Esm, "run-module http-esm ok %s", NormalizeHttpModuleUrl(path).c_str()); + TNS_DEBUG(Esm, "run-module http-esm ok %s", RepairLegacyHttpModuleUrl(path).c_str()); } return; } @@ -1448,7 +1448,7 @@ Local ModuleInternal::LoadESModule(Isolate* isolate, const std::string& p // dependency. Keying the root by anything else mints a second identity for // one file, so a cycle back to the root would not terminate on its entry. const std::string canonicalPath = CanonicalizeRegistryKey(path); - const std::string requestPath = isHttpModule ? NormalizeHttpModuleUrl(path) : canonicalPath; + const std::string requestPath = isHttpModule ? RepairLegacyHttpModuleUrl(path) : canonicalPath; auto logPhase = [&canonicalPath](const char* phase, const char* status, const char* classification = "", const char* extra = "") { diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index 22767662b..9f502be49 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -21,6 +21,7 @@ #include "HttpLoader.h" #include "JEnv.h" #include "ModuleInternal.h" +#include "ModuleUrl.h" #include "NativeScriptAssert.h" #include "NativeScriptException.h" #include "NativeScriptPlatform.h" @@ -28,7 +29,6 @@ #include "Runtime.h" #include "RuntimeState.h" #include "TraceLog.h" -#include "ada/ada.h" #include "robin_hood.h" using namespace v8; @@ -45,17 +45,6 @@ static inline bool StartsWith(const std::string& s, const char* prefix) { return s.size() >= n && s.compare(0, n, prefix) == 0; } -// Whether `key` is spelled the way the loader keys an HTTP module: a lowercase -// `http://` or `https://` prefix, file modules being keyed by absolute paths. -// Deliberately not a URL parse: it gates the rule that an HTTP importer never -// reaches the filesystem implicitly, so a key the URL parser would reject (an -// IPv6 zone id, say) must still count as HTTP. -static bool IsHttpRegistryKey(const std::string& key) { - if (key.compare(0, 4, "http") != 0) return false; - const size_t schemeEnd = key.size() > 4 && key[4] == 's' ? 5 : 4; - return key.compare(schemeEnd, 3, "://") == 0; -} - static inline bool EndsWith(const std::string& value, const std::string& suffix) { if (suffix.size() > value.size()) return false; return std::equal(suffix.rbegin(), suffix.rend(), value.rbegin()); @@ -594,7 +583,7 @@ std::string CanonicalizeRegistryKey(const std::string& key) { // separator (`http:/host/...`) must key as the URL it routes as, or the // loader registers a module under a key the probes and evictions of the // raw string can never find. - const std::string repaired = NormalizeHttpModuleUrl(key); + const std::string repaired = RepairLegacyHttpModuleUrl(key); if (IsHttpRegistryKey(repaired)) { registryKey = CanonicalizeHttpUrlKey(repaired); classification = "http"; @@ -1066,80 +1055,6 @@ static std::string UnresolvedModuleMessage(const ModuleResolution& resolution) { resolution.attempted + ")"; } -static bool HasHttpScheme(const ada::url_aggregator& url) { - return url.type == ada::scheme::type::HTTP || - url.type == ada::scheme::type::HTTPS; -} - -// The authority (userinfo, host, port) of an absolute or scheme-relative URL -// exactly as written, or empty when `url` does not spell one plainly. -static std::string WrittenAuthority(const std::string& url) { - size_t start = 0; - if (StartsWith(url, "//")) { - start = 2; - } else { - const size_t colon = url.find(':'); - if (colon == std::string::npos || url.compare(colon, 3, "://") != 0) { - return std::string(); - } - start = colon + 3; - } - const size_t end = url.find_first_of("/?#", start); - std::string authority = - url.substr(start, end == std::string::npos ? end : end - start); - for (const char c : authority) { - if (static_cast(c) <= 0x20 || c == '\\') { - return std::string(); - } - } - return authority; -} - -struct ModuleUrl { - bool parsed = false; - bool http = false; // the scheme is http or https - std::string href; -}; - -// `input` parsed with the WHATWG URL parser (the one behind JS `new URL()`): -// as an absolute URL when `base` is empty, otherwise as a path- or -// scheme-relative reference against `base`. -// -// An http(s) result keeps its authority as written by whichever string -// supplied it: tooling compares module URLs against the origin string it was -// configured with, so that spelling is part of a module's identity until every -// loader entry point canonicalizes. The parser's own href is used whenever the -// written authority would not name the same URL. -static ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base) { - ModuleUrl result; - ada::result url; - if (base.empty()) { - url = ada::parse(input, nullptr); - } else { - auto baseUrl = ada::parse(base, nullptr); - if (!baseUrl) return result; - url = ada::parse(input, &baseUrl.value()); - } - if (!url) return result; - result.parsed = true; - result.http = HasHttpScheme(*url); - result.href = std::string(url->get_href()); - if (!result.http) return result; - - const std::string authority = - WrittenAuthority(base.empty() || StartsWith(input, "//") ? input : base); - if (authority.empty()) return result; - const std::string written = std::string(url->get_protocol()) + "//" + authority + - std::string(url->get_pathname()) + - std::string(url->get_search()) + - std::string(url->get_hash()); - auto reparsed = ada::parse(written, nullptr); - if (reparsed && reparsed->get_href() == url->get_href()) { - result.href = written; - } - return result; -} - struct UrlSpecifier { enum class Kind { kHttpUrl, // an http(s) URL diff --git a/test-app/runtime/src/main/cpp/ModuleUrl.cpp b/test-app/runtime/src/main/cpp/ModuleUrl.cpp new file mode 100644 index 000000000..3742e5344 --- /dev/null +++ b/test-app/runtime/src/main/cpp/ModuleUrl.cpp @@ -0,0 +1,103 @@ +#include "ModuleUrl.h" + +#include + +#include "ada/ada.h" + +namespace tns { + +namespace { + +bool StartsWith(const std::string& s, const char* prefix) { + const size_t n = std::char_traits::length(prefix); + return s.size() >= n && s.compare(0, n, prefix) == 0; +} + +bool HasHttpScheme(const ada::url_aggregator& url) { + return url.type == ada::scheme::type::HTTP || + url.type == ada::scheme::type::HTTPS; +} + +// The authority (userinfo, host, port) of an absolute or scheme-relative URL +// exactly as written, or empty when `url` does not spell one plainly. +std::string WrittenAuthority(const std::string& url) { + size_t start = 0; + if (StartsWith(url, "//")) { + start = 2; + } else { + const size_t colon = url.find(':'); + if (colon == std::string::npos || url.compare(colon, 3, "://") != 0) { + return std::string(); + } + start = colon + 3; + } + const size_t end = url.find_first_of("/?#", start); + std::string authority = + url.substr(start, end == std::string::npos ? end : end - start); + for (const char c : authority) { + if (static_cast(c) <= 0x20 || c == '\\') { + return std::string(); + } + } + return authority; +} + +} // namespace + +bool IsHttpRegistryKey(const std::string& key) { + if (key.compare(0, 4, "http") != 0) { + return false; + } + const size_t schemeEnd = key.size() > 4 && key[4] == 's' ? 5 : 4; + return key.compare(schemeEnd, 3, "://") == 0; +} + +ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base) { + ModuleUrl result; + ada::result url; + if (base.empty()) { + url = ada::parse(input, nullptr); + } else { + auto baseUrl = ada::parse(base, nullptr); + if (!baseUrl) { + return result; + } + url = ada::parse(input, &baseUrl.value()); + } + if (!url) { + return result; + } + result.parsed = true; + result.http = HasHttpScheme(*url); + result.href = std::string(url->get_href()); + if (!result.http) { + return result; + } + + const std::string authority = + WrittenAuthority(base.empty() || StartsWith(input, "//") ? input : base); + if (authority.empty()) { + return result; + } + // Everything after the authority comes from the parser's own href: its + // getters drop an empty query's '?' and an empty fragment's '#'. + const std::string_view href = url->get_href(); + const std::string written = + std::string(url->get_protocol()) + "//" + authority + + std::string(href.substr(url->get_components().pathname_start)); + auto reparsed = ada::parse(written, nullptr); + if (reparsed && reparsed->get_href() == href) { + result.href = written; + } + return result; +} + +std::string NormalizeHttpModuleUrl(const std::string& input) { + const ModuleUrl url = ParseModuleUrl(input, std::string()); + if (url.parsed) { + return url.http ? url.href : std::string(); + } + return IsHttpRegistryKey(input) ? input : std::string(); +} + +} // namespace tns diff --git a/test-app/runtime/src/main/cpp/ModuleUrl.h b/test-app/runtime/src/main/cpp/ModuleUrl.h new file mode 100644 index 000000000..eb3ec7c8a --- /dev/null +++ b/test-app/runtime/src/main/cpp/ModuleUrl.h @@ -0,0 +1,37 @@ +#pragma once + +#include + +namespace tns { + +// Whether `key` is spelled the way the loader keys an HTTP module: a lowercase +// `http://` or `https://` prefix, file modules being keyed by absolute paths. +// Deliberately not a URL parse: it gates the rule that an HTTP importer never +// reaches the filesystem implicitly, so a key the URL parser would reject (an +// IPv6 zone id, say) must still count as HTTP. +bool IsHttpRegistryKey(const std::string& key); + +struct ModuleUrl { + bool parsed = false; + bool http = false; // the scheme is http or https + std::string href; +}; + +// `input` parsed with the WHATWG URL parser (the one behind JS `new URL()`): +// as an absolute URL when `base` is empty, otherwise as a path- or +// scheme-relative reference against `base`. +// +// An http(s) result keeps its authority as written by whichever string +// supplied it: tooling compares module URLs against the origin string it was +// configured with, so that spelling is part of a module's identity. The +// parser's own href is used whenever the written authority would not name the +// same URL. +ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base); + +// The spelling the loader gives `input` as an absolute http(s) module URL: +// ParseModuleUrl's href; `input` itself when the parser rejects it but it is +// spelled as an HTTP key (fail closed: it stays HTTP); empty when `input` is +// not an http(s) URL. +std::string NormalizeHttpModuleUrl(const std::string& input); + +} // namespace tns From cc03d32b4558097b671339af32feb9ac85ec2c42 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 1 Dec 2026 22:31:22 -0300 Subject: [PATCH 03/13] fix(runtime): spell every absolute http(s) module URL with the URL parser Every route by which an absolute http(s) URL enters the loader now classifies and spells it with NormalizeHttpModuleUrl: the registry key (CanonicalizeHttpUrlKey and CanonicalizeRegistryKey, hence invalidateModules, import.meta.url and getLoadedModuleUrls), a specifier or import-map target from any importer, the dynamic import()'s HTTP branch, the graph-walk root, the synchronous fallback fetch, LoadESModule roots, the worker entry URL and the require() URL guard. The fetched URL and the registry key derive from the same string. From a file module, HTTP://h/x and http:/h/x are now http URLs as they already were from an HTTP module, dot segments resolve before the fetch, and characters the parser percent-encodes are encoded in the key. The authority keeps its written spelling. An HTTP-prefixed string the parser rejects stays an HTTP URL in its raw spelling. Ports NativeScript/ios@ed556e1c (part of NativeScript/ios#609). --- .../assets/app/tests/testEsmHttpLoader.js | 57 +++++++++++++++++++ .../src/main/assets/app/tests/testNsModule.js | 14 +++++ .../runtime/src/main/cpp/CallbackHandlers.cpp | 8 ++- test-app/runtime/src/main/cpp/HttpLoader.cpp | 5 +- .../runtime/src/main/cpp/ModuleInternal.cpp | 17 ++++-- .../src/main/cpp/ModuleInternalCallbacks.cpp | 24 ++++---- 6 files changed, 105 insertions(+), 20 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js index c326e6215..6240ad24d 100644 --- a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js +++ b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js @@ -1541,6 +1541,63 @@ describe("HTTP ESM Loader", function () { }); }); }); + + describe("absolute http(s) URLs from a file module", function () { + useHttpTimeout(); + + var nsModule = require("ns:module"); + + afterEach(function () { + nsModule.configureLoader({ importMap: { imports: {} } }); + }); + + it("are spelled by the URL parser, keeping the authority as written", function (done) { + var hostport = origin.replace(/^http:\/\//, ""); + var base = origin + "/esm/resolve/file-abs"; + nsModule.configureLoader({ + importMap: { imports: { "ns-file-abs-mapped": base + "/mapped/../mapped.mjs" } }, + }); + Promise.all([ + import("HTTP://" + hostport + "/esm/resolve/file-abs/upper.mjs"), + import("http:/" + hostport + "/esm/resolve/file-abs/collapsed.mjs?k=1"), + import(base + "/sub/../dots.mjs"), + import(base + "/m\u00f6dule.mjs"), + import("ns-file-abs-mapped"), + ]).then(function (mods) { + expect(mods.map(function (m) { return m.url; })).toEqual([ + base + "/upper.mjs", + base + "/collapsed.mjs?k=1", + base + "/dots.mjs", + base + "/m%C3%B6dule.mjs", + base + "/mapped.mjs", + ]); + expect(mods.map(function (m) { return m.path + "?" + m.query; })).toEqual([ + "/esm/resolve/file-abs/upper.mjs?", + "/esm/resolve/file-abs/collapsed.mjs?k=1", + "/esm/resolve/file-abs/dots.mjs?", + "/esm/resolve/file-abs/m%C3%B6dule.mjs?", + "/esm/resolve/file-abs/mapped.mjs?", + ]); + nsModule.invalidateModules(["HTTP://" + hostport + "/esm/resolve/file-abs/upper.mjs"]); + expect(nsModule.getLoadedModuleUrls()).not.toContain(base + "/upper.mjs"); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("are refused by require() whatever their scheme's case", function () { + ["http://h/x.js", "HTTP://h/x.js"].forEach(function (url) { + var message = ""; + try { + require(url); + } catch (e) { + message = String((e && e.message) || e); + } + expect(message).toContain("require() of URL module is not supported: " + url); + }); + }); + }); }); // A bare `@` is not a specifier the runtime knows: it resolves through the diff --git a/test-app/app/src/main/assets/app/tests/testNsModule.js b/test-app/app/src/main/assets/app/tests/testNsModule.js index 1af659732..b870dd8ce 100644 --- a/test-app/app/src/main/assets/app/tests/testNsModule.js +++ b/test-app/app/src/main/assets/app/tests/testNsModule.js @@ -161,6 +161,20 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () { "https://cdn.example.com/lib.js?token=abc"); }); + it("spells a URL the way the URL parser does, authority aside", function () { + checkKey("HTTP://h/x", "http://h/x"); + checkKey("http:h/x", "http://h/x"); + checkKey(" http://h/x", "http://h/x"); + checkKey("http://h", "http://h/"); + checkKey("http://h?x", "http://h/?x"); + checkKey("http://h/a/../b.js", "http://h/b.js"); + checkKey("http://h/%2e%2e/b.js", "http://h/b.js"); + checkKey("http://h\\x\\y.js", "http://h/x/y.js"); + checkKey("http://h/m\u00f6dule.js", "http://h/m%C3%B6dule.js"); + checkKey("http://h/a b.js?q=a b", "http://h/a%20b.js?q=a%20b"); + checkKey("http://H:80/x?", "http://H:80/x?"); + }); + it("keeps the URLs dev tooling emits as written", function () { TOOLING_URLS.forEach(function (row) { checkKey(row[0], row[1]); diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index f0cbe3881..37f6d9485 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -19,6 +19,7 @@ #include #include #include "HttpLoader.h" +#include "ModuleUrl.h" #include "MethodCache.h" #include "ModuleInternal.h" #include "SimpleProfiler.h" @@ -1767,7 +1768,8 @@ void CallbackHandlers::NewThreadCallback(const v8::FunctionCallbackInfo context, const string& path) { const bool isHttpModule = IsHttpModulePath(path); if (isHttpModule || IsESModule(path)) { if (isHttpModule) { - TNS_DEBUG(Esm, "run-module http-esm begin %s", RepairLegacyHttpModuleUrl(path).c_str()); + TNS_DEBUG(Esm, "run-module http-esm begin %s", HttpModuleUrl(path).c_str()); } // The entry runs before this thread's event loop does, so its graph can // only make progress from the pump inside LoadESModule. LoadESModule(isolate, path, BootEntryEvaluationOptions(isHttpModule)); if (isHttpModule) { - TNS_DEBUG(Esm, "run-module http-esm ok %s", RepairLegacyHttpModuleUrl(path).c_str()); + TNS_DEBUG(Esm, "run-module http-esm ok %s", HttpModuleUrl(path).c_str()); } return; } @@ -1448,7 +1453,7 @@ Local ModuleInternal::LoadESModule(Isolate* isolate, const std::string& p // dependency. Keying the root by anything else mints a second identity for // one file, so a cycle back to the root would not terminate on its entry. const std::string canonicalPath = CanonicalizeRegistryKey(path); - const std::string requestPath = isHttpModule ? RepairLegacyHttpModuleUrl(path) : canonicalPath; + const std::string requestPath = isHttpModule ? HttpModuleUrl(path) : canonicalPath; auto logPhase = [&canonicalPath](const char* phase, const char* status, const char* classification = "", const char* extra = "") { diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index 9f502be49..de36b1627 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -584,7 +584,7 @@ std::string CanonicalizeRegistryKey(const std::string& key) { // loader registers a module under a key the probes and evictions of the // raw string can never find. const std::string repaired = RepairLegacyHttpModuleUrl(key); - if (IsHttpRegistryKey(repaired)) { + if (!NormalizeHttpModuleUrl(repaired).empty()) { registryKey = CanonicalizeHttpUrlKey(repaired); classification = "http"; } else if (StartsWith(key, "file://")) { @@ -618,12 +618,15 @@ std::string CanonicalizeRegistryKey(const std::string& key) { v8::MaybeLocal LoadHttpModuleForUrl(v8::Isolate* isolate, v8::Local context, - const std::string& requestedUrl) { + const std::string& requestedUrlArg) { auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) { return v8::MaybeLocal(); } auto& registry = moduleState->registry; + const std::string normalizedUrl = NormalizeHttpModuleUrl(requestedUrlArg); + const std::string& requestedUrl = + normalizedUrl.empty() ? requestedUrlArg : normalizedUrl; const std::string registryKey = CanonicalizeHttpUrlKey(requestedUrl); TNS_DEBUG(Esm, "[http-esm][load][begin] request=%s key=%s", @@ -1213,9 +1216,10 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, } } - if (IsHttpRegistryKey(spec)) { + const std::string httpUrl = NormalizeHttpModuleUrl(spec); + if (!httpUrl.empty()) { result.kind = ModuleResolution::Kind::kHttp; - result.url = spec; + result.url = httpUrl; return result; } @@ -1754,9 +1758,10 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, static ModuleResolution ResolutionForRoot(const std::string& root) { ModuleResolution resolution; resolution.specifier = root; - if (IsHttpRegistryKey(root)) { + const std::string httpUrl = NormalizeHttpModuleUrl(root); + if (!httpUrl.empty()) { resolution.kind = ModuleResolution::Kind::kHttp; - resolution.url = root; + resolution.url = httpUrl; } else if (IsFile(root)) { resolution.kind = ModuleResolution::Kind::kFile; resolution.path = root; @@ -2614,9 +2619,8 @@ v8::MaybeLocal ImportModuleDynamicallyCallback( TNS_DEBUG(Esm, "[dyn-import][import-map] rewrite: %s -> %s", rawSpec.c_str(), normalizedSpec.c_str()); } - // A relative or root-absolute specifier from a served referrer resolves to - // a URL the specifier itself never spells out. Routing on that URL keeps - // such an import() on the async fetch path with its absolute-URL siblings. + // Whatever resolves to an http(s) URL continues as the URL the resolver + // spelled, through the HTTP path. if (dynamicResolution.kind == ModuleResolution::Kind::kHttp && !dynamicResolution.url.empty() && dynamicResolution.url != normalizedSpec) { @@ -3009,7 +3013,7 @@ v8::MaybeLocal ImportModuleDynamicallyCallback( // ── HTTP(S) fast path ── // Security: HttpFetchModule gates remote module access centrally. - if (!normalizedSpec.empty() && IsHttpRegistryKey(normalizedSpec)) { + if (dynamicResolution.kind == ModuleResolution::Kind::kHttp) { TNS_DEBUG(Esm, "[dyn-import][http-loader] trying URL %s", normalizedSpec.c_str()); std::string key = CanonicalizeHttpUrlKey(normalizedSpec); From e949b3c7ec8c739a6d19ebf940d30af74beb25ce Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 1 Dec 2026 22:35:52 -0300 Subject: [PATCH 04/13] fix(runtime): drop the legacy module URL forms Nothing feeds the loader a file://http(s):// wrapper, a collapsed http:/ scheme or a URL embedded in a joined path any more, so the wrapper unwrap in CanonicalizeHttpUrlKey, the string repair HttpLoader exported for IsHttpModulePath, CanonicalizeRegistryKey and the worker entry, the resolver's collapsed-specifier repair and HttpUrlEmbeddedInPath all go. A collapsed http:/host still keys as http://host because the URL parser reads it that way; a wrapped file://http://... is a file: URL that names no file, so import() of it rejects without fetching. The fixture server counts the requests it receives per target and reports them at /esm/request-stats.json, so a spec can prove nothing was fetched. Ports NativeScript/ios@28850ec1 (part of NativeScript/ios#609). --- .../assets/app/tests/testEsmHttpLoader.js | 39 ++++++++++++++++ .../src/main/assets/app/tests/testNsModule.js | 15 ++++++ .../java/com/tns/tests/ModuleTestServer.java | 28 +++++++++++ .../runtime/src/main/cpp/CallbackHandlers.cpp | 2 +- test-app/runtime/src/main/cpp/HttpLoader.cpp | 32 ++----------- test-app/runtime/src/main/cpp/HttpLoader.h | 11 +---- .../runtime/src/main/cpp/ModuleInternal.cpp | 13 ++---- .../src/main/cpp/ModuleInternalCallbacks.cpp | 46 ++----------------- 8 files changed, 97 insertions(+), 89 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js index 6240ad24d..0ad5bf18f 100644 --- a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js +++ b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js @@ -3,6 +3,9 @@ // platforms. var appRoot = __dirname.replace(/\/tests$/, ""); var origin = "http://127.0.0.1:" + com.tns.tests.ModuleTestServer.ensureStarted(); +// The stats route is imported as a JSON module, so each query needs its own +// URL or the registry answers with the first count. +var requestStatsQueries = 0; describe("HTTP ESM Loader", function () { @@ -536,6 +539,25 @@ describe("HTTP ESM Loader", function () { }); }); + it("rejects an import() whose import-map target resolves to nothing", function (done) { + nsModule.configureLoader({ + importMap: { + imports: { + "ns-tail-a": "ns-tail-b", + "ns-tail-b": "~/esm/query-map/literal.mjs", + }, + }, + }); + importer(origin, "tail").then(function (mod) { + return rejectionMessage(mod.load("ns-tail-a")); + }).then(function (message) { + expect(message).toContain("Cannot find module 'ns-tail-b'"); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + it("keeps the importer's origin as written when the query or fragment is empty", function (done) { var written = origin.replace("127.0.0.1", "LOCALHOST"); @@ -1586,6 +1608,23 @@ describe("HTTP ESM Loader", function () { }); }); + it("are not unwrapped from a file:// URL", function (done) { + var target = "/esm/resolve/file-abs/wrapped.mjs"; + import("file://" + origin + target).then(function () { + expect("resolved").toBe("rejected"); + }, function (error) { + expect(String((error && error.message) || error)).toContain("Cannot find module"); + }).then(function () { + return import(origin + "/esm/request-stats.json?target=" + + encodeURIComponent(target) + "&n=" + (++requestStatsQueries)); + }).then(function (stats) { + expect(stats.default.count).toBe(0); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + it("are refused by require() whatever their scheme's case", function () { ["http://h/x.js", "HTTP://h/x.js"].forEach(function (url) { var message = ""; diff --git a/test-app/app/src/main/assets/app/tests/testNsModule.js b/test-app/app/src/main/assets/app/tests/testNsModule.js index b870dd8ce..11ce9fd3f 100644 --- a/test-app/app/src/main/assets/app/tests/testNsModule.js +++ b/test-app/app/src/main/assets/app/tests/testNsModule.js @@ -161,6 +161,21 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () { "https://cdn.example.com/lib.js?token=abc"); }); + // The URL parser reads `http:/host` as `http://host`, so a key that + // arrives collapsed, through invalidateModules say, lands on the same + // identity the resolver produces. + it("repairs a collapsed scheme to one identity", function () { + checkKey("http:/h/ns/core", "http://h/ns/core"); + checkKey("https:/h/ns/core", "https://h/ns/core"); + checkKey("http://h/ns/core", "http://h/ns/core"); + }); + + it("does not read an http URL inside a file:// URL as an http key", function () { + checkKey("file://http:/h/ns/core", "file://http:/h/ns/core"); + checkKey("file://https:/h/ns/core", "file://https:/h/ns/core"); + checkKey("file://http://h/ns/core", "file://http://h/ns/core"); + }); + it("spells a URL the way the URL parser does, authority aside", function () { checkKey("HTTP://h/x", "http://h/x"); checkKey("http:h/x", "http://h/x"); diff --git a/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java b/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java index 4bc76fa93..1ec93e6c7 100644 --- a/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java +++ b/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java @@ -10,7 +10,9 @@ import java.net.URLDecoder; import java.nio.charset.Charset; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; /** * Loopback HTTP/1.1 fixture server for the in-app Jasmine suite. Mirrors the @@ -25,6 +27,10 @@ public final class ModuleTestServer { private static Thread acceptThread; private static int boundPort = -1; private static final List workers = new ArrayList(); + // Requests received per target (path plus query), readable back through + // /esm/request-stats.json so a spec can prove how often a module was + // fetched, or that it never was. + private static final Map requestCounts = new HashMap(); private ModuleTestServer() { } @@ -146,6 +152,28 @@ private static void handle(Socket socket) throws IOException { } private static void route(Socket socket, String path, String query) throws IOException { + if (path.startsWith("/esm/") && !"/esm/request-stats.json".equals(path)) { + String target = query.isEmpty() ? path : path + "?" + query; + synchronized (requestCounts) { + Integer count = requestCounts.get(target); + requestCounts.put(target, count == null ? 1 : count + 1); + } + } + + if ("/esm/request-stats.json".equals(path)) { + // `target` is the percent-encoded request target to count. + String raw = param(query, "target="); + String wanted = raw == null ? "" : URLDecoder.decode(raw, "UTF-8"); + int count; + synchronized (requestCounts) { + Integer c = requestCounts.get(wanted); + count = c == null ? 0 : c; + } + String body = "{\"target\":\"" + jsStringLiteral(wanted) + "\",\"count\":" + count + "}"; + respond(socket, "200 OK", "application/json; charset=utf-8", body.getBytes(UTF8)); + return; + } + if ("/esm/query.mjs".equals(path) || "/ns/m/query.mjs".equals(path)) { String body = "export const path = \"" + jsStringLiteral(path) + "\";\n" + "export const query = \"" + jsStringLiteral(query) + "\";\n" diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index 37f6d9485..e73f16b21 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -1815,7 +1815,7 @@ void CallbackHandlers::NewThreadCallback(const v8::FunctionCallbackInfo context, const string& path) { const bool isHttpModule = IsHttpModulePath(path); if (isHttpModule || IsESModule(path)) { if (isHttpModule) { - TNS_DEBUG(Esm, "run-module http-esm begin %s", HttpModuleUrl(path).c_str()); + TNS_DEBUG(Esm, "run-module http-esm begin %s", NormalizeHttpModuleUrl(path).c_str()); } // The entry runs before this thread's event loop does, so its graph can // only make progress from the pump inside LoadESModule. LoadESModule(isolate, path, BootEntryEvaluationOptions(isHttpModule)); if (isHttpModule) { - TNS_DEBUG(Esm, "run-module http-esm ok %s", HttpModuleUrl(path).c_str()); + TNS_DEBUG(Esm, "run-module http-esm ok %s", NormalizeHttpModuleUrl(path).c_str()); } return; } @@ -1453,7 +1448,7 @@ Local ModuleInternal::LoadESModule(Isolate* isolate, const std::string& p // dependency. Keying the root by anything else mints a second identity for // one file, so a cycle back to the root would not terminate on its entry. const std::string canonicalPath = CanonicalizeRegistryKey(path); - const std::string requestPath = isHttpModule ? HttpModuleUrl(path) : canonicalPath; + const std::string requestPath = isHttpModule ? NormalizeHttpModuleUrl(path) : canonicalPath; auto logPhase = [&canonicalPath](const char* phase, const char* status, const char* classification = "", const char* extra = "") { diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index de36b1627..889f3c503 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -579,13 +579,11 @@ std::string CanonicalizeRegistryKey(const std::string& key) { const char* classification = "path"; bool traceEvenWithoutChange = false; - // Repair-first, exactly like IsHttpModulePath: a collapsed scheme - // separator (`http:/host/...`) must key as the URL it routes as, or the - // loader registers a module under a key the probes and evictions of the - // raw string can never find. - const std::string repaired = RepairLegacyHttpModuleUrl(key); - if (!NormalizeHttpModuleUrl(repaired).empty()) { - registryKey = CanonicalizeHttpUrlKey(repaired); + // Before any other scheme test: an http(s) URL in a spelling other than the + // key's (`HTTP://`, `http:/host`) must not fall through as a custom scheme + // and give the module a second identity. + if (!NormalizeHttpModuleUrl(key).empty()) { + registryKey = CanonicalizeHttpUrlKey(key); classification = "http"; } else if (StartsWith(key, "file://")) { registryKey = NormalizePath(FileURLToPath(key)); @@ -1094,24 +1092,6 @@ static std::string BlockedFromHttpMessage(const std::string& rawSpec, referrerKey + ": " + reason; } -// Rebuild an HTTP URL a path join swallowed ('/app/http:/host/x' → -// 'http://host/x'), or empty when the path embeds none. -static std::string HttpUrlEmbeddedInPath(const std::string& p) { - size_t pos1 = p.find("/http:/"); - size_t pos2 = p.find("/https:/"); - size_t pos = std::min(pos1 == std::string::npos ? SIZE_MAX : pos1, - pos2 == std::string::npos ? SIZE_MAX : pos2); - if (pos == SIZE_MAX) return ""; - std::string tail = p.substr(pos + 1); - if (StartsWith(tail, "http:/") && !StartsWith(tail, "http://")) { - tail.insert(5, "/"); - } else if (StartsWith(tail, "https:/") && !StartsWith(tail, "https://")) { - tail.insert(6, "/"); - } - if (!IsHttpRegistryKey(tail)) return ""; - return tail; -} - // `referrerKey` is the registry key of the importing module — empty when the // importer is unknown (a dynamic import with no compiled referrer). static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, @@ -1136,13 +1116,6 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, } std::string spec = rawSpec; - // Repair 'http:/host' (single slash) left by upstream path joins, so the URL - // takes the HTTP path instead of becoming '/app/http:/host'. - if (spec.rfind("http:/", 0) == 0 && spec.rfind("http://", 0) != 0) { - spec.insert(5, "/"); - } else if (spec.rfind("https:/", 0) == 0 && spec.rfind("https://", 0) != 0) { - spec.insert(6, "/"); - } TNS_DEBUG(Esm, "[resolver][spec] %s", spec.c_str()); @@ -1339,15 +1312,6 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, for (const std::string& baseCandidate : candidateBases) { absPath = baseCandidate; - std::string embedded = HttpUrlEmbeddedInPath(absPath); - if (!embedded.empty()) { - TNS_DEBUG(Esm, "[resolver][http-embedded] %s -> %s", absPath.c_str(), - embedded.c_str()); - result.kind = ModuleResolution::Kind::kHttp; - result.url = embedded; - return result; - } - if (IsFile(absPath)) { found = true; break; From 4b9de5a6a6379268619e47e882d2ceea7277926d Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 1 Dec 2026 22:35:52 -0300 Subject: [PATCH 05/13] docs: how the loader spells absolute http(s) module URLs Ports NativeScript/ios@77d79bb1 (part of NativeScript/ios#609). --- docs/ns-builtin-modules.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index d7424de29..e7acb73ff 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -579,7 +579,13 @@ Inside either section — labelled `imports` or `scope ''`: #### Registry canonicalization -The registry keys modules by a canonical URL. The mechanism — fragment strip, +The registry keys modules by a canonical URL. Before the vocabulary applies, +an absolute http(s) URL is spelled by the WHATWG URL parser with its authority +as written, whichever way it arrives — a specifier from any importer, an +import-map target, or `invalidateModules` — so `HTTP://host/a/../x.js` and +`http:/host/x.js` key as `http://host/x.js`. A `file://http://…` string is not +an http(s) URL: it keys as itself, and `import()` of it fails with +`Cannot find module` without fetching anything. The mechanism — fragment strip, cache-buster param drop, param sort — is the runtime's; the *vocabulary* is server policy, supplied here: From e7f3411b8763c242d573d181a0ce54d0697cccb8 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 1 Dec 2026 22:36:50 -0300 Subject: [PATCH 06/13] fix(runtime): spell remote-module allowlist entries like the URLs they gate The allowlist compares fetched URLs, which the loader now spells with the URL parser (dot segments resolved, characters such as non-ASCII percent-encoded). Each security.remoteModuleAllowlist entry is spelled the same way once, when the allowlist is loaded, with the written authority kept; an entry that is not an http(s) URL stays verbatim. The prefix-and-boundary rule is unchanged. The rule is factored into RemoteUrlMatchesAllowlist, which IsRemoteUrlAllowed applies, and debuggable builds expose it on ns:module as remoteUrlMatchesAllowlist(url, entries) so it can be tested; release builds omit the member. Ports NativeScript/ios@e79bf93d (part of NativeScript/ios#609). --- docs/ns-builtin-modules.md | 7 +- .../src/main/assets/app/tests/testNsModule.js | 2 +- .../app/tests/testRemoteModuleSecurity.js | 94 +++++++++++++++++++ test-app/runtime/src/main/cpp/HttpLoader.cpp | 25 +++-- test-app/runtime/src/main/cpp/HttpLoader.h | 12 +++ .../src/main/cpp/ModuleInternalCallbacks.cpp | 46 +++++++++ .../src/main/cpp/ModuleInternalCallbacks.h | 2 + test-app/runtime/src/main/cpp/js/ns-module.js | 6 +- 8 files changed, 182 insertions(+), 12 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index e7acb73ff..ad4899561 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -506,8 +506,11 @@ works; adding them is a change to this specification first. Debug builds additionally carry `canonicalizeHttpUrlKey(url)`, a pure test diagnostic that takes a string and throws -`canonicalizeHttpUrlKey expects a URL string` otherwise; release builds omit -it. Missing members are simply absent — never +`canonicalizeHttpUrlKey expects a URL string` otherwise, and +`remoteUrlMatchesAllowlist(url, entries)`, which applies the release +`security.remoteModuleAllowlist` rule to `url` against `entries` and throws +`remoteUrlMatchesAllowlist expects a URL string and an array of strings` +otherwise; release builds omit both. Missing members are simply absent — never present-but-throwing — so feature checks work. The module is registered in every build: the security boundary for remote module loading sits at the network layer (`security.allowRemoteModules` in nativescript.config, enforced diff --git a/test-app/app/src/main/assets/app/tests/testNsModule.js b/test-app/app/src/main/assets/app/tests/testNsModule.js index 11ce9fd3f..7172f7048 100644 --- a/test-app/app/src/main/assets/app/tests/testNsModule.js +++ b/test-app/app/src/main/assets/app/tests/testNsModule.js @@ -16,7 +16,7 @@ describe("ns:module", function () { var expected = ["configureLoader", "createPumpingRequire", "createRequire", "getLoadedModuleUrls", "invalidateModules"]; if (typeof nsModule.canonicalizeHttpUrlKey === "function") { - expected.push("canonicalizeHttpUrlKey"); + expected.push("canonicalizeHttpUrlKey", "remoteUrlMatchesAllowlist"); } expect(Object.keys(nsModule).sort()).toEqual(expected.sort()); }); diff --git a/test-app/app/src/main/assets/app/tests/testRemoteModuleSecurity.js b/test-app/app/src/main/assets/app/tests/testRemoteModuleSecurity.js index a53474d9b..4eb221794 100644 --- a/test-app/app/src/main/assets/app/tests/testRemoteModuleSecurity.js +++ b/test-app/app/src/main/assets/app/tests/testRemoteModuleSecurity.js @@ -180,4 +180,98 @@ describe("Remote Module Security", function() { }); }); }); + + // The release allowlist rule, through the debug-only diagnostic that runs + // it: debug builds never gate a fetch on it. + describe("Allowlist rule (ns:module remoteUrlMatchesAllowlist)", function() { + function matches(url, entries) { + var fn = require("ns:module").remoteUrlMatchesAllowlist; + if (typeof fn !== "function") { + pending("ns:module.remoteUrlMatchesAllowlist not exposed (release build)"); + return undefined; + } + return fn(url, entries); + } + + function expectRows(entry, rows) { + rows.forEach(function (row) { + var actual = matches(row[0], [entry]); + if (actual === undefined) { + return; + } + expect(entry + " vs " + row[0] + ": " + actual).toBe(entry + " vs " + row[0] + ": " + row[1]); + }); + } + + it("matches a plain entry by prefix at a component boundary", function() { + expectRows("https://cdn.example", [ + ["https://cdn.example/x.js", true], + ["https://cdn.example", true], + ["https://cdn.example.evil/x.js", false], + ["https://cdn.example@evil/x.js", false], + ["https://cdn.example:9999/x.js", false], + ]); + }); + + it("keeps a path-scoped entry from being escaped by dot segments", function() { + expectRows("https://cdn.example/modules/", [ + ["https://cdn.example/modules/x.js", true], + ["https://cdn.example/modules/../../x.js", false], + ["https://cdn.example/modules/%2e%2e/x.js", false], + ["https://cdn.example/other/../modules/x.js", true], + ]); + }); + + it("treats an entry with and without a trailing slash by the boundary rule", function() { + expectRows("https://cdn.example/modules", [ + ["https://cdn.example/modules/x.js", true], + ["https://cdn.example/modules?v=1", true], + ["https://cdn.example/modulesx/y.js", false], + ]); + expectRows("https://cdn.example/modules/", [ + ["https://cdn.example/modules", false], + ["https://cdn.example/modulesx/y.js", false], + ]); + }); + + it("compares the host as written", function() { + expectRows("https://CDN.example/modules/", [ + ["https://CDN.example/modules/x.js", true], + ["https://cdn.example/modules/x.js", false], + ]); + expectRows("HTTPS://cdn.example/modules/", [ + ["https://cdn.example/modules/x.js", true], + ]); + }); + + it("spells an entry's path the way fetched URLs are spelled", function() { + expectRows("https://cdn.example/m\u00f6dule/", [ + ["https://cdn.example/m\u00f6dule/x.js", true], + ["https://cdn.example/m%C3%B6dule/x.js", true], + ]); + }); + + it("keeps an entry that is not a parseable http(s) URL verbatim", function() { + expectRows("https://[fe80::1%25en0]/", [ + ["https://[fe80::1%25en0]/x.js", true], + ]); + expectRows("cdn.example/", [ + ["https://cdn.example/x.js", false], + ]); + }); + + it("rejects arguments that are not a URL string and an array of strings", function() { + var fn = require("ns:module").remoteUrlMatchesAllowlist; + if (typeof fn !== "function") { + pending("ns:module.remoteUrlMatchesAllowlist not exposed (release build)"); + return; + } + [[], ["https://h/x.js"], ["https://h/x.js", "https://h/"], [1, []], + ["https://h/x.js", [1]]].forEach(function (args) { + expect(function () { fn.apply(null, args); }) + .toThrowError(TypeError, + "remoteUrlMatchesAllowlist expects a URL string and an array of strings"); + }); + }); + }); }); diff --git a/test-app/runtime/src/main/cpp/HttpLoader.cpp b/test-app/runtime/src/main/cpp/HttpLoader.cpp index 255d1a2eb..427c8ef2b 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.cpp +++ b/test-app/runtime/src/main/cpp/HttpLoader.cpp @@ -51,6 +51,20 @@ static bool RemoteUrlMatchesAllowlistEntry(const std::string& url, const std::st return next == '/' || next == '?' || next == '#'; } +std::string NormalizeRemoteModuleAllowlistEntry(const std::string& entry) { + const std::string url = NormalizeHttpModuleUrl(entry); + return url.empty() ? entry : url; +} + +bool RemoteUrlMatchesAllowlist(const std::string& url, const std::vector& entries) { + for (const std::string& entry : entries) { + if (RemoteUrlMatchesAllowlistEntry(url, entry)) { + return true; + } + } + return false; +} + static void InitializeSecurityConfig() { std::call_once(s_securityConfigInitFlag, []() { try { @@ -91,7 +105,8 @@ static void InitializeSecurityConfig() { if (jstr != nullptr) { const char* str = env.GetStringUTFChars(jstr, nullptr); if (str != nullptr) { - s_remoteModuleAllowlist.emplace_back(str); + s_remoteModuleAllowlist.push_back( + NormalizeRemoteModuleAllowlistEntry(str)); env.ReleaseStringUTFChars(jstr, str); } env.DeleteLocalRef(jstr); @@ -133,13 +148,7 @@ bool IsRemoteUrlAllowed(const std::string& url) { return true; } - for (const std::string& entry : s_remoteModuleAllowlist) { - if (RemoteUrlMatchesAllowlistEntry(url, entry)) { - return true; - } - } - - return false; + return RemoteUrlMatchesAllowlist(url, s_remoteModuleAllowlist); } // ───────────────────────────────────────────────────────────── diff --git a/test-app/runtime/src/main/cpp/HttpLoader.h b/test-app/runtime/src/main/cpp/HttpLoader.h index 70e3955c8..332a4da1c 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.h +++ b/test-app/runtime/src/main/cpp/HttpLoader.h @@ -145,6 +145,18 @@ bool IsRemoteModulesAllowed(); // (or all URLs if the allowlist is empty). bool IsRemoteUrlAllowed(const std::string& url); +// An allowlist entry spelled the way the loader spells the URLs it fetches +// (NormalizeHttpModuleUrl), so path-scoped entries compare against resolved +// paths; an entry that is not an http(s) URL is kept verbatim. Applied once, +// when the allowlist is loaded. +std::string NormalizeRemoteModuleAllowlistEntry(const std::string& entry); + +// The allowlist rule IsRemoteUrlAllowed applies: `url`, as fetched, matches +// one of `entries` (each already normalized) by prefix, the match ending at a +// URL-component boundary. +bool RemoteUrlMatchesAllowlist(const std::string& url, + const std::vector& entries); + // Mirrors com.tns.Runtime.isDebuggable(), cached once via the security // config init. Fail-safe false until initialized. bool IsDebuggable(); diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index 889f3c503..490b9be0d 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -3791,6 +3791,52 @@ bool BuildNsModuleBinding(v8::Local context, v8::Local return false; } } + + // The release allowlist rule, which debug builds never apply to + // fetches. `url` is spelled as the loader spells the URL it fetches + // and `entries` as the allowlist is loaded. + auto allowlistCb = [](const v8::FunctionCallbackInfo& info) { + v8::Isolate* iso = info.GetIsolate(); + v8::Local ctx = iso->GetCurrentContext(); + std::vector entries; + bool valid = info.Length() >= 2 && info[0]->IsString() && info[1]->IsArray(); + if (valid) { + v8::Local list = info[1].As(); + for (uint32_t i = 0; valid && i < list->Length(); i++) { + v8::Local item; + if (!list->Get(ctx, i).ToLocal(&item)) { + return; // the element getter threw + } + valid = item->IsString(); + if (valid) { + entries.push_back(NormalizeRemoteModuleAllowlistEntry( + ArgConverter::ToString(iso, item))); + } + } + } + if (!valid) { + iso->ThrowException(v8::Exception::TypeError(ToV8String( + iso, + "remoteUrlMatchesAllowlist expects a URL string and an array of strings"))); + return; + } + const std::string raw = ArgConverter::ToString(iso, info[0]); + const std::string url = NormalizeHttpModuleUrl(raw); + info.GetReturnValue().Set( + RemoteUrlMatchesAllowlist(url.empty() ? raw : url, entries)); + }; + v8::Local allowlistFn; + if (!v8::Function::New(context, allowlistCb).ToLocal(&allowlistFn)) { + return false; + } + allowlistFn->SetName(ToV8String(isolate, "remoteUrlMatchesAllowlist")); + if (!binding + ->CreateDataProperty(context, + ToV8String(isolate, "remoteUrlMatchesAllowlist"), + allowlistFn) + .FromMaybe(false)) { + return false; + } } return true; diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h index 34752d848..a1871f7d6 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h @@ -269,6 +269,8 @@ void SetCanonicalizationConfig(CanonicalizationConfig config); // - getLoadedModuleUrls() (registry introspection) // - createRequire(path) (a CommonJS require for `path`) // - canonicalizeHttpUrlKey(url) (debug builds only; test diagnostic) +// - remoteUrlMatchesAllowlist(url, entries) +// (debug builds only; test diagnostic) // // Worker teardown across HMR cycles is userland: the dev client intercepts // the global `Worker` constructor and terminates tracked instances diff --git a/test-app/runtime/src/main/cpp/js/ns-module.js b/test-app/runtime/src/main/cpp/js/ns-module.js index 4059a7c10..9d57e30ea 100644 --- a/test-app/runtime/src/main/cpp/js/ns-module.js +++ b/test-app/runtime/src/main/cpp/js/ns-module.js @@ -6,7 +6,8 @@ // and freezes the exports. // // Membership varies by build: -// - `canonicalizeHttpUrlKey` exists only in debug builds (test diagnostic). +// - `canonicalizeHttpUrlKey` and `remoteUrlMatchesAllowlist` exist only in +// debug builds (test diagnostics). // Missing members are simply absent — never present-but-throwing — so // feature checks work. @@ -179,5 +180,8 @@ const surface = { if (binding.canonicalizeHttpUrlKey !== undefined) { surface.canonicalizeHttpUrlKey = binding.canonicalizeHttpUrlKey; } +if (binding.remoteUrlMatchesAllowlist !== undefined) { + surface.remoteUrlMatchesAllowlist = binding.remoteUrlMatchesAllowlist; +} module.exports = ObjectFreeze(surface); From 6779e8ee039e28c73e458c67e7c52934af9b94bb Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 1 Dec 2026 22:39:59 -0300 Subject: [PATCH 07/13] fix(runtime): spell http(s) import-map scope keys like the referrer keys they match A scope key matches the importing module's registry key by plain prefix, and http(s) registry keys are spelled by the URL parser, so a scope written with dot segments or a non-ASCII segment matched nothing. An http(s) scope key is now spelled the same way when the map is installed, ending in '/' exactly when it was written so; other scope keys (app paths) and imports keys stay as written. Ports NativeScript/ios@0d282683 (part of NativeScript/ios#609). --- docs/ns-builtin-modules.md | 5 +++- .../assets/app/tests/testEsmHttpLoader.js | 28 +++++++++++++++++++ .../src/main/cpp/ModuleInternalCallbacks.cpp | 17 ++++++++++- 3 files changed, 48 insertions(+), 2 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index ad4899561..f6d1f7c6f 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -544,7 +544,10 @@ A **scope key is matched as a plain prefix of the importing module's canonical registry key** — an absolute `http(s)` URL for a served module, or a canonical absolute path for a file on disk. That key is this runtime's analogue of the web's resolved referrer URL, which is what scope prefixes match in a browser. -End a scope key with `/` to keep it on a directory boundary. Resolution +An `http(s)` scope key is spelled the way registry keys are (see +[Registry canonicalization](#registry-canonicalization)) when the map is +installed, ending in `/` exactly when it is written so. End a scope key with +`/` to keep it on a directory boundary. Resolution consults the most specific matching scope first (longest prefix wins), then progressively less specific ones, then `imports` — so a scope can override a global mapping for one subtree and fall through to it everywhere else. The diff --git a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js index 0ad5bf18f..25f7f2d10 100644 --- a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js +++ b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js @@ -539,6 +539,34 @@ describe("HTTP ESM Loader", function () { }); }); + it("matches an http(s) scope the way the URL parser spells it", function (done) { + var base = origin + "/esm/resolve/scope-norm"; + var scopes = {}; + scopes[base + "/x/../dots/"] = { "ns-scope-norm": base + "/target.mjs?k=dots" }; + scopes[base + "/m\u00f6dir/"] = { "ns-scope-norm": base + "/target.mjs?k=nonascii" }; + // No trailing slash: still a plain prefix, here inside a segment. + scopes[base + "/pla"] = { "ns-scope-norm": base + "/target.mjs?k=plain" }; + scopes[origin] = { "ns-scope-norm-origin": base + "/target.mjs?k=origin" }; + nsModule.configureLoader({ importMap: { imports: {}, scopes: scopes } }); + function load(dir, spec) { + return importer(origin, "scope-norm/" + dir).then(function (mod) { + return mod.load(spec); + }); + } + Promise.all([ + load("dots", "ns-scope-norm"), + load("m\u00f6dir", "ns-scope-norm"), + load("plain", "ns-scope-norm"), + load("dots", "ns-scope-norm-origin"), + ]).then(function (mods) { + expect(mods.map(function (m) { return m.query; })) + .toEqual(["k=dots", "k=nonascii", "k=plain", "k=origin"]); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + it("rejects an import() whose import-map target resolves to nothing", function (done) { nsModule.configureLoader({ importMap: { diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index 490b9be0d..030f2f65a 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -757,6 +757,21 @@ static bool ParseImportMapEntries(v8::Isolate* isolate, v8::Local c return true; } +// A scope key matches referrer registry keys by plain prefix, and an http(s) +// referrer key is spelled by NormalizeHttpModuleUrl, so an http(s) scope key +// is spelled the same way. Whether it ends in '/' stays as written: the parser +// gives a path-less URL the path "/", which would narrow the prefix. +static std::string ImportMapScopePrefix(const std::string& scopeKey) { + std::string prefix = NormalizeHttpModuleUrl(scopeKey); + if (prefix.empty()) { + return scopeKey; + } + if (scopeKey.back() != '/' && prefix.back() == '/') { + prefix.pop_back(); + } + return prefix; +} + // Parse without touching the live map. On any failure `error` explains what is // wrong and `out` is meaningless — the caller keeps whatever it already had. // V8's JSON parser stands in for iOS's NSJSONSerialization: escapes, nesting @@ -862,7 +877,7 @@ static bool ParseImportMap(v8::Isolate* isolate, const std::string& json, "scope '" + scopePrefix + "'", &entries, error)) { return false; } - out->scopes.emplace_back(scopePrefix, std::move(entries)); + out->scopes.emplace_back(ImportMapScopePrefix(scopePrefix), std::move(entries)); } } From 85cbf8658c481b0d1740247531ccc8b13ebb88f4 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 1 Dec 2026 22:40:15 -0300 Subject: [PATCH 08/13] perf(runtime): spell each module URL once per key NormalizeHttpModuleUrl rejects a string that cannot be an http(s) URL from its first character instead of attempting a parse, so file paths pay nothing for it. ParseModuleUrl returns the parser's href unchanged when the written authority already matches it, skipping the rebuild and its re-parse. CanonicalizeHttpUrlKey splits into the spelling step and CanonicalizeNormalizedHttpUrlKey, which applies the vocabulary to an already spelled URL. CanonicalizeRegistryKey, the graph walk (enqueue, fetch completion, root), the dynamic-import HTTP branch, LoadESModule and LoadHttpModuleForUrl, whose callers pass resolved URLs, spell a URL at most once. Ports NativeScript/ios@02e939dd (part of NativeScript/ios#609). --- .../src/main/assets/app/tests/testNsModule.js | 2 ++ test-app/runtime/src/main/cpp/HttpLoader.cpp | 7 +++-- test-app/runtime/src/main/cpp/HttpLoader.h | 3 ++ .../runtime/src/main/cpp/ModuleInternal.cpp | 8 +++-- .../src/main/cpp/ModuleInternalCallbacks.cpp | 31 ++++++++++--------- .../src/main/cpp/ModuleInternalCallbacks.h | 2 ++ test-app/runtime/src/main/cpp/ModuleUrl.cpp | 24 +++++++++++--- 7 files changed, 52 insertions(+), 25 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testNsModule.js b/test-app/app/src/main/assets/app/tests/testNsModule.js index 7172f7048..e74d98be2 100644 --- a/test-app/app/src/main/assets/app/tests/testNsModule.js +++ b/test-app/app/src/main/assets/app/tests/testNsModule.js @@ -180,6 +180,8 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () { checkKey("HTTP://h/x", "http://h/x"); checkKey("http:h/x", "http://h/x"); checkKey(" http://h/x", "http://h/x"); + checkKey("\t\n HTTPS://h/x", "https://h/x"); + checkKey("h\tttp://h/x", "http://h/x"); checkKey("http://h", "http://h/"); checkKey("http://h?x", "http://h/?x"); checkKey("http://h/a/../b.js", "http://h/b.js"); diff --git a/test-app/runtime/src/main/cpp/HttpLoader.cpp b/test-app/runtime/src/main/cpp/HttpLoader.cpp index 427c8ef2b..bdd9b87e9 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.cpp +++ b/test-app/runtime/src/main/cpp/HttpLoader.cpp @@ -156,9 +156,10 @@ bool IsRemoteUrlAllowed(const std::string& url) { std::string CanonicalizeHttpUrlKey(const std::string& url) { const std::string normalizedUrl = NormalizeHttpModuleUrl(url); - if (normalizedUrl.empty()) { - return url; - } + return normalizedUrl.empty() ? url : CanonicalizeNormalizedHttpUrlKey(normalizedUrl); +} + +std::string CanonicalizeNormalizedHttpUrlKey(const std::string& normalizedUrl) { size_t hashPos = normalizedUrl.find('#'); std::string noHash = (hashPos == std::string::npos) ? normalizedUrl : normalizedUrl.substr(0, hashPos); diff --git a/test-app/runtime/src/main/cpp/HttpLoader.h b/test-app/runtime/src/main/cpp/HttpLoader.h index 332a4da1c..4d55a8f50 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.h +++ b/test-app/runtime/src/main/cpp/HttpLoader.h @@ -56,6 +56,9 @@ struct CanonicalizationConfig { // module under exactly one URL and never varies it for freshness. std::string CanonicalizeHttpUrlKey(const std::string& url); +// CanonicalizeHttpUrlKey for a URL already spelled by NormalizeHttpModuleUrl. +std::string CanonicalizeNormalizedHttpUrlKey(const std::string& normalizedUrl); + // What a module response turned out to be. Decided once, by the shared // classifier, for whichever transport produced the response. enum class ModuleResponseKind { diff --git a/test-app/runtime/src/main/cpp/ModuleInternal.cpp b/test-app/runtime/src/main/cpp/ModuleInternal.cpp index 38a3e2e88..8a21e4566 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternal.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternal.cpp @@ -1443,12 +1443,14 @@ EntryEvaluationState ModuleInternal::PollEntryEvaluation(Isolate* isolate, const Local ModuleInternal::LoadESModule(Isolate* isolate, const std::string& path, const ModuleEvaluationOptions& options) { auto context = isolate->GetCurrentContext(); - const bool isHttpModule = IsHttpModulePath(path); + const std::string httpUrl = NormalizeHttpModuleUrl(path); + const bool isHttpModule = !httpUrl.empty(); // The key the resolver would derive for this same module as someone's // dependency. Keying the root by anything else mints a second identity for // one file, so a cycle back to the root would not terminate on its entry. - const std::string canonicalPath = CanonicalizeRegistryKey(path); - const std::string requestPath = isHttpModule ? NormalizeHttpModuleUrl(path) : canonicalPath; + const std::string canonicalPath = isHttpModule ? CanonicalizeNormalizedHttpUrlKey(httpUrl) + : CanonicalizeRegistryKey(path); + const std::string requestPath = isHttpModule ? httpUrl : canonicalPath; auto logPhase = [&canonicalPath](const char* phase, const char* status, const char* classification = "", const char* extra = "") { diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index 030f2f65a..2a5fab285 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -582,8 +582,9 @@ std::string CanonicalizeRegistryKey(const std::string& key) { // Before any other scheme test: an http(s) URL in a spelling other than the // key's (`HTTP://`, `http:/host`) must not fall through as a custom scheme // and give the module a second identity. - if (!NormalizeHttpModuleUrl(key).empty()) { - registryKey = CanonicalizeHttpUrlKey(key); + const std::string httpUrl = NormalizeHttpModuleUrl(key); + if (!httpUrl.empty()) { + registryKey = CanonicalizeNormalizedHttpUrlKey(httpUrl); classification = "http"; } else if (StartsWith(key, "file://")) { registryKey = NormalizePath(FileURLToPath(key)); @@ -616,16 +617,13 @@ std::string CanonicalizeRegistryKey(const std::string& key) { v8::MaybeLocal LoadHttpModuleForUrl(v8::Isolate* isolate, v8::Local context, - const std::string& requestedUrlArg) { + const std::string& requestedUrl) { auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) { return v8::MaybeLocal(); } auto& registry = moduleState->registry; - const std::string normalizedUrl = NormalizeHttpModuleUrl(requestedUrlArg); - const std::string& requestedUrl = - normalizedUrl.empty() ? requestedUrlArg : normalizedUrl; - const std::string registryKey = CanonicalizeHttpUrlKey(requestedUrl); + const std::string registryKey = CanonicalizeNormalizedHttpUrlKey(requestedUrl); TNS_DEBUG(Esm, "[http-esm][load][begin] request=%s key=%s", requestedUrl.c_str(), registryKey.c_str()); @@ -1550,7 +1548,7 @@ static void AsyncGraphOnFetchCompleted( load->pendingFetches--; - const std::string key = CanonicalizeRegistryKey(url); + const std::string key = CanonicalizeNormalizedHttpUrlKey(url); const bool isRoot = (key == load->rootKey); if (!load->failed) { @@ -1666,10 +1664,11 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, const ModuleResolution& resolution) { const bool isHttp = resolution.kind == ModuleResolution::Kind::kHttp; const std::string& target = isHttp ? resolution.url : resolution.path; - // One keying function for both schemes: it dispatches to the HTTP canonical - // key for URLs and to the normalized path otherwise, so the walk registers - // every module under the exact key the resolver will look up. - const std::string key = CanonicalizeRegistryKey(target); + // The keys CanonicalizeRegistryKey gives these targets, so the walk registers + // every module under the exact key the resolver will look up; a resolved + // URL is already spelled, so only its vocabulary is applied. + const std::string key = + isHttp ? CanonicalizeNormalizedHttpUrlKey(target) : CanonicalizeRegistryKey(target); if (!load->visited.insert(key).second) return; v8::Isolate* isolate = load->isolate; @@ -1756,10 +1755,13 @@ void StartModuleGraphLoad( std::function context)> onComplete) { + const ModuleResolution rootResolution = ResolutionForRoot(root); auto load = std::make_shared(); load->isolate = isolate; load->context.Reset(isolate, context); - load->rootKey = CanonicalizeRegistryKey(root); + load->rootKey = rootResolution.kind == ModuleResolution::Kind::kHttp + ? CanonicalizeNormalizedHttpUrlKey(rootResolution.url) + : CanonicalizeRegistryKey(root); load->startUs = MonotonicUs(); load->onComplete = std::move(onComplete); @@ -1770,7 +1772,6 @@ void StartModuleGraphLoad( TNS_DEBUG(Esm, "[graph][start] root=%s key=%s", root.c_str(), load->rootKey.c_str()); - const ModuleResolution rootResolution = ResolutionForRoot(root); if (rootResolution.kind != ModuleResolution::Kind::kUnresolved) { AsyncGraphEnqueue(load, rootResolution); } @@ -2995,7 +2996,7 @@ v8::MaybeLocal ImportModuleDynamicallyCallback( if (dynamicResolution.kind == ModuleResolution::Kind::kHttp) { TNS_DEBUG(Esm, "[dyn-import][http-loader] trying URL %s", normalizedSpec.c_str()); - std::string key = CanonicalizeHttpUrlKey(normalizedSpec); + std::string key = CanonicalizeNormalizedHttpUrlKey(normalizedSpec); // Volatile-pattern eviction: if the URL matches any configured volatile // pattern, evict the cached module so we always re-fetch. Policy is diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h index a1871f7d6..cdb869fdc 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h @@ -124,6 +124,8 @@ v8::MaybeLocal GetOrCreateRequireFacade( // Authoritative HTTP URL loader for dev-served ESM. This compiles and // registers the module under its canonical URL key without evaluating it. +// `requestedUrl` must be spelled by NormalizeHttpModuleUrl: it is fetched as is +// and its key derives from it without spelling it again. // Returns empty with a V8 exception scheduled on `isolate` — the fetch // classifier's reason, or the compile error — so a caller that is not a V8 // resolve callback must consume it through its own TryCatch and route the text diff --git a/test-app/runtime/src/main/cpp/ModuleUrl.cpp b/test-app/runtime/src/main/cpp/ModuleUrl.cpp index 3742e5344..e805ced58 100644 --- a/test-app/runtime/src/main/cpp/ModuleUrl.cpp +++ b/test-app/runtime/src/main/cpp/ModuleUrl.cpp @@ -79,12 +79,18 @@ ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base) { if (authority.empty()) { return result; } + const std::string_view href = url->get_href(); + const size_t authorityStart = url->get_protocol().size() + 2; + const size_t pathnameStart = url->get_components().pathname_start; + if (href.substr(authorityStart, pathnameStart - authorityStart) == + authority) { + return result; + } // Everything after the authority comes from the parser's own href: its // getters drop an empty query's '?' and an empty fragment's '#'. - const std::string_view href = url->get_href(); - const std::string written = - std::string(url->get_protocol()) + "//" + authority + - std::string(href.substr(url->get_components().pathname_start)); + const std::string written = std::string(url->get_protocol()) + "//" + + authority + + std::string(href.substr(pathnameStart)); auto reparsed = ada::parse(written, nullptr); if (reparsed && reparsed->get_href() == href) { result.href = written; @@ -93,6 +99,16 @@ ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base) { } std::string NormalizeHttpModuleUrl(const std::string& input) { + // Fast reject only: the parser drops leading C0 controls and spaces, after + // which an http(s) URL (or an HTTP key) starts with 'h' or 'H'. + size_t first = 0; + while (first < input.size() && + static_cast(input[first]) <= 0x20) { + first++; + } + if (first == input.size() || (input[first] != 'h' && input[first] != 'H')) { + return std::string(); + } const ModuleUrl url = ParseModuleUrl(input, std::string()); if (url.parsed) { return url.http ? url.href : std::string(); From 5072791892b9e062b5a0f035a6b59202aa9f937e Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 1 Dec 2026 22:41:04 -0300 Subject: [PATCH 09/13] refactor(runtime): build the URL a module is reported under in one place Script origins of classic scripts, file ES modules and JSON modules, import.meta.url and the worker inspector URL each built their own file:// URL from a path. ReportedModuleUrl in ModuleUrl now does it for all of them: an http(s) URL in the loader's spelling, tested first so a string the loader reads as an http(s) URL is never prefixed with file://; any other string that carries a scheme unchanged; otherwise file:// plus the absolute path (file:///app/ when empty). The outputs are unchanged except the worker inspector URL, which for an http(s) script is now the normalized URL and for any other scheme-carrying script is the script string itself rather than a file:// prefix glued onto it. The docs no longer describe the file://http... string, which is not a form the loader accepts. Ports NativeScript/ios@e6b5bf02 and NativeScript/ios@b684e7bb (part of NativeScript/ios#609). Android reports file URLs with the absolute path, so there is no base-directory stripping. --- docs/ns-builtin-modules.md | 4 +- .../runtime/src/main/cpp/ModuleInternal.cpp | 4 +- .../src/main/cpp/ModuleInternalCallbacks.cpp | 33 ++--------------- test-app/runtime/src/main/cpp/ModuleUrl.cpp | 37 +++++++++++++++++++ test-app/runtime/src/main/cpp/ModuleUrl.h | 12 ++++++ .../runtime/src/main/cpp/WorkerWrapper.cpp | 8 ++-- 6 files changed, 58 insertions(+), 40 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index f6d1f7c6f..f95933cb3 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -589,9 +589,7 @@ The registry keys modules by a canonical URL. Before the vocabulary applies, an absolute http(s) URL is spelled by the WHATWG URL parser with its authority as written, whichever way it arrives — a specifier from any importer, an import-map target, or `invalidateModules` — so `HTTP://host/a/../x.js` and -`http:/host/x.js` key as `http://host/x.js`. A `file://http://…` string is not -an http(s) URL: it keys as itself, and `import()` of it fails with -`Cannot find module` without fetching anything. The mechanism — fragment strip, +`http:/host/x.js` key as `http://host/x.js`. The mechanism — fragment strip, cache-buster param drop, param sort — is the runtime's; the *vocabulary* is server policy, supplied here: diff --git a/test-app/runtime/src/main/cpp/ModuleInternal.cpp b/test-app/runtime/src/main/cpp/ModuleInternal.cpp index 8a21e4566..bb17511a7 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternal.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternal.cpp @@ -985,7 +985,7 @@ Local