diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 51f41ebe9..8e63a5ea4 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -1111,8 +1111,42 @@ static void KillAsyncGraphLoadsForIsolate(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 + ")"; +} + +// RFC 3986 scheme followed by ':' — a specifier with one is an absolute URL, +// never a bare name. +static bool HasUrlScheme(const std::string& spec) { + if (spec.empty() || !isalpha(static_cast(spec[0]))) { + return false; + } + for (size_t i = 1; i < spec.size(); i++) { + const unsigned char c = static_cast(spec[i]); + if (c == ':') { + return true; + } + if (!isalnum(c) && c != '+' && c != '-' && c != '.') { + return false; + } + } + return false; +} + +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; @@ -1172,15 +1206,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) { @@ -1254,6 +1290,30 @@ static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, } } + // An HTTP importer reaches the filesystem only explicitly: through an + // import-map entry (whatever its target) or a file:// URL. Every other form + // is refused here, before anything is probed on disk. + if (referrerIsHttp && !mappedByImportMap && !StartsWith(spec, "file://")) { + if (specIsRelative || specIsRootAbs) { + result.blocked = BlockedFromHttpMessage( + rawSpec, referrerKey, "it does not form an http(s) URL against the importer's URL."); + } else 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 if (!HasUrlScheme(spec)) { + result.blocked = BlockedFromHttpMessage( + rawSpec, referrerKey, + "it is not in the import map (bare specifiers from an HTTP module must be mapped)."); + } else { + // Another URL scheme (blob:, data:, …): not a file, and import() serves + // blob: itself. + result.attempted = spec; + } + return result; + } + // A query or fragment is URL syntax, never part of a file name, so // `import './x.js?v=1'` names x.js. Stripped here rather than at the // import() entry point, so a static import from a local referrer resolves @@ -1418,11 +1478,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) { @@ -2273,9 +2334,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: @@ -2496,8 +2556,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 @@ -2525,21 +2583,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. @@ -2577,9 +2620,36 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local } } } + 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()); @@ -2587,6 +2657,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. @@ -3123,6 +3202,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 8f398dea0..f07908d94 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -1113,6 +1113,230 @@ 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(); + }); + }); + }); + 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 000000000..02d67cde6 --- /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 000000000..ebd447ab8 --- /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 000000000..9db4aa188 --- /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 000000000..739080868 --- /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/tilde.mjs b/TestRunner/app/tests/esm/http-importer/tilde.mjs new file mode 100644 index 000000000..fbc1c5cae --- /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/TestRunnerTests/TestRunnerTests.swift b/TestRunnerTests/TestRunnerTests.swift index 24593e0c6..391fa61b8 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,31 @@ 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. + 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" + } + 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 72030cab8..e2fde946b 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -759,6 +759,36 @@ unmodified where a shim exists: ## Loading ES modules +### Specifier resolution + +`import` and `import()` resolve a specifier the same way, by the kind of the +importing module. `ns:`/`node:` builtins resolve first, and the +[import map](#import-maps-and-scopes) is consulted next for every importer; +the table covers a specifier the map does not match. + +| specifier | file importer | http(s) importer | +|---|---|---| +| `./x`, `../x` | the importer's directory on disk | the importer's URL, query kept | +| `/x` | the app root | the importer's origin, query kept | +| `//host/x` | the app root | the importer's scheme, query kept | +| `~/x` | the app root | refused | +| bare (`pkg`, `pkg/x`) | the app root | refused: it needs an import-map entry | +| `file:///app/x` | the app root | the app root | +| `http(s)://…` | fetched | fetched | + +On disk, the query and fragment are dropped and a missing extension or a +directory is completed with `.mjs`, `.js`, `/index.mjs`, `/index.js`, in that +order. An import-map target is never refused — an entry is explicit +configuration, so it may point an HTTP module at a `~/` path — though a +relative or root-relative target still resolves against an HTTP importer's +URL. From an HTTP importer, a specifier with any other URL scheme (`data:`, +`file:/x`) is never looked up on disk; `import()` of a `blob:nativescript/…` +URL loads from the blob store whatever the importer. 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. + ### 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 348f4485a..00f15997a 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. */