diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 5b99a1e6..df1e4fd0 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -33,6 +33,7 @@ #include "NsBuiltinModules.h" #include "Runtime.h" // for GetAppConfigValue #include "RuntimeConfig.h" +#include "ada/ada.h" // Do NOT pull all v8 symbols into namespace here; String would clash with // other typedefs inside the NativeScript codebase. We refer to v8 symbols @@ -1534,8 +1535,131 @@ static void DrainStreamedCompilesForIsolate(v8::Isolate* isolate) { std::string path; // kFile std::string specifier; // the specifier after import-map rewriting std::string attempted; // kUnresolved: the last candidate tried + // kUnresolved: non-empty when a rule forbids the specifier outright. It is + // the complete error message, and nothing was probed on disk for it. + std::string blocked; }; +static std::string UnresolvedModuleMessage(const ModuleResolution& resolution) { + if (!resolution.blocked.empty()) { + return resolution.blocked; + } + return "Cannot find module '" + resolution.specifier + "' (tried " + 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 + kOtherUrl, // an absolute URL with another scheme + kInvalid, // a relative form that does not parse against the base + kBare, // neither relative nor an absolute URL + }; + Kind kind = Kind::kBare; + std::string href; // kHttpUrl, kOtherUrl +}; + +// HTML "resolve a module specifier", import map aside, against an importer +// whose URL is `baseUrl`. Only '/', './' and '../' prefixes are relative +// ('//host/x' is a '/' form); '.x', '.' and '..' are bare. +static UrlSpecifier ResolveModuleSpecifierAgainstUrl(const std::string& spec, + const std::string& baseUrl) { + UrlSpecifier result; + const bool relative = StartsWith(spec, "/") || StartsWith(spec, "./") || StartsWith(spec, "../"); + const ModuleUrl url = ParseModuleUrl(spec, relative ? baseUrl : std::string()); + result.href = url.href; + if (!url.parsed) { + result.kind = relative ? UrlSpecifier::Kind::kInvalid : UrlSpecifier::Kind::kBare; + } else { + result.kind = url.http ? UrlSpecifier::Kind::kHttpUrl : UrlSpecifier::Kind::kOtherUrl; + } + return result; +} + +static std::string BlockedFromHttpMessage(const std::string& rawSpec, + const std::string& referrerKey, const char* reason) { + return "Cannot resolve module specifier \"" + rawSpec + "\" imported from " + referrerKey + ": " + + reason; +} + static bool IsRegularFile(const std::string& p) { std::string normalized = NormalizePath(p); struct stat st; @@ -1595,15 +1719,17 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, // specifiers must map every form it emits — keys are matched literally. const LoaderVocabulary* vocabulary = VocabularyForCurrentIsolate(); const bool hasImportMap = vocabulary != nullptr && !vocabulary->importMap.empty(); + bool mappedByImportMap = false; if (hasImportMap) { std::string mapped = LookupImportMap(spec, referrerKey); if (!mapped.empty()) { TNS_DEBUG(Esm, "[resolver][import-map] rewrite: %s -> %s", spec.c_str(), mapped.c_str()); spec = mapped; + mappedByImportMap = true; } else if (tns::LogCategoryEnabled(tns::LogCategory::Esm)) { - // A bare-looking specifier the map didn't match is about to fall back to - // filesystem resolution and almost certainly fail; surface the missing - // entry before the more cryptic `Cannot find module` follow-on. + // A bare-looking specifier the map didn't match either falls back to + // filesystem resolution and almost certainly fails, or — from an HTTP + // importer — is refused; surface the missing entry before that error. bool looksBare = spec[0] != '/' && spec[0] != '.' && spec.find("://") == std::string::npos && spec.find('\\') == std::string::npos; if (looksBare) { @@ -1627,6 +1753,48 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, result.specifier = spec; + // An HTTP importer resolves the way a browser does and reaches the + // filesystem only explicitly: through an import-map entry (whatever its + // target, handled below) or a file:// URL. Every other form is refused + // here, before anything is probed on disk. + const bool referrerIsHttp = + StartsWith(referrerKey, "http://") || StartsWith(referrerKey, "https://"); + if (referrerIsHttp && !mappedByImportMap) { + const UrlSpecifier url = ResolveModuleSpecifierAgainstUrl(spec, referrerKey); + switch (url.kind) { + case UrlSpecifier::Kind::kHttpUrl: + TNS_DEBUG(Esm, "[resolver][http-importer] base=%s spec=%s -> %s", referrerKey.c_str(), + spec.c_str(), url.href.c_str()); + result.kind = ModuleResolution::Kind::kHttp; + result.url = url.href; + return result; + case UrlSpecifier::Kind::kInvalid: + result.blocked = BlockedFromHttpMessage( + rawSpec, referrerKey, "it does not form an http(s) URL against the importer's URL."); + return result; + case UrlSpecifier::Kind::kBare: + if (spec[0] == '~') { + result.blocked = BlockedFromHttpMessage( + rawSpec, referrerKey, + "app-relative \"~/\" paths are not available to modules loaded over HTTP (use a " + "file:// URL, an import-map entry, or createRequire)."); + } else { + result.blocked = BlockedFromHttpMessage( + rawSpec, referrerKey, + "it is not in the import map (bare specifiers from an HTTP module must be " + "mapped)."); + } + return result; + case UrlSpecifier::Kind::kOtherUrl: + if (StartsWith(spec, "file://")) { + break; + } + // Not a file (blob:, data:, …); import() serves blob: itself. + result.attempted = spec; + return result; + } + } + if (StartsWith(spec, "http://") || StartsWith(spec, "https://")) { result.kind = ModuleResolution::Kind::kHttp; result.url = spec; @@ -1647,32 +1815,15 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, baseDir = RuntimeConfig.ApplicationPath + "/"; } - // A referrer fetched over HTTP makes its relative and root-absolute imports - // HTTP too, the way a browser resolves them. - const bool referrerIsHttp = - StartsWith(referrerKey, "http://") || StartsWith(referrerKey, "https://"); + // An HTTP importer's relative or root-absolute import-map target resolves + // against the importer's URL. if (referrerIsHttp && (specIsRelative || specIsRootAbs)) { - std::string resolvedHttp; - @autoreleasepool { - NSString* baseStr = [NSString stringWithUTF8String:referrerKey.c_str()]; - NSString* specStr = [NSString stringWithUTF8String:spec.c_str()]; - if (baseStr && specStr) { - NSURL* baseURL = [NSURL URLWithString:baseStr]; - NSURL* rel = [NSURL URLWithString:specStr relativeToURL:baseURL]; - NSURL* absURL = [rel absoluteURL]; - if (absURL) { - NSString* absStr = [absURL absoluteString]; - if (absStr) { - resolvedHttp = std::string([absStr UTF8String] ?: ""); - } - } - } - } - if (StartsWith(resolvedHttp, "http://") || StartsWith(resolvedHttp, "https://")) { + const ModuleUrl resolved = ParseModuleUrl(spec, referrerKey); + if (resolved.http) { TNS_DEBUG(Esm, "[resolver][http-rel] base=%s spec=%s -> %s", referrerKey.c_str(), - spec.c_str(), resolvedHttp.c_str()); + spec.c_str(), resolved.href.c_str()); result.kind = ModuleResolution::Kind::kHttp; - result.url = resolvedHttp; + result.url = resolved.href; return result; } } @@ -1841,11 +1992,12 @@ static void AsyncGraphWalkModuleRequests(const std::shared_ptr& continue; } // Builtins are served by the resolver from the builtin registry, and an - // unresolved specifier (typically a bare name with no import-map entry) - // stays on the resolver's lazy path — where it either resolves later or - // fails with the resolver's own message. An unmapped bare specifier's - // subtree is therefore not discovered here; any HTTP edge inside it is - // pathological and lands on the synchronous anomaly guard. + // unresolved specifier (typically a bare name with no import-map entry, + // or one an HTTP importer may not use) stays on the resolver's lazy path — + // where it either resolves later or fails with the resolver's own + // message. An unmapped bare specifier's subtree is therefore not + // discovered here; any HTTP edge inside it is pathological and lands on + // the synchronous anomaly guard. const ModuleResolution resolution = ResolveSpecifierToPath(*specUtf8, moduleKey); if (resolution.kind == ModuleResolution::Kind::kBuiltin || resolution.kind == ModuleResolution::Kind::kUnresolved) { @@ -2717,9 +2869,8 @@ static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate, case ModuleResolution::Kind::kUnresolved: { // Surfaced as an exception rather than left to ReadModule(), which would // abort the process trying to open a directory. - std::string msg = - "Cannot find module '" + resolution.specifier + "' (tried " + resolution.attempted + ")"; - isolate->ThrowException(v8::Exception::Error(tns::ToV8String(isolate, msg))); + isolate->ThrowException( + v8::Exception::Error(tns::ToV8String(isolate, UnresolvedModuleMessage(resolution)))); return v8::MaybeLocal(); } case ModuleResolution::Kind::kFile: @@ -2940,8 +3091,6 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local } } } - // Normalize spec: only strip ?query/hash for non-HTTP specs so SFC HTTP keys keep - // version tags std::string rawSpec = cSpec ? std::string(cSpec) : std::string(); // Builtin modules never reach the loader below; the namespace comes straight @@ -2969,21 +3118,6 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local } std::string normalizedSpec = rawSpec; - // remove query/hash ONLY for non-HTTP specs - bool isHttpLike = (!normalizedSpec.empty() && (StartsWith(normalizedSpec, "http://") || - StartsWith(normalizedSpec, "https://"))); - if (!isHttpLike) { - size_t qpos = normalizedSpec.find_first_of("?#"); - if (qpos != std::string::npos) { - normalizedSpec = normalizedSpec.substr(0, qpos); - } - } - if (normalizedSpec != rawSpec) { - // Rebuild V8 string only if changed - specifier = tns::ToV8String(isolate, normalizedSpec.c_str()); - specStr = [NSString stringWithUTF8String:normalizedSpec.c_str()]; - TNS_DEBUG(Esm, "[dyn-import][normalize] %s -> %s", rawSpec.c_str(), normalizedSpec.c_str()); - } v8::EscapableHandleScope scope(isolate); // Create a Promise resolver we'll resolve/reject synchronously for now. @@ -3009,21 +3143,55 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local // a local module — while scopes are matched against the registry key, an // absolute app path. Canonicalizing the origin alone stops at `/app/…` // and matches no scope, so the origin goes through the same resolution - // the registry keys by first. + // the registry keys by first. An HTTP module's origin is its URL + // already, and an identity: it must not go through the import map. const std::string resourceName(*resourceUtf8); - const ModuleResolution referrer = ResolveSpecifierToPath(resourceName, std::string()); - if (referrer.kind == ModuleResolution::Kind::kFile) { - dynamicReferrerKey = CanonicalizeRegistryKey(referrer.path); - } else if (referrer.kind == ModuleResolution::Kind::kHttp) { - dynamicReferrerKey = CanonicalizeRegistryKey(referrer.url); + const std::string resourceUrl = RepairCollapsedUrlScheme(resourceName); + const auto parsedResource = ada::parse(resourceUrl, nullptr); + if (parsedResource && HasHttpScheme(*parsedResource)) { + dynamicReferrerKey = CanonicalizeRegistryKey(resourceUrl); } else { - dynamicReferrerKey = CanonicalizeRegistryKey(resourceName); + const ModuleResolution referrer = ResolveSpecifierToPath(resourceName, std::string()); + if (referrer.kind == ModuleResolution::Kind::kFile) { + dynamicReferrerKey = CanonicalizeRegistryKey(referrer.path); + } else if (referrer.kind == ModuleResolution::Kind::kHttp) { + dynamicReferrerKey = CanonicalizeRegistryKey(referrer.url); + } else { + dynamicReferrerKey = CanonicalizeRegistryKey(resourceName); + } } } } + const bool importerIsHttp = + StartsWith(dynamicReferrerKey, "http://") || StartsWith(dynamicReferrerKey, "https://"); + + // A file importer's query/fragment never names part of a file, so it is + // dropped up front; an absolute http(s) specifier keeps it as identity. For + // an HTTP importer the seam resolves the specifier as a URL, query included. + const bool isHttpLike = + StartsWith(normalizedSpec, "http://") || StartsWith(normalizedSpec, "https://"); + if (!isHttpLike && !importerIsHttp) { + size_t qpos = normalizedSpec.find_first_of("?#"); + if (qpos != std::string::npos) { + normalizedSpec = normalizedSpec.substr(0, qpos); + } + } + if (normalizedSpec != rawSpec) { + specifier = tns::ToV8String(isolate, normalizedSpec.c_str()); + specStr = [NSString stringWithUTF8String:normalizedSpec.c_str()]; + TNS_DEBUG(Esm, "[dyn-import][normalize] %s -> %s", rawSpec.c_str(), normalizedSpec.c_str()); + } + ModuleResolution dynamicResolution; if (!normalizedSpec.empty()) { dynamicResolution = ResolveSpecifierToPath(normalizedSpec, dynamicReferrerKey); + if (!dynamicResolution.blocked.empty()) { + resolver + ->Reject(context, v8::Exception::Error(tns::ToV8String( + isolate, UnresolvedModuleMessage(dynamicResolution)))) + .FromMaybe(false); + return scope.Escape(resolver->GetPromise()); + } if (!dynamicResolution.specifier.empty() && dynamicResolution.specifier != normalizedSpec) { normalizedSpec = dynamicResolution.specifier; specifier = tns::ToV8String(isolate, normalizedSpec.c_str()); @@ -3031,6 +3199,15 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local TNS_DEBUG(Esm, "[dyn-import][import-map] rewrite: %s -> %s", rawSpec.c_str(), normalizedSpec.c_str()); } + // An HTTP importer's relative, root-relative and scheme-relative imports + // continue as the absolute URL the seam resolved, through the HTTP path. + if (importerIsHttp && dynamicResolution.kind == ModuleResolution::Kind::kHttp && + dynamicResolution.url != normalizedSpec) { + normalizedSpec = dynamicResolution.url; + specifier = tns::ToV8String(isolate, normalizedSpec.c_str()); + specStr = [NSString stringWithUTF8String:normalizedSpec.c_str()]; + TNS_DEBUG(Esm, "[dyn-import][http-rel] %s -> %s", rawSpec.c_str(), normalizedSpec.c_str()); + } } // Re-use the static resolver to locate / compile the module. @@ -3567,6 +3744,19 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local return scope.Escape(resolver->GetPromise()); } + // The tail below re-resolves with no referrer, which would let an HTTP + // importer's unmapped other-scheme specifier ('data:', 'file:/x') reach + // '/' on disk. Only explicit file:// URLs and import-map + // targets may continue into it. + if (importerIsHttp && dynamicResolution.kind == ModuleResolution::Kind::kUnresolved && + normalizedSpec == rawSpec && !StartsWith(normalizedSpec, "file://")) { + resolver + ->Reject(context, v8::Exception::Error(tns::ToV8String( + isolate, UnresolvedModuleMessage(dynamicResolution)))) + .FromMaybe(false); + return scope.Escape(resolver->GetPromise()); + } + // Attempt to resolve relative specs against the referrer's resource URL if available. // This reduces reliance on app-root fallback and ensures ../ segments are collapsed. v8::Local refMod; diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index d09d702a..c9e2116a 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -1459,6 +1459,541 @@ describe("HTTP ESM Loader", function() { }); }); + // A module served over HTTP resolves specifiers the way a browser does, + // against its own URL, and reaches the filesystem only explicitly. The + // bundled fixtures named by refused specifiers exist, so an implicit + // filesystem fallback would have loaded them. + describe("specifier resolution from an HTTP importer", function () { + var nsModule = require("ns:module"); + + afterEach(function () { + nsModule.configureLoader({ importMap: { imports: {} } }); + }); + + function importer(origin, dir) { + return import(origin + "/esm/resolve/" + dir + "/importer.mjs"); + } + + function expectRefused(promise, done, check) { + promise.then(function () { + expect("resolved").toBe("rejected"); + done(); + }, function (error) { + check(String((error && error.message) || error)); + done(); + }); + } + + it("resolves ./, ../, root- and scheme-relative import() against the importer's URL", + function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var schemeRelative = origin.replace(/^https?:/, "") + "/esm/resolve/rel/scheme.mjs"; + importer(origin, "rel/dir").then(function (mod) { + return Promise.all([ + mod.load("./sibling.mjs"), + mod.load("../parent.mjs"), + mod.load("/esm/resolve/rel/rooted.mjs"), + mod.load(schemeRelative), + ]); + }).then(function (mods) { + expect(mods.map(function (m) { return m.path; })).toEqual([ + "/esm/resolve/rel/dir/sibling.mjs", + "/esm/resolve/rel/parent.mjs", + "/esm/resolve/rel/rooted.mjs", + "/esm/resolve/rel/scheme.mjs", + ]); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("keeps an import()'s query as part of the module's identity", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + importer(origin, "query").then(function (mod) { + return Promise.all([mod.load("./target.mjs?k=1"), mod.load("./target.mjs?k=2")]); + }).then(function (mods) { + expect([mods[0].query, mods[1].query]).toEqual(["k=1", "k=2"]); + expect(mods[0]).not.toBe(mods[1]); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("refuses a static bare import the import map does not cover", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var spec = "tests/esm/http-importer/bare-static.mjs"; + expectRefused( + import(origin + "/esm/resolve/static.mjs?spec=" + encodeURIComponent(spec)), + done, + function (message) { + expect(message).toContain("\"" + spec + "\""); + expect(message).toContain("not in the import map"); + expect(globalThis.__nsHttpImporterDiskRead_bareStatic).toBeUndefined(); + }); + }); + + it("refuses a dynamic bare import the import map does not cover", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var spec = "tests/esm/http-importer/bare-dynamic.mjs"; + expectRefused(importer(origin, "bare").then(function (mod) { + return mod.load(spec); + }), done, function (message) { + expect(message).toContain("\"" + spec + "\""); + expect(message).toContain(origin + "/esm/resolve/bare/importer.mjs"); + expect(message).toContain("not in the import map"); + expect(globalThis.__nsHttpImporterDiskRead_bareDynamic).toBeUndefined(); + }); + }); + + it("refuses an app-relative ~/ import", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var spec = "~/tests/esm/http-importer/tilde.mjs"; + expectRefused(importer(origin, "tilde").then(function (mod) { + return mod.load(spec); + }), done, function (message) { + expect(message).toContain("\"" + spec + "\""); + expect(message).toContain("\"~/\" paths are not available"); + expect(globalThis.__nsHttpImporterDiskRead_tilde).toBeUndefined(); + }); + }); + + // The fixture is written at run time: a colon in a checked-in file + // name cannot be checked out on Windows. + describe("with a module at the app root named like an other-scheme URL", function () { + var spec = "x-ns-test:other-scheme.mjs"; + var fixturePath = NSBundle.mainBundle.resourcePath + "/app/" + spec; + + afterEach(function () { + var fileManager = NSFileManager.defaultManager; + if (fileManager.fileExistsAtPath(fixturePath)) { + fileManager.removeItemAtPathError(fixturePath); + } + }); + + it("refuses the import() instead of reading the app root", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var body = "globalThis.__nsHttpImporterDiskRead_otherScheme = true;\n" + + "export const name = \"other-scheme\";\n"; + var data = NSString.stringWithString(body).dataUsingEncoding(NSUTF8StringEncoding); + var written = NSFileManager.defaultManager + .createFileAtPathContentsAttributes(fixturePath, data, null); + expect(written).toBe(true); + expect(NSFileManager.defaultManager.fileExistsAtPath(fixturePath)).toBe(true); + expectRefused(importer(origin, "other-scheme").then(function (mod) { + return mod.load(spec); + }), done, function (message) { + expect(message).toContain(spec); + expect(globalThis.__nsHttpImporterDiskRead_otherScheme).toBeUndefined(); + }); + }); + }); + + it("imports a builtin", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + importer(origin, "builtin").then(function (mod) { + return mod.load("ns:module"); + }).then(function (ns) { + expect(ns.createRequire).toBe(nsModule.createRequire); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("imports a bundled module named by an explicit file:// URL", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + importer(origin, "file-url").then(function (mod) { + return mod.load("file:///app/tests/esm/http-importer/file-url.mjs"); + }).then(function (ns) { + expect(ns.name).toBe("file-url"); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("imports a bare specifier through its import-map entry, whatever the target", + function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + nsModule.configureLoader({ + importMap: { + imports: { "ns-http-importer-mapped": "~/tests/esm/http-importer/mapped.mjs" }, + }, + }); + importer(origin, "mapped").then(function (mod) { + return mod.load("ns-http-importer-mapped"); + }).then(function (ns) { + expect(ns.name).toBe("mapped"); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("resolves a relative import-map target against the importer's URL", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + nsModule.configureLoader({ + importMap: { imports: { "ns-http-importer-relative": "./mapped-target.mjs?k=map" } }, + }); + Promise.all([ + importer(origin, "map-relative").then(function (mod) { + return mod.load("ns-http-importer-relative"); + }), + import(origin + "/esm/resolve/static.mjs?spec=ns-http-importer-relative"), + ]).then(function (namespaces) { + expect([namespaces[0].path, namespaces[0].query]) + .toEqual(["/esm/resolve/map-relative/mapped-target.mjs", "k=map"]); + expect([namespaces[1].dep.path, namespaces[1].dep.query]) + .toEqual(["/esm/resolve/mapped-target.mjs", "k=map"]); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("imports a blob:nativescript URL", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + // The bare test realm has no Blob; createObjectURL needs an + // instance carrying `type`, and the loader only calls `.text()`. + var previousBlob = globalThis.Blob; + globalThis.Blob = function Blob(parts, options) { + this._text = (parts || []).join(""); + this.type = (options && options.type) || ""; + }; + globalThis.Blob.prototype.text = function () { + return Promise.resolve(this._text); + }; + var url = URL.createObjectURL( + new Blob(["export const name = 'http-importer-blob';\n"], + { type: "text/javascript" }), + { ext: ".mjs" }); + function cleanUp() { + URL.revokeObjectURL(url); + if (typeof previousBlob === "undefined") { + delete globalThis.Blob; + } else { + globalThis.Blob = previousBlob; + } + } + importer(origin, "blob").then(function (mod) { + return mod.load(url); + }).then(function (ns) { + cleanUp(); + expect(ns.name).toBe("http-importer-blob"); + done(); + }).catch(function (error) { + cleanUp(); + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + function rejectionMessage(promise) { + return promise.then(function () { + return "resolved"; + }, function (error) { + return String((error && error.message) || error); + }); + } + + it("stays an HTTP importer when the import map maps its own URL to a file", + function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var importerUrl = origin + "/esm/resolve/self-mapped/importer.mjs"; + var mod; + import(importerUrl).then(function (loaded) { + mod = loaded; + var imports = {}; + imports[importerUrl] = "~/tests/esm/http-importer/self-mapped.mjs"; + nsModule.configureLoader({ importMap: { imports: imports } }); + return mod.load("./target.mjs?k=self"); + }).then(function (target) { + expect([target.path, target.query]) + .toEqual(["/esm/resolve/self-mapped/target.mjs", "k=self"]); + return rejectionMessage(mod.load("tests/esm/http-importer/self-mapped-bare.mjs")); + }).then(function (bareMessage) { + expect(bareMessage).toContain("not in the import map"); + return rejectionMessage(mod.load("~/tests/esm/http-importer/self-mapped-tilde.mjs")); + }).then(function (tildeMessage) { + expect(tildeMessage).toContain("\"~/\" paths are not available"); + expect(globalThis.__nsHttpImporterDiskRead_selfMappedBare).toBeUndefined(); + expect(globalThis.__nsHttpImporterDiskRead_selfMappedTilde).toBeUndefined(); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("refuses a static import of a dot-prefixed bare specifier", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var spec = ".hidden/dep.mjs"; + expectRefused( + import(origin + "/esm/resolve/static.mjs?spec=" + encodeURIComponent(spec)), + done, + function (message) { + expect(message).toContain("\"" + spec + "\""); + expect(message).toContain("not in the import map"); + }); + }); + + it("refuses a dynamic import of '.x', '.' and '..' as bare specifiers", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + importer(origin, "dot-bare/dir").then(function (mod) { + return Promise.all([".hidden/dynamic.mjs", ".", ".."].map(function (spec) { + return rejectionMessage(mod.load(spec)); + })); + }).then(function (messages) { + messages.forEach(function (message) { + expect(message).toContain("not in the import map"); + }); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + // `new URL()` and the loader share the WHATWG URL parser, so every + // spelling of one URL names one module. + it("imports one module for every spelling of its URL from import()", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var importerUrl = origin + "/esm/resolve/identity/importer.mjs"; + import(importerUrl).then(function (mod) { + return Promise.all([ + mod.load("./x.mjs?v=1"), + mod.load("./sub/../x.mjs?v=1"), + mod.load("/esm/resolve/identity/./x.mjs?v=1"), + import(origin + "/esm/resolve/identity/x.mjs?v=1"), + import(new URL("./x.mjs?v=1", importerUrl).href), + ]); + }).then(function (namespaces) { + expect(namespaces[0].query).toBe("v=1"); + namespaces.forEach(function (ns) { + expect(ns).toBe(namespaces[0]); + }); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("imports one module for every spelling of its URL from a static import", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + function staticImporter(spec) { + return import(origin + "/esm/resolve/static.mjs?spec=" + encodeURIComponent(spec)); + } + Promise.all([ + staticImporter("./identity-static/x.mjs?v=1"), + staticImporter("/esm/resolve/identity-static/./x.mjs?v=1"), + import(origin + "/esm/resolve/identity-static/x.mjs?v=1"), + ]).then(function (namespaces) { + expect(namespaces[2].query).toBe("v=1"); + expect(namespaces[0].dep).toBe(namespaces[2]); + expect(namespaces[1].dep).toBe(namespaces[2]); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + // `LOCALHOST` reaches the same server as the canonical origin but is + // spelled the way the parser would not spell it. + it("keeps the importer's origin as written in the URLs it resolves", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var written = origin.replace("127.0.0.1", "LOCALHOST"); + var childUrl = written + "/esm/resolve/authority/x.mjs"; + var direct; + import(childUrl).then(function (ns) { + direct = ns; + return Promise.all([ + importer(written, "authority").then(function (mod) { + return Promise.all([ + mod.load("./x.mjs"), + mod.load("/esm/resolve/authority/x.mjs"), + ]); + }), + import(written + "/esm/resolve/authority/static.mjs?spec=" + + encodeURIComponent("./x.mjs")), + importer(origin, "authority-own").then(function (mod) { + return Promise.all([ + mod.load(childUrl.replace(/^http:/, "")), + mod.load(childUrl.replace(/^http:/, "HTTP:")), + ]); + }), + ]); + }).then(function (results) { + expect(results[0][0]).toBe(direct); + expect(results[0][1]).toBe(direct); + expect(results[1].dep).toBe(direct); + expect(results[2][0]).toBe(direct); + expect(results[2][1]).toBe(direct); + expect(direct.url).toBe(childUrl); + expect(nsModule.getLoadedModuleUrls()).toContain(childUrl); + nsModule.invalidateModules([childUrl]); + expect(nsModule.getLoadedModuleUrls()).not.toContain(childUrl); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("normalizes a specifier the way the WHATWG URL parser does", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + importer(origin, "norm").then(function (mod) { + return Promise.all([ + mod.load("/esm/resolve/norm/./a/../dots.mjs"), + mod.load("../../../../../esm/resolve/norm/climb.mjs"), + mod.load("./sub\\back.mjs"), + mod.load(origin.replace(/^http:/, "HTTP:") + "/esm/resolve/norm/upper.mjs"), + ]); + }).then(function (mods) { + expect(mods.map(function (m) { return m.path; })).toEqual([ + "/esm/resolve/norm/dots.mjs", + "/esm/resolve/norm/climb.mjs", + "/esm/resolve/norm/sub/back.mjs", + "/esm/resolve/norm/upper.mjs", + ]); + expect(mods[3].url).toBe(origin + "/esm/resolve/norm/upper.mjs"); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + }); + + describe("import-map lookup of a query from a file module", function () { + var nsModule = require("ns:module"); + + afterEach(function () { + nsModule.configureLoader({ importMap: { imports: {} } }); + }); + + it("looks a static import's query up in the map and drops an import()'s", function (done) { + nsModule.configureLoader({ + importMap: { + imports: { + "ns-query-map-pkg": "~/tests/esm/query-map/stripped.mjs", + "ns-query-map-pkg?x": "~/tests/esm/query-map/literal.mjs", + }, + }, + }); + Promise.all([ + import("~/tests/esm/query-map/static-importer.mjs"), + import("ns-query-map-pkg?x"), + ]).then(function (namespaces) { + expect(namespaces[0].dep.name).toBe("literal"); + expect(namespaces[1].name).toBe("stripped"); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + }); + describe("URL Key Canonicalization", function () { it("preserves query for non-dev/public URLs", function (done) { var origin = getHostOrigin(); diff --git a/TestRunner/app/tests/esm/http-importer/bare-dynamic.mjs b/TestRunner/app/tests/esm/http-importer/bare-dynamic.mjs new file mode 100644 index 00000000..02d67cde --- /dev/null +++ b/TestRunner/app/tests/esm/http-importer/bare-dynamic.mjs @@ -0,0 +1,2 @@ +globalThis.__nsHttpImporterDiskRead_bareDynamic = true; +export const name = "bare-dynamic"; diff --git a/TestRunner/app/tests/esm/http-importer/bare-static.mjs b/TestRunner/app/tests/esm/http-importer/bare-static.mjs new file mode 100644 index 00000000..ebd447ab --- /dev/null +++ b/TestRunner/app/tests/esm/http-importer/bare-static.mjs @@ -0,0 +1,2 @@ +globalThis.__nsHttpImporterDiskRead_bareStatic = true; +export const name = "bare-static"; diff --git a/TestRunner/app/tests/esm/http-importer/file-url.mjs b/TestRunner/app/tests/esm/http-importer/file-url.mjs new file mode 100644 index 00000000..9db4aa18 --- /dev/null +++ b/TestRunner/app/tests/esm/http-importer/file-url.mjs @@ -0,0 +1 @@ +export const name = "file-url"; diff --git a/TestRunner/app/tests/esm/http-importer/mapped.mjs b/TestRunner/app/tests/esm/http-importer/mapped.mjs new file mode 100644 index 00000000..73908086 --- /dev/null +++ b/TestRunner/app/tests/esm/http-importer/mapped.mjs @@ -0,0 +1 @@ +export const name = "mapped"; diff --git a/TestRunner/app/tests/esm/http-importer/self-mapped-bare.mjs b/TestRunner/app/tests/esm/http-importer/self-mapped-bare.mjs new file mode 100644 index 00000000..990b057f --- /dev/null +++ b/TestRunner/app/tests/esm/http-importer/self-mapped-bare.mjs @@ -0,0 +1,2 @@ +globalThis.__nsHttpImporterDiskRead_selfMappedBare = true; +export const name = "self-mapped-bare"; diff --git a/TestRunner/app/tests/esm/http-importer/self-mapped-tilde.mjs b/TestRunner/app/tests/esm/http-importer/self-mapped-tilde.mjs new file mode 100644 index 00000000..d9c28d9a --- /dev/null +++ b/TestRunner/app/tests/esm/http-importer/self-mapped-tilde.mjs @@ -0,0 +1,2 @@ +globalThis.__nsHttpImporterDiskRead_selfMappedTilde = true; +export const name = "self-mapped-tilde"; diff --git a/TestRunner/app/tests/esm/http-importer/self-mapped.mjs b/TestRunner/app/tests/esm/http-importer/self-mapped.mjs new file mode 100644 index 00000000..d2d45bb7 --- /dev/null +++ b/TestRunner/app/tests/esm/http-importer/self-mapped.mjs @@ -0,0 +1 @@ +export const name = "self-mapped"; diff --git a/TestRunner/app/tests/esm/http-importer/tilde.mjs b/TestRunner/app/tests/esm/http-importer/tilde.mjs new file mode 100644 index 00000000..fbc1c5ca --- /dev/null +++ b/TestRunner/app/tests/esm/http-importer/tilde.mjs @@ -0,0 +1,2 @@ +globalThis.__nsHttpImporterDiskRead_tilde = true; +export const name = "tilde"; diff --git a/TestRunner/app/tests/esm/query-map/literal.mjs b/TestRunner/app/tests/esm/query-map/literal.mjs new file mode 100644 index 00000000..2bf324a3 --- /dev/null +++ b/TestRunner/app/tests/esm/query-map/literal.mjs @@ -0,0 +1 @@ +export const name = "literal"; diff --git a/TestRunner/app/tests/esm/query-map/static-importer.mjs b/TestRunner/app/tests/esm/query-map/static-importer.mjs new file mode 100644 index 00000000..8f41c258 --- /dev/null +++ b/TestRunner/app/tests/esm/query-map/static-importer.mjs @@ -0,0 +1 @@ +export * as dep from "ns-query-map-pkg?x"; diff --git a/TestRunner/app/tests/esm/query-map/stripped.mjs b/TestRunner/app/tests/esm/query-map/stripped.mjs new file mode 100644 index 00000000..9f0af7cd --- /dev/null +++ b/TestRunner/app/tests/esm/query-map/stripped.mjs @@ -0,0 +1 @@ +export const name = "stripped"; diff --git a/TestRunnerTests/TestRunnerTests.swift b/TestRunnerTests/TestRunnerTests.swift index 2cfb2430..079459ae 100644 --- a/TestRunnerTests/TestRunnerTests.swift +++ b/TestRunnerTests/TestRunnerTests.swift @@ -35,6 +35,14 @@ class TestRunnerTests: XCTestCase { let path = (environ["PATH_INFO"] as? String) ?? "/" let query = (environ["QUERY_STRING"] as? String) ?? "" + func jsStringLiteral(_ s: String) -> String { + return s + .replacingOccurrences(of: "\\", with: "\\\\") + .replacingOccurrences(of: "\"", with: "\\\"") + .replacingOccurrences(of: "\n", with: "\\n") + .replacingOccurrences(of: "\r", with: "\\r") + } + // Progress beacon from the in-app Jasmine reporter (fire-and-forget): // records the spec currently running so a hang/timeout can report // where the JS suite stalled, even though no JUnit report is POSTed. @@ -111,13 +119,6 @@ class TestRunnerTests: XCTestCase { } if path == "/esm/query.mjs" || path == "/ns/m/query.mjs" { - func jsStringLiteral(_ s: String) -> String { - return s - .replacingOccurrences(of: "\\", with: "\\\\") - .replacingOccurrences(of: "\"", with: "\\\"") - .replacingOccurrences(of: "\n", with: "\\n") - .replacingOccurrences(of: "\r", with: "\\r") - } let nowMs = Int(Date().timeIntervalSince1970 * 1000.0) let body = """ export const path = \"\(jsStringLiteral(path))\"; @@ -130,6 +131,32 @@ class TestRunnerTests: XCTestCase { return } + // ── Specifier resolution from an HTTP importer ── + // `…/importer.mjs` exports `load(spec)`, an import() issued + // from its own URL; `…/static.mjs` statically imports the + // specifier in its `spec` param; any other path answers with + // the request target it was reached at and its import.meta.url. + if path.hasPrefix("/esm/resolve/") { + let body: String + if path.hasSuffix("/importer.mjs") { + body = "export function load(spec) { return import(spec); }\n" + } else if path.hasSuffix("/static.mjs") { + var spec = "" + if let pair = query.split(separator: "&").first(where: { $0.hasPrefix("spec=") }), + let decoded = String(pair.dropFirst("spec=".count)).removingPercentEncoding { + spec = decoded + } + body = "export * as dep from \"\(jsStringLiteral(spec))\";\n" + } else { + body = "export const path = \"\(jsStringLiteral(path))\";\n" + + "export const query = \"\(jsStringLiteral(query))\";\n" + + "export const url = import.meta.url;\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 b43b2b3e..506776a6 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -944,6 +944,50 @@ unmodified where a shim exists: ## Loading ES modules +### Specifier resolution + +A module loaded over http(s) resolves the specifiers it imports, with `import` +and `import()` alike, as below. `ns:`/`node:` builtins resolve first, and the +[import map](#import-maps-and-scopes) is consulted next; the table covers a +specifier the map does not match. + +| specifier | from an http(s) importer | +|---|---| +| `./x`, `../x` | the importer's URL, query kept | +| `/x` | the importer's origin, query kept | +| `//host/x` | the importer's scheme, query kept | +| `http(s)://…` | that URL | +| `file:///app/x` | the app root, on disk | +| `~/x` | refused | +| bare (`pkg`, `pkg/x`) | refused: it needs an import-map entry | + +Only `/`, `./` and `../` prefixes are relative: `.x`, `.` and `..` are bare +specifiers and are refused without an import-map entry. Specifiers follow the +HTML module-specifier rules: the WHATWG URL parser, the one behind +`new URL()`, decides whether a specifier is relative, an absolute URL or bare, +and produces the path, query and fragment, so dot segments and `\` resolve and +the scheme is lowercased as in a browser. The authority (userinfo, host and +port) keeps its spelling from the importer's URL, or from the specifier when it +names one (`//host/x`, `http(s)://…`). A specifier that resolves to an http(s) +URL therefore names the same module as `new URL(specifier, importerUrl).href` +whenever that authority is already spelled the way `new URL()` spells it (a +lowercase host, no default port). + +An import-map entry is never refused — it is explicit configuration, so it may +point an HTTP module at a `~/` path — though a relative or root-relative target +still resolves against the importer's URL. A specifier with any other URL +scheme (`data:`, `file:/x`) is never looked up on disk, and `import()` of a +`blob:nativescript/…` URL loads from the blob store. A refused specifier fails +before anything is fetched or read from disk, with an `Error` whose message +names the specifier, the importer and what to use instead; +`createRequire()` is the explicit way for an HTTP module to reach +CommonJS or ES modules on disk. + +From a file module, a static `import 'pkg?x'` looks `pkg?x` up in the import +map, while `import('pkg?x')` drops the query and looks up `pkg`. An import-map +target should not itself be a key of the map: `import()` may look a target up +a second time. + ### The `require()` specifier Every `require` — the global one and any minted by `createRequire` / diff --git a/types/ns-module.d.ts b/types/ns-module.d.ts index 348f4485..00f15997 100644 --- a/types/ns-module.d.ts +++ b/types/ns-module.d.ts @@ -6,7 +6,8 @@ declare module "ns:module" { * resolved on demand. * * A key ending in `/` maps a whole subtree and its target must end in `/` - * too; longest match wins. The map is validated in full before it is + * too; longest match wins. A module loaded over `http(s)` can use a bare + * specifier only through this map. The map is validated in full before it is * installed — an invalid map throws a `TypeError` out of * {@link configureLoader} and leaves the previously installed map in place. */