From 58b047d6c7559cebda96cbb115c7fc315ae3d44d Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 14:04:49 -0300 Subject: [PATCH 1/7] fix(runtime): consult the import map with a file module's import() specifier as written From a file module, import() dropped the specifier's query or fragment before the import map was consulted, so import('pkg?x') looked up 'pkg' while a static import 'pkg?x' looked up 'pkg?x'. Both forms now match the map (imports and scopes) against the specifier as written, and the query or fragment is dropped only where a file path is derived. - A relative import() drops the query or fragment before it is joined onto the importer's directory, so dot segments inside a query cannot reach the path. - A file importer's own blob: specifier still reaches the blob store without its query or fragment. HTTP importers and absolute http(s) specifiers are unchanged. --- .../runtime/ModuleInternalCallbacks.mm | 34 +++-- TestRunner/app/tests/HttpEsmLoaderTests.js | 127 ++++++++++++++++-- .../app/tests/esm/query-map/dir/sub.mjs | 1 + TestRunner/app/tests/esm/query-map/file.mjs | 1 + .../app/tests/esm/query-map/importer.mjs | 3 + .../app/tests/esm/query-map/static-files.mjs | 4 + .../esm/query-map/static-http-prefix.mjs | 1 + .../app/tests/esm/query-map/static-prefix.mjs | 1 + .../app/tests/esm/query-map/static-scoped.mjs | 1 + .../tests/esm/query-map/static-unmapped.mjs | 1 + docs/ns-builtin-modules.md | 12 +- 11 files changed, 151 insertions(+), 35 deletions(-) create mode 100644 TestRunner/app/tests/esm/query-map/dir/sub.mjs create mode 100644 TestRunner/app/tests/esm/query-map/file.mjs create mode 100644 TestRunner/app/tests/esm/query-map/importer.mjs create mode 100644 TestRunner/app/tests/esm/query-map/static-files.mjs create mode 100644 TestRunner/app/tests/esm/query-map/static-http-prefix.mjs create mode 100644 TestRunner/app/tests/esm/query-map/static-prefix.mjs create mode 100644 TestRunner/app/tests/esm/query-map/static-scoped.mjs create mode 100644 TestRunner/app/tests/esm/query-map/static-unmapped.mjs diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 42f38953..2aff24cd 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -3126,22 +3126,9 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local } const bool importerIsHttp = IsHttpRegistryKey(dynamicReferrerKey); - // 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 = !NormalizeHttpModuleUrl(normalizedSpec).empty(); - 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()); - } - + // The specifier goes to the resolver as written, as a static import's does: + // the import map is matched against it query included, and the resolver + // drops a file specifier's query or fragment only to derive the path. ModuleResolution dynamicResolution; if (!normalizedSpec.empty()) { dynamicResolution = ResolveSpecifierToPath(normalizedSpec, dynamicReferrerKey); @@ -3177,6 +3164,12 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local // We retrieve the blob content from the global BLOB_STORE via URL.InternalAccessor.getData() // and compile/execute it as an ES module. if (!normalizedSpec.empty() && StartsWith(normalizedSpec, "blob:nativescript/")) { + // The blob store is keyed by the bare object URL. A file importer's own + // blob specifier reaches it without query or fragment; an HTTP + // importer's, and an import-map target, as written. + if (!importerIsHttp && normalizedSpec == rawSpec) { + normalizedSpec = normalizedSpec.substr(0, normalizedSpec.find_first_of("?#")); + } const std::string blobRegistryKey = CanonicalizeRegistryKey(normalizedSpec); TNS_DEBUG(Esm, "[dyn-import][blob] trying blob URL %s key=%s", normalizedSpec.c_str(), @@ -3733,12 +3726,15 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local size_t slash = refPath.find_last_of("/\\"); std::string baseDir = slash == std::string::npos ? std::string() : refPath.substr(0, slash + 1); + // Dropped before the join: dot segments inside a query or fragment + // would otherwise collapse into the path. + const std::string relPath = normalizedSpec.substr(0, normalizedSpec.find_first_of("?#")); TNS_DEBUG(Esm, "[dyn-import][ref] url=%s base=%s spec=%s", refUrl.c_str(), - baseDir.c_str(), normalizedSpec.c_str()); + baseDir.c_str(), relPath.c_str()); // Join and standardize via NSString to collapse dot-segments @autoreleasepool { NSString* nsBase = [NSString stringWithUTF8String:baseDir.c_str()]; - NSString* nsRel = [NSString stringWithUTF8String:normalizedSpec.c_str()]; + NSString* nsRel = [NSString stringWithUTF8String:relPath.c_str()]; if (nsBase && nsRel) { NSString* joined = [nsBase stringByAppendingPathComponent:nsRel]; NSString* std = [joined stringByStandardizingPath]; @@ -3748,7 +3744,7 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local // Prefer absolute filesystem path; ResolveModuleCallback can handle it adjustedSpecifier = tns::ToV8String(isolate, fsPath.c_str()); TNS_DEBUG(Esm, "[dyn-import][normalize-rel] %s + %s -> %s", baseDir.c_str(), - normalizedSpec.c_str(), fsPath.c_str()); + relPath.c_str(), fsPath.c_str()); } } } diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index d636e1bc..06a18b39 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -2425,31 +2425,136 @@ describe("HTTP ESM Loader", function() { }); }); + // Each row compares a static import with an import() issued from a module + // in the same directory. A static importer links once per process, so each + // one serves a single map. describe("import-map lookup of a query from a file module", function () { var nsModule = require("ns:module"); + var dir = "~/tests/esm/query-map/"; afterEach(function () { nsModule.configureLoader({ importMap: { imports: {} } }); }); - it("looks a static import's query up in the map and drops an import()'s", function (done) { + function settle(promise, pick) { + return promise.then(pick, function (error) { + return "rejected: " + formatError(error); + }); + } + + function name(ns) { + return ns.name; + } + + function dynamicImport(spec) { + return import(dir + "importer.mjs").then(function (mod) { + return mod.load(spec); + }); + } + + // Resolves to [static import's result, import()'s result]. + function bothForms(staticImporter, spec, pick) { + return Promise.all([ + settle(import(dir + staticImporter), function (ns) { + return pick(ns.dep); + }), + settle(dynamicImport(spec), pick), + ]); + } + + it("looks the query up in the map for import() as for a static import", 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", + "ns-query-map-pkg": dir + "stripped.mjs", + "ns-query-map-pkg?x": dir + "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"); + bothForms("static-importer.mjs", "ns-query-map-pkg?x", name).then(function (results) { + expect(results).toEqual(["literal", "literal"]); done(); - }).catch(function (error) { - expect("rejected: " + formatError(error)).toBe("resolved"); + }); + }); + + it("applies no entry of the query-less specifier to either form", function (done) { + nsModule.configureLoader({ + importMap: { imports: { "ns-query-map-unmapped": dir + "stripped.mjs" } }, + }); + bothForms("static-unmapped.mjs", "ns-query-map-unmapped?x", name).then(function (results) { + expect(results[0]).toContain("Cannot find module 'ns-query-map-unmapped?x'"); + expect(results[1]).toContain("Cannot find module 'ns-query-map-unmapped?x'"); + done(); + }); + }); + + it("matches a prefix entry rather than the query-less specifier's exact entry", + function (done) { + nsModule.configureLoader({ + importMap: { + imports: { + "ns-query-map-dir/": dir + "dir/", + "ns-query-map-dir/sub.mjs": dir + "stripped.mjs", + }, + }, + }); + bothForms("static-prefix.mjs", "ns-query-map-dir/sub.mjs?x", name).then(function (results) { + expect(results).toEqual(["sub", "sub"]); + done(); + }); + }); + + it("keeps the query on a prefix entry's http(s) target", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + nsModule.configureLoader({ + importMap: { imports: { "ns-query-map-http/": origin + "/esm/" } }, + }); + bothForms("static-http-prefix.mjs", "ns-query-map-http/query.mjs?k=pfx", function (ns) { + return ns.query; + }).then(function (results) { + expect(results).toEqual(["k=pfx", "k=pfx"]); + done(); + }); + }); + + it("applies a scope to import() as to a static import", function (done) { + var scopes = {}; + scopes[__dirname + "/esm/query-map/"] = { "ns-query-map-scoped?x": dir + "literal.mjs" }; + nsModule.configureLoader({ + importMap: { + imports: { "ns-query-map-scoped": dir + "stripped.mjs" }, + scopes: scopes, + }, + }); + bothForms("static-scoped.mjs", "ns-query-map-scoped?x", name).then(function (results) { + expect(results).toEqual(["literal", "literal"]); + done(); + }); + }); + + it("loads the file a relative or ~/ specifier names, whatever its query or fragment", + function (done) { + var specs = [ + "./file.mjs?v=1", + "./file.mjs#frag", + dir + "file.mjs?v=1", + "./file.mjs?from=/../../nope", + ]; + Promise.all([ + settle(import(dir + "static-files.mjs"), function (ns) { + return [ns.query.name, ns.fragment.name, ns.tilde.name, ns.dotsInQuery.name]; + }), + Promise.all(specs.map(function (spec) { + return settle(dynamicImport(spec), name); + })), + ]).then(function (results) { + expect(results[0]).toEqual(["file", "file", "file", "file"]); + expect(results[1]).toEqual(["file", "file", "file", "file"]); done(); }); }); diff --git a/TestRunner/app/tests/esm/query-map/dir/sub.mjs b/TestRunner/app/tests/esm/query-map/dir/sub.mjs new file mode 100644 index 00000000..df64d305 --- /dev/null +++ b/TestRunner/app/tests/esm/query-map/dir/sub.mjs @@ -0,0 +1 @@ +export const name = "sub"; diff --git a/TestRunner/app/tests/esm/query-map/file.mjs b/TestRunner/app/tests/esm/query-map/file.mjs new file mode 100644 index 00000000..95f503bc --- /dev/null +++ b/TestRunner/app/tests/esm/query-map/file.mjs @@ -0,0 +1 @@ +export const name = "file"; diff --git a/TestRunner/app/tests/esm/query-map/importer.mjs b/TestRunner/app/tests/esm/query-map/importer.mjs new file mode 100644 index 00000000..0712d2d4 --- /dev/null +++ b/TestRunner/app/tests/esm/query-map/importer.mjs @@ -0,0 +1,3 @@ +export function load(spec) { + return import(spec); +} diff --git a/TestRunner/app/tests/esm/query-map/static-files.mjs b/TestRunner/app/tests/esm/query-map/static-files.mjs new file mode 100644 index 00000000..b6ef2c47 --- /dev/null +++ b/TestRunner/app/tests/esm/query-map/static-files.mjs @@ -0,0 +1,4 @@ +export * as query from "./file.mjs?v=1"; +export * as fragment from "./file.mjs#frag"; +export * as tilde from "~/tests/esm/query-map/file.mjs?v=1"; +export * as dotsInQuery from "./file.mjs?from=/../../nope"; diff --git a/TestRunner/app/tests/esm/query-map/static-http-prefix.mjs b/TestRunner/app/tests/esm/query-map/static-http-prefix.mjs new file mode 100644 index 00000000..a12564b5 --- /dev/null +++ b/TestRunner/app/tests/esm/query-map/static-http-prefix.mjs @@ -0,0 +1 @@ +export * as dep from "ns-query-map-http/query.mjs?k=pfx"; diff --git a/TestRunner/app/tests/esm/query-map/static-prefix.mjs b/TestRunner/app/tests/esm/query-map/static-prefix.mjs new file mode 100644 index 00000000..d1e9a25b --- /dev/null +++ b/TestRunner/app/tests/esm/query-map/static-prefix.mjs @@ -0,0 +1 @@ +export * as dep from "ns-query-map-dir/sub.mjs?x"; diff --git a/TestRunner/app/tests/esm/query-map/static-scoped.mjs b/TestRunner/app/tests/esm/query-map/static-scoped.mjs new file mode 100644 index 00000000..93ba827b --- /dev/null +++ b/TestRunner/app/tests/esm/query-map/static-scoped.mjs @@ -0,0 +1 @@ +export * as dep from "ns-query-map-scoped?x"; diff --git a/TestRunner/app/tests/esm/query-map/static-unmapped.mjs b/TestRunner/app/tests/esm/query-map/static-unmapped.mjs new file mode 100644 index 00000000..c790bf6c --- /dev/null +++ b/TestRunner/app/tests/esm/query-map/static-unmapped.mjs @@ -0,0 +1 @@ +export * as dep from "ns-query-map-unmapped?x"; diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 8aaf580c..754208e1 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -1002,11 +1002,13 @@ 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: a file module's `import()` may -look a target up a second time (an HTTP module's follows one entry, as its -static import does). +From a file module, `import 'pkg?x'` and `import('pkg?x')` both look `pkg?x` +up in the import map, exactly as written: an entry for `pkg` does not match it, +while a `pkg/` prefix entry matches `pkg/x.js?v=1`. A query or fragment is +dropped only when a file path is derived, so `./x.js?v=1` and `./x.js#f` load +`x.js`. An import-map target should not itself be a key of the map: a file +module's `import()` may look a target up a second time (an HTTP module's +follows one entry, as its static import does). ### The `require()` specifier From 1ddab83972601426c91d8543d113c0a98086a037 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 14:57:14 -0300 Subject: [PATCH 2/7] test(runtime): pin what import() settles with per importer and specifier shape A table of import() outcomes from a file ES module, a direct eval inside one, a CommonJS script, new Function, an indirect eval and an HTTP module, over relative, bare (mapped and unmapped), ~/, absolute, file://, extensionless, directory, JSON, builtin, blob:, http(s) and unresolvable specifiers, plus modules that fail to link or throw while evaluating, repeated and concurrent imports. Every row holds the current behaviour. --- TestRunner/app/tests/DynamicImportTests.js | 285 ++++++++++++++++++ .../app/tests/esm/import-pin/concurrent.mjs | 2 + TestRunner/app/tests/esm/import-pin/data.json | 1 + .../app/tests/esm/import-pin/dir/index.mjs | 1 + .../app/tests/esm/import-pin/importer-cjs.js | 3 + .../app/tests/esm/import-pin/importer.mjs | 7 + TestRunner/app/tests/esm/import-pin/leaf.mjs | 1 + .../app/tests/esm/import-pin/link-export.mjs | 2 + .../app/tests/esm/import-pin/link-missing.mjs | 2 + .../app/tests/esm/import-pin/syntax-error.mjs | 1 + .../app/tests/esm/import-pin/throws.mjs | 2 + TestRunner/app/tests/esm/import-pin/tla.mjs | 2 + TestRunner/app/tests/index.js | 3 + 13 files changed, 312 insertions(+) create mode 100644 TestRunner/app/tests/DynamicImportTests.js create mode 100644 TestRunner/app/tests/esm/import-pin/concurrent.mjs create mode 100644 TestRunner/app/tests/esm/import-pin/data.json create mode 100644 TestRunner/app/tests/esm/import-pin/dir/index.mjs create mode 100644 TestRunner/app/tests/esm/import-pin/importer-cjs.js create mode 100644 TestRunner/app/tests/esm/import-pin/importer.mjs create mode 100644 TestRunner/app/tests/esm/import-pin/leaf.mjs create mode 100644 TestRunner/app/tests/esm/import-pin/link-export.mjs create mode 100644 TestRunner/app/tests/esm/import-pin/link-missing.mjs create mode 100644 TestRunner/app/tests/esm/import-pin/syntax-error.mjs create mode 100644 TestRunner/app/tests/esm/import-pin/throws.mjs create mode 100644 TestRunner/app/tests/esm/import-pin/tla.mjs diff --git a/TestRunner/app/tests/DynamicImportTests.js b/TestRunner/app/tests/DynamicImportTests.js new file mode 100644 index 00000000..51e70f56 --- /dev/null +++ b/TestRunner/app/tests/DynamicImportTests.js @@ -0,0 +1,285 @@ +// What import() settles with, per importer kind and specifier shape. Each row +// is "ok:" or "rejected::", +// with the app root, the test server origin and blob URLs written as , +// and . Rows run in order and share one module registry, so a +// later row can see what an earlier one loaded. Code built by `new Function` +// or an indirect eval imports with the referrer of the script that built it, +// here this file in tests/. +describe("import() resolution table", function () { + var nsModule = require("ns:module"); + var dir = "~/tests/esm/import-pin/"; + var appRoot = __dirname.slice(0, __dirname.length - "/tests".length); + + function hostOrigin() { + try { + var reportUrl = NSProcessInfo.processInfo.environment.objectForKey("REPORT_BASEURL"); + return reportUrl ? new URL(String(reportUrl)).origin : null; + } catch (e) { + return null; + } + } + var origin = hostOrigin(); + var blobUrl = null; + + function normalize(text) { + var out = String(text).split(appRoot).join(""); + if (origin) { + out = out.split(origin).join(""); + } + if (blobUrl) { + out = out.split(blobUrl).join(""); + } + return out; + } + + function exposed(ns) { + if (ns === null || typeof ns !== "object") { + return "non-object:" + typeof ns; + } + if ("name" in ns) { + return String(ns.name); + } + if ("query" in ns) { + return "query=" + ns.query; + } + if ("default" in ns && ns.default && typeof ns.default === "object" && "name" in ns.default) { + return "default.name=" + ns.default.name; + } + return "keys=" + Object.keys(ns).sort().slice(0, 3).join(","); + } + + function describeError(e) { + var cls = e && e.constructor && e.constructor.name ? e.constructor.name : typeof e; + var message = e && typeof e.message === "string" ? e.message : String(e); + return cls + ":" + normalize(message); + } + + function outcome(promise) { + return Promise.resolve(promise).then(function (ns) { + return "ok:" + exposed(ns); + }, function (e) { + return "rejected:" + describeError(e); + }); + } + + var importers = { + esm: function (spec) { + return import(dir + "importer.mjs").then(function (m) { return m.load(spec); }); + }, + esmEval: function (spec) { + return import(dir + "importer.mjs").then(function (m) { return m.evalLoad(spec); }); + }, + cjs: function (spec) { + return require("./esm/import-pin/importer-cjs.js").load(spec); + }, + newFunction: new Function("spec", "return import(spec);"), + indirectEval: function (spec) { + globalThis.__importPinSpec = spec; + return (0, eval)("import(globalThis.__importPinSpec)"); + }, + http: function (spec) { + return import(origin + "/esm/resolve/import-pin/importer.mjs").then(function (m) { + return m.load(spec); + }); + }, + }; + + beforeAll(function () { + nsModule.configureLoader({ + importMap: { + imports: { + "ns-pin-mapped": "~/tests/esm/import-pin/leaf.mjs", + "ns-pin-relative-target": "./leaf.mjs", + "ns-pin-chain": "ns-pin-mapped", + "ns-pin-dir/": "~/tests/esm/import-pin/dir/", + }, + }, + }); + // 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); + }; + blobUrl = URL.createObjectURL(new Blob(["export const name = 'blob';\n"], + { type: "text/javascript" }), { ext: ".mjs" }); + if (typeof previousBlob === "undefined") { + delete globalThis.Blob; + } else { + globalThis.Blob = previousBlob; + } + }); + + afterAll(function () { + URL.revokeObjectURL(blobUrl); + nsModule.configureLoader({ importMap: { imports: {} } }); + }); + + // [importer, specifier, expected]; a specifier function is called when the + // row runs. + var rows = [ + ["esm", "./leaf.mjs", "ok:leaf"], + ["esm", "../import-pin/leaf.mjs", "ok:leaf"], + ["esm", "./leaf", "ok:leaf"], + ["esm", "./dir", "ok:dir-index"], + ["esm", "./dir/", "ok:dir-index"], + ["esm", "./leaf.mjs?v=1", "ok:leaf"], + ["esm", "./leaf.mjs#f", "ok:leaf"], + ["esm", "ns-pin-mapped", "ok:leaf"], + ["esm", "ns-pin-relative-target", "ok:leaf"], + ["esm", "ns-pin-chain", "ok:leaf"], + ["esm", "ns-pin-dir/index.mjs", "ok:dir-index"], + ["esm", "ns-pin-unmapped", "rejected:Error:Cannot find module 'ns-pin-unmapped' (tried /ns-pin-unmapped)"], + ["esm", "~/tests/esm/import-pin/leaf.mjs", "ok:leaf"], + ["esm", "/tests/esm/import-pin/leaf.mjs", "ok:leaf"], + ["esm", "/app/tests/esm/import-pin/leaf.mjs", "ok:leaf"], + ["esm", function () { return __dirname + "/esm/import-pin/leaf.mjs"; }, "rejected:Error:Cannot find module '/tests/esm/import-pin/leaf.mjs' (tried /tests/esm/import-pin/leaf.mjs)"], + ["esm", "file:///app/tests/esm/import-pin/leaf.mjs", "ok:leaf"], + ["esm", function () { return "file://" + __dirname + "/esm/import-pin/leaf.mjs"; }, "rejected:Error:Cannot find module 'file:///tests/esm/import-pin/leaf.mjs' (tried /tests/esm/import-pin/leaf.mjs)"], + ["esm", "./data.json", "ok:default.name=json"], + ["esm", "ns:module", "ok:keys=canonicalizeHttpUrlKey,configureLoader,createPumpingRequire"], + ["esm", "node:url", "ok:keys=URL,URLSearchParams,default"], + ["esm", "ns:import-pin-missing", "rejected:Error:No such built-in module: ns:import-pin-missing"], + ["esm", function () { return blobUrl; }, "ok:blob"], + ["esm", function () { return blobUrl + "?x"; }, "ok:blob"], + ["esm", function () { return blobUrl + "#f"; }, "ok:blob"], + ["esm", "./missing.mjs", "rejected:Error:Cannot find module '/app/tests/esm/import-pin/missing.mjs' (tried /tests/esm/import-pin/missing.mjs)"], + ["esm", "~/tests/esm/import-pin/missing.mjs", "rejected:Error:Cannot find module '~/tests/esm/import-pin/missing.mjs' (tried /app/tests/esm/import-pin/missing.mjs)"], + ["esm", "./syntax-error.mjs", "rejected:SyntaxError:Unexpected token ';'"], + ["esm", "./link-export.mjs", "rejected:Error:Failed to instantiate module: ./link-export.mjs \u2014 SyntaxError: The requested module './leaf.mjs' does not provide an export named 'missingExport'"], + ["esm", "./link-export.mjs", "rejected:Error:Failed to instantiate module: ./link-export.mjs \u2014 SyntaxError: The requested module './leaf.mjs' does not provide an export named 'missingExport'"], + ["esm", "./link-missing.mjs", "rejected:Error:Failed to instantiate module: ./link-missing.mjs \u2014 Error: Cannot find module './missing-dependency.mjs' (tried /tests/esm/import-pin/missing-dependency.mjs)"], + ["esm", "./throws.mjs", "rejected:TypeError:import-pin evaluation error"], + ["esm", "./throws.mjs", "rejected:TypeError:import-pin evaluation error"], + ["esm", "./tla.mjs", "ok:tla"], + ["esm", "", "rejected:Error:Module resolution failed for dynamic import: "], + + ["esmEval", "./leaf.mjs", "ok:leaf"], + + ["cjs", "./leaf.mjs", "ok:leaf"], + ["cjs", "../import-pin/leaf.mjs", "ok:leaf"], + ["cjs", "./leaf", "ok:leaf"], + ["cjs", "./dir", "ok:dir-index"], + ["cjs", "ns-pin-mapped", "ok:leaf"], + ["cjs", "ns-pin-relative-target", "ok:leaf"], + ["cjs", "ns-pin-chain", "ok:leaf"], + ["cjs", "ns-pin-unmapped", "rejected:Error:Cannot find module 'ns-pin-unmapped' (tried /ns-pin-unmapped)"], + ["cjs", "~/tests/esm/import-pin/leaf.mjs", "ok:leaf"], + ["cjs", "/tests/esm/import-pin/leaf.mjs", "ok:leaf"], + ["cjs", "file:///app/tests/esm/import-pin/leaf.mjs", "ok:leaf"], + ["cjs", "./data.json", "ok:default.name=json"], + ["cjs", "ns:module", "ok:keys=canonicalizeHttpUrlKey,configureLoader,createPumpingRequire"], + ["cjs", function () { return blobUrl; }, "ok:blob"], + ["cjs", function () { return blobUrl + "?x"; }, "ok:blob"], + ["cjs", function () { return blobUrl + "#f"; }, "ok:blob"], + ["cjs", "./missing.mjs", "rejected:Error:Cannot find module '/app/tests/esm/import-pin/missing.mjs' (tried /tests/esm/import-pin/missing.mjs)"], + ["cjs", "./throws.mjs", "rejected:TypeError:import-pin evaluation error"], + + ["newFunction", "./leaf.mjs", "rejected:Error:Cannot find module '/app/tests/leaf.mjs' (tried /tests/leaf.mjs)"], + ["newFunction", "./tests/esm/import-pin/leaf.mjs", "rejected:Error:Cannot find module '/app/tests/tests/esm/import-pin/leaf.mjs' (tried /tests/tests/esm/import-pin/leaf.mjs)"], + ["newFunction", "ns-pin-mapped", "ok:leaf"], + ["newFunction", "ns-pin-relative-target", "rejected:Error:Cannot find module '/app/tests/leaf.mjs' (tried /tests/leaf.mjs)"], + ["newFunction", "ns-pin-unmapped", "rejected:Error:Cannot find module 'ns-pin-unmapped' (tried /ns-pin-unmapped)"], + ["newFunction", "~/tests/esm/import-pin/leaf.mjs", "ok:leaf"], + ["newFunction", "/tests/esm/import-pin/leaf.mjs", "ok:leaf"], + ["newFunction", "file:///app/tests/esm/import-pin/leaf.mjs", "ok:leaf"], + ["newFunction", "ns:module", "ok:keys=canonicalizeHttpUrlKey,configureLoader,createPumpingRequire"], + ["newFunction", function () { return blobUrl + "#f"; }, "ok:blob"], + + ["indirectEval", "./leaf.mjs", "rejected:Error:Cannot find module '/app/tests/leaf.mjs' (tried /tests/leaf.mjs)"], + ["indirectEval", "./tests/esm/import-pin/leaf.mjs", "rejected:Error:Cannot find module '/app/tests/tests/esm/import-pin/leaf.mjs' (tried /tests/tests/esm/import-pin/leaf.mjs)"], + ["indirectEval", "~/tests/esm/import-pin/leaf.mjs", "ok:leaf"], + ]; + + var httpRows = [ + ["esm", function () { return origin + "/esm/query.mjs?k=pin"; }, "ok:query=k=pin"], + ["cjs", function () { return origin + "/esm/query.mjs?k=pin"; }, "ok:query=k=pin"], + ["newFunction", function () { return origin + "/esm/query.mjs?k=pin"; }, "ok:query=k=pin"], + ["http", "./relative.mjs?k=1", "ok:query=k=1"], + ["http", "ns-pin-mapped", "ok:leaf"], + ["http", "ns-pin-unmapped", "rejected:Error:Cannot resolve module specifier \"ns-pin-unmapped\" imported from /esm/resolve/import-pin/importer.mjs: it is not in the import map (bare specifiers from an HTTP module must be mapped)."], + ["http", "~/tests/esm/import-pin/leaf.mjs", "rejected:Error:Cannot resolve module specifier \"~/tests/esm/import-pin/leaf.mjs\" imported from /esm/resolve/import-pin/importer.mjs: app-relative \"~/\" paths are not available to modules loaded over HTTP (use a file:// URL, an import-map entry, or createRequire)."], + ["http", "file:///app/tests/esm/import-pin/leaf.mjs", "ok:leaf"], + ["http", "file:///app/tests/esm/import-pin/dir", "ok:dir-index"], + ["http", "file:///app/tests/esm/import-pin/data.json", "ok:default.name=json"], + ["http", "file:///app/tests/esm/import-pin/missing.mjs", "rejected:Error:Cannot find module 'file:///app/tests/esm/import-pin/missing.mjs' (tried /app/tests/esm/import-pin/missing.mjs)"], + ["http", "file:///app/tests/esm/import-pin/throws.mjs", "rejected:TypeError:import-pin evaluation error"], + ["http", "ns:module", "ok:keys=canonicalizeHttpUrlKey,configureLoader,createPumpingRequire"], + ["http", function () { return blobUrl; }, "ok:blob"], + ["http", function () { return blobUrl + "?x"; }, "rejected:Error:Blob not found: ?x"], + ["http", function () { return blobUrl + "#f"; }, "rejected:Error:Blob not found: #f"], + ]; + + var rowCount = 0; + function addRow(row, needsOrigin) { + var label = typeof row[1] === "function" + ? String(row[1]).replace(/^function \(\) \{ return |; \}$/g, "") + : JSON.stringify(row[1]); + rowCount++; + it("#" + rowCount + " from " + row[0] + ": " + label, function (done) { + if (needsOrigin && !origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var spec = typeof row[1] === "function" ? row[1]() : row[1]; + outcome(importers[row[0]](spec)).then(function (actual) { + expect(actual).toBe(row[2]); + done(); + }); + }); + } + + rows.forEach(function (row) { + addRow(row, row[0] === "http"); + }); + httpRows.forEach(function (row) { + addRow(row, true); + }); + + it("from esm: the same namespace for a repeated import", function (done) { + Promise.all([importers.esm("./leaf.mjs"), importers.esm("./leaf.mjs")]).then(function (r) { + expect(r[0] === r[1]).toBe(true); + done(); + }, function (e) { + expect("rejected:" + describeError(e)).toBe("resolved"); + done(); + }); + }); + + it("from esm and cjs: the same namespace for one file", function (done) { + Promise.all([importers.esm("./leaf.mjs"), importers.cjs("./leaf.mjs"), + importers.esm("~/tests/esm/import-pin/leaf.mjs")]).then(function (r) { + expect([r[0] === r[1], r[0] === r[2]]).toEqual([true, true]); + done(); + }, function (e) { + expect("rejected:" + describeError(e)).toBe("resolved"); + done(); + }); + }); + + it("from esm: concurrent first imports share one evaluation and namespace", function (done) { + Promise.all([importers.esm("./concurrent.mjs"), importers.esm("./concurrent.mjs"), + importers.cjs("./concurrent.mjs")]).then(function (r) { + expect([r[0] === r[1], r[0] === r[2], globalThis.__importPinConcurrentEvaluations]) + .toEqual([true, true, 1]); + done(); + }, function (e) { + expect("rejected:" + describeError(e)).toBe("resolved"); + done(); + }); + }); + + it("from esm: JSON with a type attribute", function (done) { + import(dir + "importer.mjs").then(function (m) { + return outcome(m.load("./data.json", { with: { type: "json" } })); + }).then(function (actual) { + expect(actual).toBe("ok:default.name=json"); + done(); + }); + }); +}); diff --git a/TestRunner/app/tests/esm/import-pin/concurrent.mjs b/TestRunner/app/tests/esm/import-pin/concurrent.mjs new file mode 100644 index 00000000..c2854c33 --- /dev/null +++ b/TestRunner/app/tests/esm/import-pin/concurrent.mjs @@ -0,0 +1,2 @@ +globalThis.__importPinConcurrentEvaluations = (globalThis.__importPinConcurrentEvaluations || 0) + 1; +export const name = "concurrent"; diff --git a/TestRunner/app/tests/esm/import-pin/data.json b/TestRunner/app/tests/esm/import-pin/data.json new file mode 100644 index 00000000..a31b158e --- /dev/null +++ b/TestRunner/app/tests/esm/import-pin/data.json @@ -0,0 +1 @@ +{ "name": "json" } diff --git a/TestRunner/app/tests/esm/import-pin/dir/index.mjs b/TestRunner/app/tests/esm/import-pin/dir/index.mjs new file mode 100644 index 00000000..c3ed4ff7 --- /dev/null +++ b/TestRunner/app/tests/esm/import-pin/dir/index.mjs @@ -0,0 +1 @@ +export const name = "dir-index"; diff --git a/TestRunner/app/tests/esm/import-pin/importer-cjs.js b/TestRunner/app/tests/esm/import-pin/importer-cjs.js new file mode 100644 index 00000000..32bd4680 --- /dev/null +++ b/TestRunner/app/tests/esm/import-pin/importer-cjs.js @@ -0,0 +1,3 @@ +exports.load = function (spec) { + return import(spec); +}; diff --git a/TestRunner/app/tests/esm/import-pin/importer.mjs b/TestRunner/app/tests/esm/import-pin/importer.mjs new file mode 100644 index 00000000..873b41b6 --- /dev/null +++ b/TestRunner/app/tests/esm/import-pin/importer.mjs @@ -0,0 +1,7 @@ +export function load(spec, options) { + return options === undefined ? import(spec) : import(spec, options); +} + +export function evalLoad(spec) { + return eval("import(spec)"); +} diff --git a/TestRunner/app/tests/esm/import-pin/leaf.mjs b/TestRunner/app/tests/esm/import-pin/leaf.mjs new file mode 100644 index 00000000..78c8271f --- /dev/null +++ b/TestRunner/app/tests/esm/import-pin/leaf.mjs @@ -0,0 +1 @@ +export const name = "leaf"; diff --git a/TestRunner/app/tests/esm/import-pin/link-export.mjs b/TestRunner/app/tests/esm/import-pin/link-export.mjs new file mode 100644 index 00000000..90a58f29 --- /dev/null +++ b/TestRunner/app/tests/esm/import-pin/link-export.mjs @@ -0,0 +1,2 @@ +import { missingExport } from "./leaf.mjs"; +export const name = "link-export" + missingExport; diff --git a/TestRunner/app/tests/esm/import-pin/link-missing.mjs b/TestRunner/app/tests/esm/import-pin/link-missing.mjs new file mode 100644 index 00000000..b61e5b5d --- /dev/null +++ b/TestRunner/app/tests/esm/import-pin/link-missing.mjs @@ -0,0 +1,2 @@ +import "./missing-dependency.mjs"; +export const name = "link-missing"; diff --git a/TestRunner/app/tests/esm/import-pin/syntax-error.mjs b/TestRunner/app/tests/esm/import-pin/syntax-error.mjs new file mode 100644 index 00000000..8d651937 --- /dev/null +++ b/TestRunner/app/tests/esm/import-pin/syntax-error.mjs @@ -0,0 +1 @@ +export const name = ; diff --git a/TestRunner/app/tests/esm/import-pin/throws.mjs b/TestRunner/app/tests/esm/import-pin/throws.mjs new file mode 100644 index 00000000..1f3fdd55 --- /dev/null +++ b/TestRunner/app/tests/esm/import-pin/throws.mjs @@ -0,0 +1,2 @@ +export const name = "throws"; +throw new TypeError("import-pin evaluation error"); diff --git a/TestRunner/app/tests/esm/import-pin/tla.mjs b/TestRunner/app/tests/esm/import-pin/tla.mjs new file mode 100644 index 00000000..63b8ae48 --- /dev/null +++ b/TestRunner/app/tests/esm/import-pin/tla.mjs @@ -0,0 +1,2 @@ +await Promise.resolve(); +export const name = "tla"; diff --git a/TestRunner/app/tests/index.js b/TestRunner/app/tests/index.js index 7be398e0..89b4b440 100644 --- a/TestRunner/app/tests/index.js +++ b/TestRunner/app/tests/index.js @@ -170,6 +170,9 @@ require("./URLPattern"); // HTTP ESM Loader tests require("./HttpEsmLoaderTests"); +// What import() settles with, per importer kind and specifier shape +require("./DynamicImportTests"); + // Remote Module Security tests require("./RemoteModuleSecurityTests"); From 9b2519da421e0163011c284f38209037d8c21f9f Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 15:04:58 -0300 Subject: [PATCH 3/7] fix(runtime): resolve an import() specifier once, through the static resolver import() resolved its specifier, then resolved it a second time with no importer after joining relative specifiers onto the referrer's path by hand. It now resolves once, with the importer key a static import from the same module uses, and dispatches on the result: builtins, http(s), blob: and file modules each load through their own step, and a file module is compiled and registered by the same step a static import's resolver uses. What the promise settles with is unchanged except: - The import map is applied once; a target that is itself a key is not looked up again. - A relative specifier that names no file is reported as written ('./x.mjs'), as a static import reports it. - blob: URLs follow the File API from every importer: the fragment is ignored and the query kept, so blobUrl + '#f' loads from an HTTP module too and blobUrl + '?x' is not found from a file module either. --- .../runtime/ModuleInternalCallbacks.mm | 399 ++++++++---------- NativeScript/runtime/ModuleUrl.cpp | 18 + NativeScript/runtime/ModuleUrl.h | 5 + TestRunner/app/tests/DynamicImportTests.js | 24 +- docs/ns-builtin-modules.md | 19 +- 5 files changed, 217 insertions(+), 248 deletions(-) diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 2aff24cd..8b71b72a 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -1566,10 +1566,11 @@ static void DrainStreamedCompilesForIsolate(v8::Isolate* isolate) { kBuiltin, // ns:/node: — served from the builtin registry kHttp, // absolute http(s) URL kFile, // absolute filesystem path, confirmed to be a regular file + kBlob, // blob: URL — only import() serves it, from the blob store }; Kind kind = Kind::kUnresolved; - std::string url; // kHttp + std::string url; // kHttp; kBlob without its fragment std::string path; // kFile std::string specifier; // the specifier after import-map rewriting std::string attempted; // kUnresolved: the last candidate tried @@ -1718,6 +1719,14 @@ static ModuleResolution ResolveSpecifierToPath( result.specifier = spec; + const std::string blobUrl = BlobStoreUrl(spec); + if (!blobUrl.empty()) { + result.kind = ModuleResolution::Kind::kBlob; + result.url = blobUrl; + result.attempted = blobUrl; + return result; + } + // 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 @@ -1957,6 +1966,7 @@ static void AsyncGraphWalkModuleRequests(const std::shared_ptr& // the synchronous anomaly guard. const ModuleResolution resolution = ResolveSpecifierToPath(*spec, moduleKey); if (resolution.kind == ModuleResolution::Kind::kBuiltin || + resolution.kind == ModuleResolution::Kind::kBlob || resolution.kind == ModuleResolution::Kind::kUnresolved) { continue; } @@ -2782,6 +2792,62 @@ static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate, return CompileJsonTextAsEsModule(isolate, context, jsonText, registryAbsPath, url); } +// The file module `resolution` names: its live registry entry, or the file +// compiled and registered now. Never instantiates or evaluates — a static +// import's resolver must not, and import() does both itself. On failure an +// exception is pending on the isolate. +static v8::MaybeLocal LoadResolvedFileModule(v8::Isolate* isolate, + v8::Local context, + const ModuleResolution& resolution) { + auto* moduleState = ModuleLoaderStateFor(isolate); + if (moduleState == nullptr) { + return v8::MaybeLocal(); + } + auto& registry = moduleState->registry; + const std::string& absPath = resolution.path; + const std::string registryAbsPath = CanonicalizeRegistryKey(absPath); + + // JSON imports (import data from './foo.json' with { type: 'json' }). + if (absPath.size() >= 5 && absPath.compare(absPath.size() - 5, 5, ".json") == 0) { + return CompileJsonAsEsModule(isolate, context, absPath, registryAbsPath); + } + + // Reuse any live, non-errored registry entry. The resolver never evaluates, + // so an unfinished entry (kUninstantiated / kInstantiating / kEvaluating) + // simply rejoins the graph V8 is currently linking — that is how import + // cycles terminate, the same way Node/Blink break them with the module-map + // self-insert. + auto it = registry.find(registryAbsPath); + if (it != registry.end()) { + v8::Local existing = it->second.Get(isolate); + if (!existing.IsEmpty() && existing->GetStatus() != v8::Module::kErrored) { + TNS_DEBUG(Esm, "[resolver] cache hit %s (status=%s)", absPath.c_str(), + ModuleStatusToString(existing->GetStatus())); + return v8::MaybeLocal(existing); + } + RemoveModuleFromRegistry(isolate, absPath); + } + + // Compile + register only. V8 is instantiating a static importer and + // continues the graph walk by resolving this module's own requests next; + // evaluating here would run dependencies in resolver order instead of the + // spec's evaluation order. + TNS_DEBUG(Esm, "[resolver] → compile-register %s", absPath.c_str()); + try { + v8::Local mod; + if (!tns::ModuleInternal::CompileFileEsModule(isolate, absPath).ToLocal(&mod)) { + // The compile exception is pending on the isolate; V8 fails the + // importer's instantiation with it. + return v8::MaybeLocal(); + } + SetRegisteredModule(*moduleState, isolate, registryAbsPath, mod); + return v8::MaybeLocal(mod); + } catch (NativeScriptException& ex) { + ex.ReThrowToV8(isolate); + return v8::MaybeLocal(); + } +} + // Callback invoked by V8 to resolve `import X from 'specifier';` v8::MaybeLocal ResolveModuleCallback(v8::Local context, v8::Local specifier, @@ -2792,7 +2858,6 @@ static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate, if (moduleState == nullptr) { return v8::MaybeLocal(); } - auto& registry = moduleState->registry; const std::optional spec = ModuleSpecifierUtf8(isolate, specifier); if (!spec.has_value()) { @@ -2823,6 +2888,7 @@ static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate, case ModuleResolution::Kind::kHttp: // Security: HttpFetchModule gates remote module access centrally. return LoadHttpModuleForUrl(isolate, context, resolution.url); + case ModuleResolution::Kind::kBlob: case ModuleResolution::Kind::kUnresolved: { // Surfaced as an exception rather than left to ReadModule(), which would // abort the process trying to open a directory. @@ -2833,49 +2899,7 @@ static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate, case ModuleResolution::Kind::kFile: break; } - - const std::string& absPath = resolution.path; - const std::string registryAbsPath = CanonicalizeRegistryKey(absPath); - - // JSON imports (import data from './foo.json' with { type: 'json' }). - if (absPath.size() >= 5 && absPath.compare(absPath.size() - 5, 5, ".json") == 0) { - return CompileJsonAsEsModule(isolate, context, absPath, registryAbsPath); - } - - // Reuse any live, non-errored registry entry. The resolver never evaluates, - // so an unfinished entry (kUninstantiated / kInstantiating / kEvaluating) - // simply rejoins the graph V8 is currently linking — that is how import - // cycles terminate, the same way Node/Blink break them with the module-map - // self-insert. - auto it = registry.find(registryAbsPath); - if (it != registry.end()) { - v8::Local existing = it->second.Get(isolate); - if (!existing.IsEmpty() && existing->GetStatus() != v8::Module::kErrored) { - TNS_DEBUG(Esm, "[resolver] cache hit %s (status=%s)", absPath.c_str(), - ModuleStatusToString(existing->GetStatus())); - return v8::MaybeLocal(existing); - } - RemoveModuleFromRegistry(isolate, absPath); - } - - // Compile + register only — never instantiate or evaluate here. V8 is - // instantiating the importer and continues the graph walk by resolving this - // module's own requests next; evaluating inside the resolver would run - // dependencies in resolver order instead of the spec's evaluation order. - TNS_DEBUG(Esm, "[resolver] → compile-register %s", absPath.c_str()); - try { - v8::Local mod; - if (!tns::ModuleInternal::CompileFileEsModule(isolate, absPath).ToLocal(&mod)) { - // The compile exception is pending on the isolate; V8 fails the - // importer's instantiation with it. - return v8::MaybeLocal(); - } - SetRegisteredModule(*moduleState, isolate, registryAbsPath, mod); - return v8::MaybeLocal(mod); - } catch (NativeScriptException& ex) { - ex.ReThrowToV8(isolate); - return v8::MaybeLocal(); - } + return LoadResolvedFileModule(isolate, context, resolution); } // ──────────────────────────────────────────────────────────────────────────── @@ -3019,6 +3043,38 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local RejectHttpDynamicWaiters(isolate, context, key, loadFailureReason); } +// The importer key an import() resolves against, from the resource name V8 +// hands the host: the registry key a static import from the same module +// resolves against, so relative specifiers and import-map scopes match alike. +// A module's origin is its identity and never goes through the import map. +static std::string DynamicImportReferrerKey(v8::Isolate* isolate, + v8::Local resource_name) { + if (resource_name.IsEmpty() || !resource_name->IsString()) { + return std::string(); + } + v8::String::Utf8Value resourceUtf8(isolate, resource_name); + if (*resourceUtf8 == nullptr) { + return std::string(); + } + const std::string resourceName(*resourceUtf8); + if (!NormalizeHttpModuleUrl(resourceName).empty()) { + return CanonicalizeRegistryKey(resourceName); + } + const ModuleResolution referrer = + ResolveSpecifierToPath(resourceName, std::string(), ImportMapLookup::kSkip); + switch (referrer.kind) { + case ModuleResolution::Kind::kFile: + return CanonicalizeRegistryKey(referrer.path); + case ModuleResolution::Kind::kHttp: + case ModuleResolution::Kind::kBlob: + return CanonicalizeRegistryKey(referrer.url); + case ModuleResolution::Kind::kBuiltin: + case ModuleResolution::Kind::kUnresolved: + break; + } + return CanonicalizeRegistryKey(resourceName); +} + // ──────────────────────────────────────────────────────────────────────────── // Dynamic import() host callback v8::MaybeLocal ImportModuleDynamicallyCallback( @@ -3046,8 +3102,7 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local .FromMaybe(false); return nulScope.Escape(nulResolver->GetPromise()); } - std::string rawSpec = *specUtf8; - NSString* specStr = tns::ToNSString(rawSpec); + const std::string& rawSpec = *specUtf8; if (tns::LogCategoryEnabled(tns::LogCategory::Esm)) { TNS_DEBUG(Esm, "[dyn-import] → %s", rawSpec.c_str()); // Also log the referrer resource when available to correlate origin of dynamic imports @@ -3059,117 +3114,72 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local } } } - // Builtin modules never reach the loader below; the namespace comes straight - // from the realm's synthetic module. - if (NsBuiltinModules::IsBuiltinScheme(rawSpec)) { - v8::EscapableHandleScope builtinScope(isolate); - v8::Local builtinResolver; - if (!v8::Promise::Resolver::New(context).ToLocal(&builtinResolver)) { - return v8::MaybeLocal(); - } - v8::TryCatch tc(isolate); - v8::Local builtin; - if (NsBuiltinModules::GetModule(context, rawSpec).ToLocal(&builtin)) { - builtinResolver->Resolve(context, builtin->GetModuleNamespace()).FromMaybe(false); - } else { - v8::Local error = tc.HasCaught() - ? tc.Exception() - : v8::Exception::Error(tns::ToV8String( - isolate, NsBuiltinModules::NotFoundMessage(rawSpec))); - // Reject must not run with the exception still pending on the isolate. - tc.Reset(); - builtinResolver->Reject(context, error).FromMaybe(false); - } - return builtinScope.Escape(builtinResolver->GetPromise()); - } - - std::string normalizedSpec = rawSpec; v8::EscapableHandleScope scope(isolate); - - // Create a Promise resolver we'll resolve/reject synchronously for now. v8::Local resolver; if (!v8::Promise::Resolver::New(context).ToLocal(&resolver)) { - // Failed to create resolver, return empty promise return v8::MaybeLocal(); } + auto rejectWithMessage = [&](const std::string& message) { + resolver->Reject(context, v8::Exception::Error(tns::ToV8String(isolate, message))) + .FromMaybe(false); + return scope.Escape(resolver->GetPromise()); + }; + + if (rawSpec.empty()) { + return rejectWithMessage("Module resolution failed for dynamic import: "); + } + + // The one resolution of this import(): the call a static import from the + // importing module makes, with the same importer key. Everything below loads + // what it names and never resolves the specifier again. + const ModuleResolution resolution = + ResolveSpecifierToPath(rawSpec, DynamicImportReferrerKey(isolate, resource_name)); + if (!resolution.blocked.empty()) { + return rejectWithMessage(UnresolvedModuleMessage(resolution)); + } + if (resolution.specifier != rawSpec) { + TNS_DEBUG(Esm, "[dyn-import][import-map] rewrite: %s -> %s", rawSpec.c_str(), + resolution.specifier.c_str()); + } - // ── Resolution for dynamic import() ─────────────────────────── - // Resolved once, here, through the same seam the static resolver and the - // graph walk use, and reused for the discovery pre-pass further down. The - // referrer key comes from the host-supplied resource name, canonicalized the - // way the registry keys it, so a scope matches an import() exactly as it - // matches a static import from the same module. Resolving a second time for - // the pre-pass applied the import map twice and, having no referrer to hand, - // resolved that second pass with every scope dropped. - std::string dynamicReferrerKey; - if (!resource_name.IsEmpty() && resource_name->IsString()) { - v8::String::Utf8Value resourceUtf8(isolate, resource_name); - if (*resourceUtf8) { - // A module's origin is its identity and never goes through the import - // map. A local origin (`file:///app/…`) still has to become the absolute - // app path the registry keys by, or no scope would match it. - const std::string resourceName(*resourceUtf8); - if (!NormalizeHttpModuleUrl(resourceName).empty()) { - dynamicReferrerKey = CanonicalizeRegistryKey(resourceName); + switch (resolution.kind) { + case ModuleResolution::Kind::kBuiltin: { + v8::TryCatch tc(isolate); + v8::Local builtin; + if (NsBuiltinModules::GetModule(context, rawSpec).ToLocal(&builtin)) { + resolver->Resolve(context, builtin->GetModuleNamespace()).FromMaybe(false); } else { - const ModuleResolution referrer = - ResolveSpecifierToPath(resourceName, std::string(), ImportMapLookup::kSkip); - 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); - } + v8::Local error = + tc.HasCaught() ? tc.Exception() + : v8::Exception::Error(tns::ToV8String( + isolate, NsBuiltinModules::NotFoundMessage(rawSpec))); + // Reject must not run with the exception still pending on the isolate. + tc.Reset(); + resolver->Reject(context, error).FromMaybe(false); } - } - } - const bool importerIsHttp = IsHttpRegistryKey(dynamicReferrerKey); - - // The specifier goes to the resolver as written, as a static import's does: - // the import map is matched against it query included, and the resolver - // drops a file specifier's query or fragment only to derive the path. - 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()); - specStr = [NSString stringWithUTF8String:normalizedSpec.c_str()]; - TNS_DEBUG(Esm, "[dyn-import][import-map] rewrite: %s -> %s", rawSpec.c_str(), - normalizedSpec.c_str()); - } - // 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 != 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()); - } + case ModuleResolution::Kind::kUnresolved: + return rejectWithMessage(UnresolvedModuleMessage(resolution)); + case ModuleResolution::Kind::kHttp: + case ModuleResolution::Kind::kBlob: + case ModuleResolution::Kind::kFile: + break; } - // Re-use the static resolver to locate / compile the module. + // An http(s) or blob: module is keyed and fetched by its URL; a file module + // is named in import()'s own failure messages by the specifier after + // import-map rewriting. + const std::string normalizedSpec = + resolution.kind == ModuleResolution::Kind::kFile ? resolution.specifier : resolution.url; + NSString* specStr = tns::ToNSString(normalizedSpec); + try { // ── Blob URL support (e.g., blob:nativescript/) ── // Also useful for HMR updates where we can load a blob URL // We retrieve the blob content from the global BLOB_STORE via URL.InternalAccessor.getData() // and compile/execute it as an ES module. - if (!normalizedSpec.empty() && StartsWith(normalizedSpec, "blob:nativescript/")) { - // The blob store is keyed by the bare object URL. A file importer's own - // blob specifier reaches it without query or fragment; an HTTP - // importer's, and an import-map target, as written. - if (!importerIsHttp && normalizedSpec == rawSpec) { - normalizedSpec = normalizedSpec.substr(0, normalizedSpec.find_first_of("?#")); - } + if (resolution.kind == ModuleResolution::Kind::kBlob) { const std::string blobRegistryKey = CanonicalizeRegistryKey(normalizedSpec); TNS_DEBUG(Esm, "[dyn-import][blob] trying blob URL %s key=%s", normalizedSpec.c_str(), @@ -3509,7 +3519,7 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local // If spec is an HTTP(S) URL, try HTTP fetch+compile directly // Security: HttpFetchModule gates remote module access centrally. - if (dynamicResolution.kind == ModuleResolution::Kind::kHttp) { + if (resolution.kind == ModuleResolution::Kind::kHttp) { TNS_DEBUG(Esm, "[dyn-import][http-loader] trying URL %s", normalizedSpec.c_str()); std::string key = CanonicalizeNormalizedHttpUrlKey(normalizedSpec); // Volatile pattern check: if the URL matches any configured volatile @@ -3697,98 +3707,25 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local return scope.Escape(resolver->GetPromise()); } - // The tail below re-resolves with no referrer and joins relative - // specifiers onto the referrer as a path, which would let an HTTP - // importer's specifier reach '/' on disk or path-join an http - // URL. Only explicit file:// URLs may continue into it. - if (importerIsHttp && dynamicResolution.kind == ModuleResolution::Kind::kUnresolved && - !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; - v8::Local adjustedSpecifier = specifier; - if (!normalizedSpec.empty() && - (normalizedSpec.rfind("./", 0) == 0 || normalizedSpec.rfind("../", 0) == 0)) { - // Try to extract a base directory from resource_name, which is a file:// URL - v8::Local resName = resource_name; - if (!resName.IsEmpty() && resName->IsString()) { - v8::String::Utf8Value rn(isolate, resName); - std::string refUrl = *rn ? *rn : std::string(); - if (!refUrl.empty()) { - std::string refPath = FileURLToPath(refUrl); - size_t slash = refPath.find_last_of("/\\"); - std::string baseDir = - slash == std::string::npos ? std::string() : refPath.substr(0, slash + 1); - // Dropped before the join: dot segments inside a query or fragment - // would otherwise collapse into the path. - const std::string relPath = normalizedSpec.substr(0, normalizedSpec.find_first_of("?#")); - TNS_DEBUG(Esm, "[dyn-import][ref] url=%s base=%s spec=%s", refUrl.c_str(), - baseDir.c_str(), relPath.c_str()); - // Join and standardize via NSString to collapse dot-segments - @autoreleasepool { - NSString* nsBase = [NSString stringWithUTF8String:baseDir.c_str()]; - NSString* nsRel = [NSString stringWithUTF8String:relPath.c_str()]; - if (nsBase && nsRel) { - NSString* joined = [nsBase stringByAppendingPathComponent:nsRel]; - NSString* std = [joined stringByStandardizingPath]; - if (std) { - std::string fsPath = std.UTF8String; - // Convert back to a path relative to app when applicable - // Prefer absolute filesystem path; ResolveModuleCallback can handle it - adjustedSpecifier = tns::ToV8String(isolate, fsPath.c_str()); - TNS_DEBUG(Esm, "[dyn-import][normalize-rel] %s + %s -> %s", baseDir.c_str(), - relPath.c_str(), fsPath.c_str()); - } - } - } - } - } else { - TNS_DEBUG(Esm, - "[dyn-import][ref] missing resource name; cannot normalize relative spec against " - "referrer"); - } - } - - // Discovery pre-pass, the same one the static path runs: a local graph can - // reach HTTP edges, and without the walk those meet the resolver cold and - // fetch serially, one blocking round trip each. A graph with no HTTP edges - // settles inside the call, so a local-only dynamic import is unchanged — - // it neither waits nor touches the runloop. - if (dynamicResolution.kind == ModuleResolution::Kind::kFile) { - RunModuleGraphLoadPumped(isolate, context, dynamicResolution.path, - tns::kModuleEvaluateDeadlineSeconds); - } - - v8::TryCatch resolveTc(isolate); - v8::MaybeLocal maybeModule = - ResolveModuleCallback(context, adjustedSpecifier, import_assertions, refMod); - if (tns::LogCategoryEnabled(tns::LogCategory::Esm)) { - // Log the adjusted specifier we sent to the resolver - v8::String::Utf8Value adj(isolate, adjustedSpecifier); - const char* cAdj = (*adj) ? *adj : ""; - TNS_DEBUG(Esm, "[dyn-import][resolver-call] raw=%s normalized=%s adjusted=%s", - rawSpec.c_str(), normalizedSpec.c_str(), cAdj); - } + // A file module. Discovery pre-pass, the same one the static path runs: a + // local graph can reach HTTP edges, and without the walk those meet the + // resolver cold and fetch serially, one blocking round trip each. A graph + // with no HTTP edges settles inside the call, so a local-only dynamic + // import neither waits nor touches the runloop. + RunModuleGraphLoadPumped(isolate, context, resolution.path, + tns::kModuleEvaluateDeadlineSeconds); + + // The walk leaves JSON, and any module it could not compile, for this + // step, which also replaces an errored registry entry. A compile failure + // is what the promise rejects with. + v8::TryCatch loadTc(isolate); + v8::MaybeLocal maybeModule = LoadResolvedFileModule(isolate, context, resolution); if (maybeModule.IsEmpty()) { - if (resolveTc.HasCaught()) { - // Reject the promise with the thrown exception so callers don't hang - resolver->Reject(context, resolveTc.Exception()).FromMaybe(false); - return scope.Escape(resolver->GetPromise()); - } else { - // No exception thrown (debug path); reject with a helpful error - std::string msg = "Module resolution failed for dynamic import: "; - msg += normalizedSpec.empty() ? "" : normalizedSpec; - resolver->Reject(context, v8::Exception::Error(tns::ToV8String(isolate, msg.c_str()))) - .FromMaybe(false); + if (loadTc.HasCaught()) { + resolver->Reject(context, loadTc.Exception()).FromMaybe(false); return scope.Escape(resolver->GetPromise()); } + return rejectWithMessage("Module resolution failed for dynamic import: " + normalizedSpec); } v8::Local module = maybeModule.ToLocalChecked(); diff --git a/NativeScript/runtime/ModuleUrl.cpp b/NativeScript/runtime/ModuleUrl.cpp index 62340321..311ea6e6 100644 --- a/NativeScript/runtime/ModuleUrl.cpp +++ b/NativeScript/runtime/ModuleUrl.cpp @@ -117,6 +117,24 @@ std::string NormalizeHttpModuleUrl(const std::string& input) { return IsHttpRegistryKey(input) ? input : std::string(); } +std::string BlobStoreUrl(const std::string& input) { + // Fast reject only, as in NormalizeHttpModuleUrl. + size_t first = 0; + while (first < input.size() && + static_cast(input[first]) <= 0x20) { + first++; + } + if (first == input.size() || (input[first] != 'b' && input[first] != 'B')) { + return std::string(); + } + auto url = ada::parse(input, nullptr); + if (!url || url->get_protocol() != "blob:") { + return std::string(); + } + url->set_hash(""); + return std::string(url->get_href()); +} + bool HasUrlScheme(const std::string& s) { const size_t colon = s.find(':'); if (colon == 0 || colon == std::string::npos) { diff --git a/NativeScript/runtime/ModuleUrl.h b/NativeScript/runtime/ModuleUrl.h index 359d429b..e67e5b15 100644 --- a/NativeScript/runtime/ModuleUrl.h +++ b/NativeScript/runtime/ModuleUrl.h @@ -34,6 +34,11 @@ ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base); // not an http(s) URL. std::string NormalizeHttpModuleUrl(const std::string& input); +// The key the blob URL store is looked up by for `input`, per the File API's +// blob URL resolution: the URL serialized without its fragment, a query kept. +// Empty when `input` is not an absolute blob: URL. +std::string BlobStoreUrl(const std::string& input); + // Whether `s` starts with a URL scheme and ':' (`node:fs`, `blob:…`, // `http://…`) rather than being a filesystem path. bool HasUrlScheme(const std::string& s); diff --git a/TestRunner/app/tests/DynamicImportTests.js b/TestRunner/app/tests/DynamicImportTests.js index 51e70f56..56d6c443 100644 --- a/TestRunner/app/tests/DynamicImportTests.js +++ b/TestRunner/app/tests/DynamicImportTests.js @@ -131,7 +131,7 @@ describe("import() resolution table", function () { ["esm", "./leaf.mjs#f", "ok:leaf"], ["esm", "ns-pin-mapped", "ok:leaf"], ["esm", "ns-pin-relative-target", "ok:leaf"], - ["esm", "ns-pin-chain", "ok:leaf"], + ["esm", "ns-pin-chain", "rejected:Error:Cannot find module 'ns-pin-mapped' (tried /ns-pin-mapped)"], ["esm", "ns-pin-dir/index.mjs", "ok:dir-index"], ["esm", "ns-pin-unmapped", "rejected:Error:Cannot find module 'ns-pin-unmapped' (tried /ns-pin-unmapped)"], ["esm", "~/tests/esm/import-pin/leaf.mjs", "ok:leaf"], @@ -145,9 +145,9 @@ describe("import() resolution table", function () { ["esm", "node:url", "ok:keys=URL,URLSearchParams,default"], ["esm", "ns:import-pin-missing", "rejected:Error:No such built-in module: ns:import-pin-missing"], ["esm", function () { return blobUrl; }, "ok:blob"], - ["esm", function () { return blobUrl + "?x"; }, "ok:blob"], + ["esm", function () { return blobUrl + "?x"; }, "rejected:Error:Blob not found: ?x"], ["esm", function () { return blobUrl + "#f"; }, "ok:blob"], - ["esm", "./missing.mjs", "rejected:Error:Cannot find module '/app/tests/esm/import-pin/missing.mjs' (tried /tests/esm/import-pin/missing.mjs)"], + ["esm", "./missing.mjs", "rejected:Error:Cannot find module './missing.mjs' (tried /tests/esm/import-pin/missing.mjs)"], ["esm", "~/tests/esm/import-pin/missing.mjs", "rejected:Error:Cannot find module '~/tests/esm/import-pin/missing.mjs' (tried /app/tests/esm/import-pin/missing.mjs)"], ["esm", "./syntax-error.mjs", "rejected:SyntaxError:Unexpected token ';'"], ["esm", "./link-export.mjs", "rejected:Error:Failed to instantiate module: ./link-export.mjs \u2014 SyntaxError: The requested module './leaf.mjs' does not provide an export named 'missingExport'"], @@ -166,7 +166,7 @@ describe("import() resolution table", function () { ["cjs", "./dir", "ok:dir-index"], ["cjs", "ns-pin-mapped", "ok:leaf"], ["cjs", "ns-pin-relative-target", "ok:leaf"], - ["cjs", "ns-pin-chain", "ok:leaf"], + ["cjs", "ns-pin-chain", "rejected:Error:Cannot find module 'ns-pin-mapped' (tried /ns-pin-mapped)"], ["cjs", "ns-pin-unmapped", "rejected:Error:Cannot find module 'ns-pin-unmapped' (tried /ns-pin-unmapped)"], ["cjs", "~/tests/esm/import-pin/leaf.mjs", "ok:leaf"], ["cjs", "/tests/esm/import-pin/leaf.mjs", "ok:leaf"], @@ -174,15 +174,15 @@ describe("import() resolution table", function () { ["cjs", "./data.json", "ok:default.name=json"], ["cjs", "ns:module", "ok:keys=canonicalizeHttpUrlKey,configureLoader,createPumpingRequire"], ["cjs", function () { return blobUrl; }, "ok:blob"], - ["cjs", function () { return blobUrl + "?x"; }, "ok:blob"], + ["cjs", function () { return blobUrl + "?x"; }, "rejected:Error:Blob not found: ?x"], ["cjs", function () { return blobUrl + "#f"; }, "ok:blob"], - ["cjs", "./missing.mjs", "rejected:Error:Cannot find module '/app/tests/esm/import-pin/missing.mjs' (tried /tests/esm/import-pin/missing.mjs)"], + ["cjs", "./missing.mjs", "rejected:Error:Cannot find module './missing.mjs' (tried /tests/esm/import-pin/missing.mjs)"], ["cjs", "./throws.mjs", "rejected:TypeError:import-pin evaluation error"], - ["newFunction", "./leaf.mjs", "rejected:Error:Cannot find module '/app/tests/leaf.mjs' (tried /tests/leaf.mjs)"], - ["newFunction", "./tests/esm/import-pin/leaf.mjs", "rejected:Error:Cannot find module '/app/tests/tests/esm/import-pin/leaf.mjs' (tried /tests/tests/esm/import-pin/leaf.mjs)"], + ["newFunction", "./leaf.mjs", "rejected:Error:Cannot find module './leaf.mjs' (tried /tests/leaf.mjs)"], + ["newFunction", "./tests/esm/import-pin/leaf.mjs", "rejected:Error:Cannot find module './tests/esm/import-pin/leaf.mjs' (tried /tests/tests/esm/import-pin/leaf.mjs)"], ["newFunction", "ns-pin-mapped", "ok:leaf"], - ["newFunction", "ns-pin-relative-target", "rejected:Error:Cannot find module '/app/tests/leaf.mjs' (tried /tests/leaf.mjs)"], + ["newFunction", "ns-pin-relative-target", "rejected:Error:Cannot find module './leaf.mjs' (tried /tests/leaf.mjs)"], ["newFunction", "ns-pin-unmapped", "rejected:Error:Cannot find module 'ns-pin-unmapped' (tried /ns-pin-unmapped)"], ["newFunction", "~/tests/esm/import-pin/leaf.mjs", "ok:leaf"], ["newFunction", "/tests/esm/import-pin/leaf.mjs", "ok:leaf"], @@ -190,8 +190,8 @@ describe("import() resolution table", function () { ["newFunction", "ns:module", "ok:keys=canonicalizeHttpUrlKey,configureLoader,createPumpingRequire"], ["newFunction", function () { return blobUrl + "#f"; }, "ok:blob"], - ["indirectEval", "./leaf.mjs", "rejected:Error:Cannot find module '/app/tests/leaf.mjs' (tried /tests/leaf.mjs)"], - ["indirectEval", "./tests/esm/import-pin/leaf.mjs", "rejected:Error:Cannot find module '/app/tests/tests/esm/import-pin/leaf.mjs' (tried /tests/tests/esm/import-pin/leaf.mjs)"], + ["indirectEval", "./leaf.mjs", "rejected:Error:Cannot find module './leaf.mjs' (tried /tests/leaf.mjs)"], + ["indirectEval", "./tests/esm/import-pin/leaf.mjs", "rejected:Error:Cannot find module './tests/esm/import-pin/leaf.mjs' (tried /tests/tests/esm/import-pin/leaf.mjs)"], ["indirectEval", "~/tests/esm/import-pin/leaf.mjs", "ok:leaf"], ]; @@ -211,7 +211,7 @@ describe("import() resolution table", function () { ["http", "ns:module", "ok:keys=canonicalizeHttpUrlKey,configureLoader,createPumpingRequire"], ["http", function () { return blobUrl; }, "ok:blob"], ["http", function () { return blobUrl + "?x"; }, "rejected:Error:Blob not found: ?x"], - ["http", function () { return blobUrl + "#f"; }, "rejected:Error:Blob not found: #f"], + ["http", function () { return blobUrl + "#f"; }, "ok:blob"], ]; var rowCount = 0; diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 754208e1..e13512f4 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -995,8 +995,7 @@ 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 +scheme (`data:`, `file:/x`) is never looked up on disk. 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 @@ -1006,9 +1005,19 @@ From a file module, `import 'pkg?x'` and `import('pkg?x')` both look `pkg?x` up in the import map, exactly as written: an entry for `pkg` does not match it, while a `pkg/` prefix entry matches `pkg/x.js?v=1`. A query or fragment is dropped only when a file path is derived, so `./x.js?v=1` and `./x.js#f` load -`x.js`. An import-map target should not itself be a key of the map: a file -module's `import()` may look a target up a second time (an HTTP module's -follows one entry, as its static import does). +`x.js`. + +`import()` resolves its specifier once, by the same rules and against the same +importer as a static import from the module that calls it, so the import map is +applied once: an entry's target is never looked up in the map again, and a +`./x` or `../x` that names no file is reported as written +(`Cannot find module './x' (tried )`), as a static import reports it. + +`import()` of a `blob:` URL loads from the blob store, from any importer. The +store is looked up the way the File API resolves a blob URL: without the +fragment and with the query, so `blobUrl + '#f'` loads the blob and +`blobUrl + '?x'` rejects with `Blob not found`. A static import of a `blob:` +URL does not resolve. ### The `require()` specifier From f1009a35302b095f1540b29af78457c6ad696bda Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 15:14:04 -0300 Subject: [PATCH 4/7] feat(runtime): make a file module's query part of its identity As in browsers and Node, ./x.mjs?v=1, ./x.mjs?v=2 and ./x.mjs are now three module instances of one file, each evaluated once, from static imports and import() alike. A file module's registry key is its canonical path plus the specifier's query as the URL parser serializes it (after import-map rewriting); the fragment is not part of it, as for http(s) modules. An empty query (x.mjs?) is distinct from none, as the URL standard keeps it. import.meta.url carries the query; import.meta.dirname, relative imports, import-map scopes, createRequire(import.meta.url), relative Worker paths, the inspector's script-to-file mapping and the code cache read the file path, through one function that turns a key or reported URL into a path. getLoadedModuleUrls() keeps leaving file modules out when a query contains '://'. The entry module, worker scripts and require() of an ES module load the instance without a query. --- NativeScript/inspector/JsV8InspectorClient.mm | 8 +- NativeScript/runtime/ModuleInternal.h | 7 +- NativeScript/runtime/ModuleInternal.mm | 5 +- .../runtime/ModuleInternalCallbacks.mm | 104 ++++++----- NativeScript/runtime/ModuleUrl.cpp | 36 +++- NativeScript/runtime/ModuleUrl.h | 18 +- NativeScript/runtime/Runtime.mm | 13 +- NativeScript/runtime/Worker.mm | 5 +- TestRunner/app/tests/DynamicImportTests.js | 163 ++++++++++++++++++ .../app/tests/esm/query-identity/counted.mjs | 4 + .../app/tests/esm/query-identity/importer.mjs | 3 + .../app/tests/esm/query-identity/probe.mjs | 20 +++ .../tests/esm/query-identity/query-worker.js | 1 + .../esm/query-identity/scoped-target.mjs | 1 + .../tests/esm/query-identity/sibling-cjs.js | 1 + .../app/tests/esm/query-identity/sibling.mjs | 1 + .../esm/query-identity/static-mapped.mjs | 1 + .../tests/esm/query-identity/static-v1.mjs | 1 + docs/ns-builtin-modules.md | 25 ++- 19 files changed, 352 insertions(+), 65 deletions(-) create mode 100644 TestRunner/app/tests/esm/query-identity/counted.mjs create mode 100644 TestRunner/app/tests/esm/query-identity/importer.mjs create mode 100644 TestRunner/app/tests/esm/query-identity/probe.mjs create mode 100644 TestRunner/app/tests/esm/query-identity/query-worker.js create mode 100644 TestRunner/app/tests/esm/query-identity/scoped-target.mjs create mode 100644 TestRunner/app/tests/esm/query-identity/sibling-cjs.js create mode 100644 TestRunner/app/tests/esm/query-identity/sibling.mjs create mode 100644 TestRunner/app/tests/esm/query-identity/static-mapped.mjs create mode 100644 TestRunner/app/tests/esm/query-identity/static-v1.mjs diff --git a/NativeScript/inspector/JsV8InspectorClient.mm b/NativeScript/inspector/JsV8InspectorClient.mm index 82743339..41e08c34 100644 --- a/NativeScript/inspector/JsV8InspectorClient.mm +++ b/NativeScript/inspector/JsV8InspectorClient.mm @@ -16,6 +16,7 @@ #include "Helpers.h" #include "InspectorServer.h" #include "JsV8InspectorClient.h" +#include "ModuleUrl.h" #include "NativeScriptException.h" #include "NativeScriptPlatform.h" #include "RuntimeConfig.h" @@ -92,7 +93,7 @@ bool ShouldRewriteSourceMapURLs() { std::string path; if (sourceMapURL.rfind("file://", 0) == 0) { - path = sourceMapURL.substr(strlen("file://")); + path = tns::FileModulePath(sourceMapURL); } else if (sourceMapURL[0] == '/') { path = sourceMapURL; } else { @@ -102,8 +103,7 @@ bool ShouldRewriteSourceMapURLs() { return message; } @autoreleasepool { - NSString* scriptPath = - [NSString stringWithUTF8String:scriptUrl.substr(strlen("file://")).c_str()]; + NSString* scriptPath = [NSString stringWithUTF8String:tns::FileModulePath(scriptUrl).c_str()]; NSString* mapPath = [NSString stringWithUTF8String:sourceMapURL.c_str()]; if (scriptPath != nil && mapPath != nil) { NSString* resolved = [[[scriptPath stringByDeletingLastPathComponent] @@ -1008,7 +1008,7 @@ bool GetInt32(const json& value, long long& out) { if (url.rfind(kSourceMapScheme, 0) == 0) { path = url.substr(strlen(kSourceMapScheme)); } else if (url.rfind("file://", 0) == 0) { - path = url.substr(strlen("file://")); + path = tns::FileModulePath(url); } else { // Reply with a protocol error (not success:false) so DevTools falls back // to loading the resource from the frontend host, which is the diff --git a/NativeScript/runtime/ModuleInternal.h b/NativeScript/runtime/ModuleInternal.h index 29ad542e..f2e1df83 100644 --- a/NativeScript/runtime/ModuleInternal.h +++ b/NativeScript/runtime/ModuleInternal.h @@ -79,9 +79,12 @@ class ModuleInternal { // On compile failure the exception is left pending on the isolate (or a // NativeScriptException is thrown for setup failures) and the result is // empty. This is the resolver's file loader: the resolver must only ever - // hand V8 a compiled module — evaluation order belongs to V8. + // hand V8 a compiled module — evaluation order belongs to V8. `query` is + // the module key's query: it is part of the reported URL (script origin, + // import.meta.url), never of the file read or of the code cache's name. static v8::MaybeLocal CompileFileEsModule( - v8::Isolate* isolate, const std::string& path); + v8::Isolate* isolate, const std::string& path, + const std::string& query = std::string()); // The entry module's still-pending evaluation promise, or empty when // evaluation has settled (classic scripts settle synchronously and always // return empty). Callers use this after RunModule to observe a top-level diff --git a/NativeScript/runtime/ModuleInternal.mm b/NativeScript/runtime/ModuleInternal.mm index 4e4da944..ff07dfaa 100644 --- a/NativeScript/runtime/ModuleInternal.mm +++ b/NativeScript/runtime/ModuleInternal.mm @@ -1009,7 +1009,8 @@ ScriptOrigin origin(urlString, return script; } -MaybeLocal ModuleInternal::CompileFileEsModule(Isolate* isolate, const std::string& path) { +MaybeLocal ModuleInternal::CompileFileEsModule(Isolate* isolate, const std::string& path, + const std::string& query) { std::string canonicalPath = NormalizePath(path); struct stat st; @@ -1017,7 +1018,7 @@ ScriptOrigin origin(urlString, throw NativeScriptException("Cannot find module " + canonicalPath); } - const std::string url = ReportedModuleUrl(canonicalPath); + const std::string url = ReportedModuleUrl(canonicalPath + query); Local sourceText = ModuleInternal::WrapModuleContent(isolate, canonicalPath); auto* cacheData = ModuleInternal::LoadScriptCache(canonicalPath, ScriptCacheKind::kEsModule); diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 8b71b72a..63c58355 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -782,7 +782,7 @@ static bool ShouldTraceRegistryKey(const std::string& rawKey, const std::string& registryKey = CanonicalizeNormalizedHttpUrlKey(httpUrl); classification = "http"; } else if (StartsWith(key, "file://")) { - registryKey = NormalizePath(FileURLToPath(key)); + registryKey = NormalizePath(FileURLToPath(key)) + ModuleQuery(key); classification = "file-url"; } else if (StartsWith(key, "blob:")) { registryKey = key; @@ -798,7 +798,10 @@ static bool ShouldTraceRegistryKey(const std::string& rawKey, const std::string& classification = "custom-scheme"; traceEvenWithoutChange = true; } else { - registryKey = NormalizePath(key); + // Standardizing must not reach the query: its dot segments and + // slashes are not path syntax. + const std::string path = FileModulePath(key); + registryKey = NormalizePath(path) + key.substr(path.size()); } } @@ -1145,15 +1148,18 @@ static bool IsVolatileUrl(const std::string& url) { // // A scope key matches as a plain prefix of `referrerKey`, the importing // module's canonical registry key: an absolute http(s) URL for a served -// module, or a canonical absolute path for a file. That key is this runtime's -// analogue of the web's resolved referrer URL, which is what scope prefixes -// match there. Ending a scope key with '/' keeps it on a directory boundary, -// exactly as on the web. -static std::string LookupImportMap(const std::string& specifier, const std::string& referrerKey) { +// module, or a canonical absolute path for a file — without the query a file +// module's key may carry, so a scope matches every instance of one file alike. +// That key is this runtime's analogue of the web's resolved referrer URL, +// which is what scope prefixes match there. Ending a scope key with '/' keeps +// it on a directory boundary, exactly as on the web. +static std::string LookupImportMap(const std::string& specifier, const std::string& importerKey) { const LoaderVocabulary* vocabulary = VocabularyForCurrentIsolate(); if (vocabulary == nullptr) { return ""; } + const std::string importerPath = FileModulePath(importerKey); + const std::string& referrerKey = importerPath.empty() ? importerKey : importerPath; for (const auto& scope : vocabulary->importMap.scopes) { const std::string& prefix = scope.first; if (referrerKey.size() < prefix.size() || referrerKey.compare(0, prefix.size(), prefix) != 0) { @@ -1571,7 +1577,11 @@ static void DrainStreamedCompilesForIsolate(v8::Isolate* isolate) { Kind kind = Kind::kUnresolved; std::string url; // kHttp; kBlob without its fragment - std::string path; // kFile + std::string path; // kFile: what is read, probed and code-cached + // kFile: the module's identity — the canonical path plus the specifier's + // query (ModuleQuery), so one file imported with two queries is two modules. + std::string key; + std::string query; // kFile: the query `key` carries, '?' included 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 @@ -1779,8 +1789,10 @@ static ModuleResolution ResolveSpecifierToPath( const bool specIsRelative = spec[0] == '.'; const bool specIsRootAbs = spec[0] == '/'; - size_t slash = referrerKey.find_last_of("/\\"); - std::string baseDir = slash == std::string::npos ? "" : referrerKey.substr(0, slash + 1); + const std::string referrerPath = FileModulePath(referrerKey); + const std::string& referrerBase = referrerPath.empty() ? referrerKey : referrerPath; + size_t slash = referrerBase.find_last_of("/\\"); + std::string baseDir = slash == std::string::npos ? "" : referrerBase.substr(0, slash + 1); if (referrerKey.empty() && specIsRelative) { TNS_DEBUG(Esm, "[resolver] no registered referrer for relative import '%s'; resolving " @@ -1803,10 +1815,9 @@ static ModuleResolution ResolveSpecifierToPath( } // 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 - // the same way instead of probing for a file literally called 'x.js?v=1'. - // HTTP specifiers returned above keep their query: there it is identity. + // `import './x.js?v=1'` reads x.js. The query stays part of the module's + // identity, in its key; the fragment does not, as for an http(s) module. + const std::string query = ModuleQuery(spec); { size_t queryOrHash = spec.find_first_of("?#"); if (queryOrHash != std::string::npos) { @@ -1931,6 +1942,8 @@ static ModuleResolution ResolveSpecifierToPath( if (IsRegularFile(absPath)) { result.kind = ModuleResolution::Kind::kFile; result.path = absPath; + result.query = query; + result.key = CanonicalizeRegistryKey(absPath) + query; } return result; } @@ -2123,20 +2136,23 @@ static void AsyncGraphOnFetchCompleted(const std::shared_ptr& lo // owns the error message for a module that will not compile. Leaving it // unregistered is exactly what makes those paths run and report. static void AsyncGraphCompileLocalModule(const std::shared_ptr& load, - v8::Local context, const std::string& path, - const std::string& key) { + v8::Local context, + const ModuleResolution& resolution) { v8::Isolate* isolate = load->isolate; auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) { return; } + const std::string& path = resolution.path; + const std::string& key = resolution.key; v8::Local mod; { v8::TryCatch tcCompile(isolate); bool compiled = false; try { - compiled = tns::ModuleInternal::CompileFileEsModule(isolate, path).ToLocal(&mod); + compiled = + tns::ModuleInternal::CompileFileEsModule(isolate, path, resolution.query).ToLocal(&mod); } catch (NativeScriptException& ex) { TNS_DEBUG(Esm, "[graph][local-compile-fail] %s %s (left to the resolver)", path.c_str(), ex.getMessage().c_str()); @@ -2159,11 +2175,10 @@ 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; - // 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); + // The key the resolver looks the module up by, so the walk registers every + // module under it; a resolved URL is already spelled, so only its + // vocabulary is applied. + const std::string key = isHttp ? CanonicalizeNormalizedHttpUrlKey(target) : resolution.key; if (!load->visited.insert(key).second) { return; } @@ -2201,7 +2216,7 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, } v8::Local context = load->context.Get(isolate); if (!context.IsEmpty()) { - AsyncGraphCompileLocalModule(load, context, target, key); + AsyncGraphCompileLocalModule(load, context, resolution); } return; } @@ -2246,18 +2261,22 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, } // Classify a walk root. The root arrives already resolved — an absolute URL -// from the HTTP loader, or a canonical path from LoadESModule — so it needs -// only scheme dispatch, not the full specifier resolution. +// from the HTTP loader, a canonical path from LoadESModule, or a file module's +// registry key from import() — so it needs only scheme dispatch, not the full +// specifier resolution. static ModuleResolution ResolutionForRoot(const std::string& root) { ModuleResolution resolution; resolution.specifier = root; const std::string httpUrl = NormalizeHttpModuleUrl(root); + const std::string path = FileModulePath(root); if (!httpUrl.empty()) { resolution.kind = ModuleResolution::Kind::kHttp; resolution.url = httpUrl; - } else if (IsRegularFile(root)) { + } else if (!path.empty() && IsRegularFile(path)) { resolution.kind = ModuleResolution::Kind::kFile; - resolution.path = root; + resolution.path = path; + resolution.key = CanonicalizeRegistryKey(root); + resolution.query = root.substr(path.size()); } // Anything else stays kUnresolved: there is nothing to walk, and the // caller's own load path reports why. @@ -2427,7 +2446,8 @@ void RemoveModuleFromRegistry(v8::Isolate* isolate, const std::string& canonical for (const auto& entry : registry) { const std::string& key = entry.first; - if (key.empty()) continue; + // A file module's key is a path, whatever its query contains. + if (key.empty() || !FileModulePath(key).empty()) continue; if (StartsWith(key, "blob:") || key.find("://") != std::string::npos) { urls.push_back(key); } @@ -2786,10 +2806,10 @@ static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate, static v8::MaybeLocal CompileJsonAsEsModule(v8::Isolate* isolate, v8::Local context, const std::string& absPath, - const std::string& registryAbsPath) { + const std::string& registryKey) { const std::string jsonText = tns::ReadText(absPath); - const std::string url = ReportedModuleUrl(absPath); - return CompileJsonTextAsEsModule(isolate, context, jsonText, registryAbsPath, url); + const std::string url = ReportedModuleUrl(registryKey); + return CompileJsonTextAsEsModule(isolate, context, jsonText, registryKey, url); } // The file module `resolution` names: its live registry entry, or the file @@ -2805,11 +2825,11 @@ static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate, } auto& registry = moduleState->registry; const std::string& absPath = resolution.path; - const std::string registryAbsPath = CanonicalizeRegistryKey(absPath); + const std::string& registryKey = resolution.key; // JSON imports (import data from './foo.json' with { type: 'json' }). if (absPath.size() >= 5 && absPath.compare(absPath.size() - 5, 5, ".json") == 0) { - return CompileJsonAsEsModule(isolate, context, absPath, registryAbsPath); + return CompileJsonAsEsModule(isolate, context, absPath, registryKey); } // Reuse any live, non-errored registry entry. The resolver never evaluates, @@ -2817,30 +2837,31 @@ static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate, // simply rejoins the graph V8 is currently linking — that is how import // cycles terminate, the same way Node/Blink break them with the module-map // self-insert. - auto it = registry.find(registryAbsPath); + auto it = registry.find(registryKey); if (it != registry.end()) { v8::Local existing = it->second.Get(isolate); if (!existing.IsEmpty() && existing->GetStatus() != v8::Module::kErrored) { - TNS_DEBUG(Esm, "[resolver] cache hit %s (status=%s)", absPath.c_str(), + TNS_DEBUG(Esm, "[resolver] cache hit %s (status=%s)", registryKey.c_str(), ModuleStatusToString(existing->GetStatus())); return v8::MaybeLocal(existing); } - RemoveModuleFromRegistry(isolate, absPath); + RemoveModuleFromRegistry(isolate, registryKey); } // Compile + register only. V8 is instantiating a static importer and // continues the graph walk by resolving this module's own requests next; // evaluating here would run dependencies in resolver order instead of the // spec's evaluation order. - TNS_DEBUG(Esm, "[resolver] → compile-register %s", absPath.c_str()); + TNS_DEBUG(Esm, "[resolver] → compile-register %s", registryKey.c_str()); try { v8::Local mod; - if (!tns::ModuleInternal::CompileFileEsModule(isolate, absPath).ToLocal(&mod)) { + if (!tns::ModuleInternal::CompileFileEsModule(isolate, absPath, resolution.query) + .ToLocal(&mod)) { // The compile exception is pending on the isolate; V8 fails the // importer's instantiation with it. return v8::MaybeLocal(); } - SetRegisteredModule(*moduleState, isolate, registryAbsPath, mod); + SetRegisteredModule(*moduleState, isolate, registryKey, mod); return v8::MaybeLocal(mod); } catch (NativeScriptException& ex) { ex.ReThrowToV8(isolate); @@ -3064,7 +3085,7 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local ResolveSpecifierToPath(resourceName, std::string(), ImportMapLookup::kSkip); switch (referrer.kind) { case ModuleResolution::Kind::kFile: - return CanonicalizeRegistryKey(referrer.path); + return referrer.key; case ModuleResolution::Kind::kHttp: case ModuleResolution::Kind::kBlob: return CanonicalizeRegistryKey(referrer.url); @@ -3712,8 +3733,7 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local // resolver cold and fetch serially, one blocking round trip each. A graph // with no HTTP edges settles inside the call, so a local-only dynamic // import neither waits nor touches the runloop. - RunModuleGraphLoadPumped(isolate, context, resolution.path, - tns::kModuleEvaluateDeadlineSeconds); + RunModuleGraphLoadPumped(isolate, context, resolution.key, tns::kModuleEvaluateDeadlineSeconds); // The walk leaves JSON, and any module it could not compile, for this // step, which also replaces an errored registry entry. A compile failure diff --git a/NativeScript/runtime/ModuleUrl.cpp b/NativeScript/runtime/ModuleUrl.cpp index 311ea6e6..5f225c56 100644 --- a/NativeScript/runtime/ModuleUrl.cpp +++ b/NativeScript/runtime/ModuleUrl.cpp @@ -169,8 +169,10 @@ std::string ReportedModuleUrl(const std::string& keyOrPath) { if (HasUrlScheme(keyOrPath)) { return keyOrPath; } - // Every occurrence, as tns::ReplaceAll removes it everywhere else. - std::string path = keyOrPath; + // Every occurrence, as tns::ReplaceAll removes it everywhere else; a + // file module key's query is not part of its path and is kept whole. + std::string path = FileModulePath(keyOrPath); + const std::string query = keyOrPath.substr(path.size()); const std::string& baseDir = RuntimeConfig.BaseDir; if (!baseDir.empty()) { for (size_t pos = path.find(baseDir); pos != std::string::npos; @@ -178,7 +180,35 @@ std::string ReportedModuleUrl(const std::string& keyOrPath) { path.erase(pos, baseDir.size()); } } - return "file://" + path; + return "file://" + path + query; +} + +std::string ModuleQuery(const std::string& specifier) { + if (specifier.find('?') == std::string::npos) { + return std::string(); + } + static const auto base = ada::parse("file:///", nullptr); + auto url = ada::parse(specifier, &base.value()); + if (!url || !url->has_search()) { + return std::string(); + } + const std::string_view search = url->get_search(); + return search.empty() ? std::string("?") : std::string(search); +} + +std::string FileModulePath(const std::string& keyOrUrl) { + // The inverse of ReportedModuleUrl's spelling, which writes the path + // verbatim (not percent-encoded) after `file://`. + if (StartsWith(keyOrUrl, "file://")) { + const std::string rest = + keyOrUrl.substr(std::char_traits::length("file://")); + return rest.substr(0, rest.find_first_of("?#")); + } + if (keyOrUrl.empty() || HasUrlScheme(keyOrUrl) || + IsHttpRegistryKey(keyOrUrl)) { + return std::string(); + } + return keyOrUrl.substr(0, keyOrUrl.find('?')); } } // namespace tns diff --git a/NativeScript/runtime/ModuleUrl.h b/NativeScript/runtime/ModuleUrl.h index e67e5b15..c26ca4c6 100644 --- a/NativeScript/runtime/ModuleUrl.h +++ b/NativeScript/runtime/ModuleUrl.h @@ -47,8 +47,22 @@ bool HasUrlScheme(const std::string& s); // import.meta.url, inspector target), from its registry key or path: an // http(s) URL as NormalizeHttpModuleUrl spells it; any other string that // carries a URL scheme unchanged; a filesystem path as `file://` plus the path -// with RuntimeConfig.BaseDir removed, `file:///app/` for an empty one. The only -// place a `file://` URL is built from a path. +// with RuntimeConfig.BaseDir removed, then a file module key's query, +// `file:///app/` for an empty one. The only place a `file://` URL is built from +// a path. std::string ReportedModuleUrl(const std::string& keyOrPath); +// The query of `specifier` as the URL parser serializes it, '?' included, the +// fragment dropped: what a file module's registry key carries after its path. +// "?" for an empty query, which the URL standard keeps distinct from none; +// empty when there is no query. +std::string ModuleQuery(const std::string& specifier); + +// The filesystem path a file module's registry key, or a `file://` URL as +// ReportedModuleUrl spells it, names: the key or URL path without its query or +// fragment. A URL's path is relative to RuntimeConfig.BaseDir. Empty for a key +// or URL with any other scheme. The one way a module key or script URL is +// read as a path. +std::string FileModulePath(const std::string& keyOrUrl); + } // namespace tns diff --git a/NativeScript/runtime/Runtime.mm b/NativeScript/runtime/Runtime.mm index 89995468..de66d255 100644 --- a/NativeScript/runtime/Runtime.mm +++ b/NativeScript/runtime/Runtime.mm @@ -66,10 +66,12 @@ // filesystem. Their identity is the scheme + body itself; // `import.meta.url` keeps that string unchanged. // -// 3. Absolute filesystem path — `/Users/.../app/src/foo.js`. The -// production / non-HMR dev shape. Strip the runtime base dir to -// recover the canonical "/app/" shape JS consumers see, then -// prepend `file://` so the result is a well-formed URL. +// 3. Absolute filesystem path — `/Users/.../app/src/foo.js`, followed by +// the query the module was imported with, if any. The production / +// non-HMR dev shape. Strip the runtime base dir to recover the +// canonical "/app/" shape JS consumers see, then prepend +// `file://` so the result is a well-formed URL; the query stays on the +// url and never reaches dirname. // static void InitializeImportMetaObject(Local context, Local module, Local meta) { @@ -99,7 +101,8 @@ static void InitializeImportMetaObject(Local context, Local mod if (modulePath.empty()) { dirname = "/app"; } else { - const std::string appRelative = tns::ReplaceAll(modulePath, RuntimeConfig.BaseDir, ""); + const std::string appRelative = + tns::ReplaceAll(tns::FileModulePath(modulePath), RuntimeConfig.BaseDir, ""); size_t lastSlash = appRelative.find_last_of("/\\"); if (lastSlash != std::string::npos && lastSlash > 0) { dirname = appRelative.substr(0, lastSlash); diff --git a/NativeScript/runtime/Worker.mm b/NativeScript/runtime/Worker.mm index ed107381..ad49e9ef 100644 --- a/NativeScript/runtime/Worker.mm +++ b/NativeScript/runtime/Worker.mm @@ -405,10 +405,7 @@ throw NativeScriptException("Cannot resolve worker path \"" + workerPath + } workerPath = resolved.href; } else if (!callerScript.empty()) { - const std::string filePrefix = "file://"; - if (callerScript.rfind(filePrefix, 0) == 0) { - callerScript = callerScript.substr(filePrefix.size()); - } + callerScript = FileModulePath(callerScript); // Script origins are relative to the app bundle root (BaseDir) if (!callerScript.empty() && callerScript[0] == '/' && callerScript.rfind(RuntimeConfig.BaseDir, 0) != 0) { diff --git a/TestRunner/app/tests/DynamicImportTests.js b/TestRunner/app/tests/DynamicImportTests.js index 56d6c443..f23ab070 100644 --- a/TestRunner/app/tests/DynamicImportTests.js +++ b/TestRunner/app/tests/DynamicImportTests.js @@ -283,3 +283,166 @@ describe("import() resolution table", function () { }); }); }); + +// A file module's query is part of its identity, as in browsers and Node; its +// fragment is not, as for an http(s) module here. +describe("file module instances per query", function () { + var nsModule = require("ns:module"); + var dir = "~/tests/esm/query-identity/"; + var urlBase = "file:///app/tests/esm/query-identity/"; + + function evaluations(url) { + var counts = globalThis.__queryIdentityEvaluations || {}; + return counts[url] || 0; + } + + function load(spec) { + return import(dir + "importer.mjs").then(function (m) { return m.load(spec); }); + } + + function fail(done) { + return function (e) { + expect("rejected: " + String((e && e.message) || e)).toBe("resolved"); + done(); + }; + } + + afterEach(function () { + nsModule.configureLoader({ importMap: { imports: {} } }); + }); + + it("gives a static import and an import() with one query one instance", function (done) { + Promise.all([import(dir + "static-v1.mjs"), load("./counted.mjs?v=1")]).then(function (r) { + expect(r[0].dep).toBe(r[1]); + expect(r[1].url).toBe(urlBase + "counted.mjs?v=1"); + expect(evaluations(urlBase + "counted.mjs?v=1")).toBe(1); + done(); + }, fail(done)); + }); + + it("gives two queries, an empty query and none four instances, each evaluated once", + function (done) { + Promise.all([load("./counted.mjs?v=1"), load("./counted.mjs?v=2"), load("./counted.mjs?"), + load("./counted.mjs")]).then(function (r) { + expect(r.map(function (ns) { return ns.url; })).toEqual([ + urlBase + "counted.mjs?v=1", + urlBase + "counted.mjs?v=2", + urlBase + "counted.mjs?", + urlBase + "counted.mjs", + ]); + expect([r[0] === r[1], r[0] === r[3], r[1] === r[3], r[2] === r[3]]) + .toEqual([false, false, false, false]); + expect(r.map(function (ns) { return evaluations(ns.url); })).toEqual([1, 1, 1, 1]); + done(); + }, fail(done)); + }); + + it("keeps the query of an import-map target in the module's identity", function (done) { + nsModule.configureLoader({ + importMap: { imports: { "ns-query-identity-mapped": dir + "counted.mjs?v=map" } }, + }); + Promise.all([import(dir + "static-mapped.mjs"), load("ns-query-identity-mapped"), + load("./counted.mjs?v=map")]).then(function (r) { + expect([r[0].dep === r[1], r[1] === r[2]]).toEqual([true, true]); + expect(r[1].url).toBe(urlBase + "counted.mjs?v=map"); + expect(evaluations(urlBase + "counted.mjs?v=map")).toBe(1); + done(); + }, fail(done)); + }); + + it("does not split instances by fragment", function (done) { + Promise.all([load("./counted.mjs#a"), load("./counted.mjs#b"), load("./counted.mjs"), + load("./counted.mjs?v=1#c"), load("./counted.mjs?v=1")]).then(function (r) { + expect([r[0] === r[2], r[1] === r[2], r[3] === r[4]]).toEqual([true, true, true]); + expect([r[0].url, r[3].url]).toEqual([urlBase + "counted.mjs", urlBase + "counted.mjs?v=1"]); + done(); + }, fail(done)); + }); + + it("gives require() of the file the instance without a query", function (done) { + Promise.all([load("./counted.mjs"), load("./counted.mjs?v=1")]).then(function (r) { + var required = require("./esm/query-identity/counted.mjs"); + expect([required === r[0], required === r[1]]).toEqual([true, false]); + done(); + }, fail(done)); + }); + + describe("inside a module imported with a query containing '/', '..' and '://'", function () { + var query = "?a=/../../y&u=http://h/z"; + var probe; + + beforeAll(function (done) { + var scopes = {}; + scopes[__dirname + "/esm/query-identity/"] = { + "ns-query-identity-scoped": dir + "scoped-target.mjs", + }; + nsModule.configureLoader({ importMap: { imports: {}, scopes: scopes } }); + load("./probe.mjs" + query).then(function (ns) { + probe = ns; + done(); + }, function (e) { + probe = { error: String((e && e.message) || e) }; + done(); + }); + }); + + it("loads", function () { + expect(probe.error).toBeUndefined(); + }); + + it("reports the query in import.meta.url and not in import.meta.dirname", function () { + expect(probe.url).toBe(urlBase + "probe.mjs" + query); + expect(probe.search).toBe(query); + expect(probe.dirname).toBe("/app/tests/esm/query-identity"); + }); + + it("resolves relative imports against the module's directory", function (done) { + expect(probe.staticSibling).toBe("sibling"); + expect(probe.required).toBe("sibling-cjs"); + probe.dynamicSibling().then(function (name) { + expect(name).toBe("sibling"); + done(); + }, fail(done)); + }); + + it("matches an import-map scope on the module's directory", function (done) { + var scopes = {}; + scopes[__dirname + "/esm/query-identity/"] = { + "ns-query-identity-scoped": dir + "scoped-target.mjs", + }; + nsModule.configureLoader({ importMap: { imports: {}, scopes: scopes } }); + probe.scopedImport().then(function (name) { + expect(name).toBe("scoped-target"); + done(); + }, fail(done)); + }); + + it("starts a relative worker from the module's directory", function (done) { + var worker = probe.startWorker(); + var timer = setTimeout(function () { + worker.terminate(); + expect("no message").toBe("query-worker-ready"); + done(); + }, 10000); + worker.onerror = function (e) { + clearTimeout(timer); + worker.terminate(); + expect("error: " + String((e && e.message) || e)).toBe("query-worker-ready"); + done(); + }; + worker.onmessage = function (msg) { + clearTimeout(timer); + worker.terminate(); + expect(msg.data).toBe("query-worker-ready"); + done(); + }; + }); + + it("is not listed by getLoadedModuleUrls, like any file module", function () { + var listed = nsModule.getLoadedModuleUrls().filter(function (u) { + return u.indexOf("query-identity") >= 0; + }); + expect(listed).toEqual([]); + }); + }); +}); diff --git a/TestRunner/app/tests/esm/query-identity/counted.mjs b/TestRunner/app/tests/esm/query-identity/counted.mjs new file mode 100644 index 00000000..89601e0a --- /dev/null +++ b/TestRunner/app/tests/esm/query-identity/counted.mjs @@ -0,0 +1,4 @@ +const counts = (globalThis.__queryIdentityEvaluations ??= {}); +counts[import.meta.url] = (counts[import.meta.url] || 0) + 1; + +export const url = import.meta.url; diff --git a/TestRunner/app/tests/esm/query-identity/importer.mjs b/TestRunner/app/tests/esm/query-identity/importer.mjs new file mode 100644 index 00000000..0712d2d4 --- /dev/null +++ b/TestRunner/app/tests/esm/query-identity/importer.mjs @@ -0,0 +1,3 @@ +export function load(spec) { + return import(spec); +} diff --git a/TestRunner/app/tests/esm/query-identity/probe.mjs b/TestRunner/app/tests/esm/query-identity/probe.mjs new file mode 100644 index 00000000..0b7e5232 --- /dev/null +++ b/TestRunner/app/tests/esm/query-identity/probe.mjs @@ -0,0 +1,20 @@ +import { createRequire } from "ns:module"; +import { name as siblingName } from "./sibling.mjs"; + +export const url = import.meta.url; +export const search = new URL(import.meta.url).search; +export const dirname = import.meta.dirname; +export const staticSibling = siblingName; +export const required = createRequire(import.meta.url)("./sibling-cjs.js").name; + +export function dynamicSibling() { + return import("./sibling.mjs").then((m) => m.name); +} + +export function scopedImport() { + return import("ns-query-identity-scoped").then((m) => m.name); +} + +export function startWorker() { + return new Worker("./query-worker.js"); +} diff --git a/TestRunner/app/tests/esm/query-identity/query-worker.js b/TestRunner/app/tests/esm/query-identity/query-worker.js new file mode 100644 index 00000000..3d945d59 --- /dev/null +++ b/TestRunner/app/tests/esm/query-identity/query-worker.js @@ -0,0 +1 @@ +postMessage("query-worker-ready"); diff --git a/TestRunner/app/tests/esm/query-identity/scoped-target.mjs b/TestRunner/app/tests/esm/query-identity/scoped-target.mjs new file mode 100644 index 00000000..058bd630 --- /dev/null +++ b/TestRunner/app/tests/esm/query-identity/scoped-target.mjs @@ -0,0 +1 @@ +export const name = "scoped-target"; diff --git a/TestRunner/app/tests/esm/query-identity/sibling-cjs.js b/TestRunner/app/tests/esm/query-identity/sibling-cjs.js new file mode 100644 index 00000000..532e984f --- /dev/null +++ b/TestRunner/app/tests/esm/query-identity/sibling-cjs.js @@ -0,0 +1 @@ +exports.name = "sibling-cjs"; diff --git a/TestRunner/app/tests/esm/query-identity/sibling.mjs b/TestRunner/app/tests/esm/query-identity/sibling.mjs new file mode 100644 index 00000000..309610c4 --- /dev/null +++ b/TestRunner/app/tests/esm/query-identity/sibling.mjs @@ -0,0 +1 @@ +export const name = "sibling"; diff --git a/TestRunner/app/tests/esm/query-identity/static-mapped.mjs b/TestRunner/app/tests/esm/query-identity/static-mapped.mjs new file mode 100644 index 00000000..bfb546ca --- /dev/null +++ b/TestRunner/app/tests/esm/query-identity/static-mapped.mjs @@ -0,0 +1 @@ +export * as dep from "ns-query-identity-mapped"; diff --git a/TestRunner/app/tests/esm/query-identity/static-v1.mjs b/TestRunner/app/tests/esm/query-identity/static-v1.mjs new file mode 100644 index 00000000..ff8517ae --- /dev/null +++ b/TestRunner/app/tests/esm/query-identity/static-v1.mjs @@ -0,0 +1 @@ +export * as dep from "./counted.mjs?v=1"; diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index e13512f4..00971a8c 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -665,7 +665,8 @@ ending in `/` must have a target ending in `/`. 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 +absolute path for a file on disk, without the query a file module may have been +imported with. That key is this runtime's analogue of the web's resolved referrer URL, which is what scope prefixes match in a browser. An `http(s)` scope key is spelled the way registry keys are (see [Registry canonicalization](#registry-canonicalization)) when the map is @@ -1007,6 +1008,28 @@ while a `pkg/` prefix entry matches `pkg/x.js?v=1`. A query or fragment is dropped only when a file path is derived, so `./x.js?v=1` and `./x.js#f` load `x.js`. +#### File module identity + +As in browsers and Node, the query is part of a file module's identity: +`./x.js?v=1`, `./x.js?v=2` and `./x.js` are three instances of one file, each +evaluated once, whether imported statically or with `import()`; an import-map +target's query counts the same way. `./x.js?` is a fourth: the URL standard +keeps an empty query distinct from none. The fragment is not part of the +identity — `./x.js#a` and `./x.js#b` are the `./x.js` instance — matching how +this loader keys http(s) modules. The query is kept as the URL parser +serializes it. + +Inside such a module, `import.meta.url` carries the query +(`file:///app/x.js?v=1`) while `import.meta.dirname` does not, and relative +imports, `createRequire(import.meta.url)`, `new Worker('./w.js')` and +import-map scopes resolve exactly as for the module without a query. Anything +that names a file without a specifier — the entry module, a worker's script, +`require()` of an ES module — loads the instance without a query. The code +cache is per file, shared by every instance. File modules are not listed by +`getLoadedModuleUrls()`, with or without a query. + +The Android runtime keeps one instance per file for now, whatever the query. + `import()` resolves its specifier once, by the same rules and against the same importer as a static import from the module that calls it, so the import map is applied once: an entry's target is never looked up in the map again, and a From 876befe7ac5681e4de9dcb8b5c4adbb69c11d37d Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 15:23:44 -0300 Subject: [PATCH 5/7] test(runtime): keep the import() table's builtin rows independent of the build configuration ns:module exposes canonicalizeHttpUrlKey only in Debug, so the rows that listed its first members failed in Release. They now check createRequire, which both configurations export. --- TestRunner/app/tests/DynamicImportTests.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/TestRunner/app/tests/DynamicImportTests.js b/TestRunner/app/tests/DynamicImportTests.js index f23ab070..cc4cdff3 100644 --- a/TestRunner/app/tests/DynamicImportTests.js +++ b/TestRunner/app/tests/DynamicImportTests.js @@ -45,6 +45,10 @@ describe("import() resolution table", function () { if ("default" in ns && ns.default && typeof ns.default === "object" && "name" in ns.default) { return "default.name=" + ns.default.name; } + // ns:module's member list differs between Debug and Release. + if ("createRequire" in ns) { + return "createRequire=" + typeof ns.createRequire; + } return "keys=" + Object.keys(ns).sort().slice(0, 3).join(","); } @@ -141,7 +145,7 @@ describe("import() resolution table", function () { ["esm", "file:///app/tests/esm/import-pin/leaf.mjs", "ok:leaf"], ["esm", function () { return "file://" + __dirname + "/esm/import-pin/leaf.mjs"; }, "rejected:Error:Cannot find module 'file:///tests/esm/import-pin/leaf.mjs' (tried /tests/esm/import-pin/leaf.mjs)"], ["esm", "./data.json", "ok:default.name=json"], - ["esm", "ns:module", "ok:keys=canonicalizeHttpUrlKey,configureLoader,createPumpingRequire"], + ["esm", "ns:module", "ok:createRequire=function"], ["esm", "node:url", "ok:keys=URL,URLSearchParams,default"], ["esm", "ns:import-pin-missing", "rejected:Error:No such built-in module: ns:import-pin-missing"], ["esm", function () { return blobUrl; }, "ok:blob"], @@ -172,7 +176,7 @@ describe("import() resolution table", function () { ["cjs", "/tests/esm/import-pin/leaf.mjs", "ok:leaf"], ["cjs", "file:///app/tests/esm/import-pin/leaf.mjs", "ok:leaf"], ["cjs", "./data.json", "ok:default.name=json"], - ["cjs", "ns:module", "ok:keys=canonicalizeHttpUrlKey,configureLoader,createPumpingRequire"], + ["cjs", "ns:module", "ok:createRequire=function"], ["cjs", function () { return blobUrl; }, "ok:blob"], ["cjs", function () { return blobUrl + "?x"; }, "rejected:Error:Blob not found: ?x"], ["cjs", function () { return blobUrl + "#f"; }, "ok:blob"], @@ -187,7 +191,7 @@ describe("import() resolution table", function () { ["newFunction", "~/tests/esm/import-pin/leaf.mjs", "ok:leaf"], ["newFunction", "/tests/esm/import-pin/leaf.mjs", "ok:leaf"], ["newFunction", "file:///app/tests/esm/import-pin/leaf.mjs", "ok:leaf"], - ["newFunction", "ns:module", "ok:keys=canonicalizeHttpUrlKey,configureLoader,createPumpingRequire"], + ["newFunction", "ns:module", "ok:createRequire=function"], ["newFunction", function () { return blobUrl + "#f"; }, "ok:blob"], ["indirectEval", "./leaf.mjs", "rejected:Error:Cannot find module './leaf.mjs' (tried /tests/leaf.mjs)"], @@ -208,7 +212,7 @@ describe("import() resolution table", function () { ["http", "file:///app/tests/esm/import-pin/data.json", "ok:default.name=json"], ["http", "file:///app/tests/esm/import-pin/missing.mjs", "rejected:Error:Cannot find module 'file:///app/tests/esm/import-pin/missing.mjs' (tried /app/tests/esm/import-pin/missing.mjs)"], ["http", "file:///app/tests/esm/import-pin/throws.mjs", "rejected:TypeError:import-pin evaluation error"], - ["http", "ns:module", "ok:keys=canonicalizeHttpUrlKey,configureLoader,createPumpingRequire"], + ["http", "ns:module", "ok:createRequire=function"], ["http", function () { return blobUrl; }, "ok:blob"], ["http", function () { return blobUrl + "?x"; }, "rejected:Error:Blob not found: ?x"], ["http", function () { return blobUrl + "#f"; }, "ok:blob"], From f8a57369961e2f970f01147e89d985479865fb87 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 15:42:34 -0300 Subject: [PATCH 6/7] fix(runtime): keep a '#' in a script URL's path when reading it as a file path ReportedModuleUrl writes a script's path verbatim after file:// and appends only a module key's query, so a '#' in that URL is part of a directory or file name, never a fragment. FileModulePath cut such URLs at the first '?' or '#', which sent a relative new Worker() from a script under a directory named with '#' to the app root. It now cuts at '?' only, the exact inverse of what ReportedModuleUrl appends. --- NativeScript/runtime/ModuleUrl.cpp | 5 +- NativeScript/runtime/ModuleUrl.h | 8 +-- TestRunner/app/tests/DynamicImportTests.js | 58 ++++++++++++++++++++++ 3 files changed, 65 insertions(+), 6 deletions(-) diff --git a/NativeScript/runtime/ModuleUrl.cpp b/NativeScript/runtime/ModuleUrl.cpp index 5f225c56..081e2348 100644 --- a/NativeScript/runtime/ModuleUrl.cpp +++ b/NativeScript/runtime/ModuleUrl.cpp @@ -198,11 +198,12 @@ std::string ModuleQuery(const std::string& specifier) { std::string FileModulePath(const std::string& keyOrUrl) { // The inverse of ReportedModuleUrl's spelling, which writes the path - // verbatim (not percent-encoded) after `file://`. + // verbatim (not percent-encoded, so a '#' is part of it) after `file://` + // and appends only a key's query. if (StartsWith(keyOrUrl, "file://")) { const std::string rest = keyOrUrl.substr(std::char_traits::length("file://")); - return rest.substr(0, rest.find_first_of("?#")); + return rest.substr(0, rest.find('?')); } if (keyOrUrl.empty() || HasUrlScheme(keyOrUrl) || IsHttpRegistryKey(keyOrUrl)) { diff --git a/NativeScript/runtime/ModuleUrl.h b/NativeScript/runtime/ModuleUrl.h index c26ca4c6..2eedaff7 100644 --- a/NativeScript/runtime/ModuleUrl.h +++ b/NativeScript/runtime/ModuleUrl.h @@ -59,10 +59,10 @@ std::string ReportedModuleUrl(const std::string& keyOrPath); std::string ModuleQuery(const std::string& specifier); // The filesystem path a file module's registry key, or a `file://` URL as -// ReportedModuleUrl spells it, names: the key or URL path without its query or -// fragment. A URL's path is relative to RuntimeConfig.BaseDir. Empty for a key -// or URL with any other scheme. The one way a module key or script URL is -// read as a path. +// ReportedModuleUrl spells it, names: everything before the query. Neither +// carries a fragment, so a '#' is part of the path. A URL's path is relative +// to RuntimeConfig.BaseDir. Empty for a key or URL with any other scheme. The +// one way a module key or script URL is read as a path. std::string FileModulePath(const std::string& keyOrUrl); } // namespace tns diff --git a/TestRunner/app/tests/DynamicImportTests.js b/TestRunner/app/tests/DynamicImportTests.js index cc4cdff3..b4bba223 100644 --- a/TestRunner/app/tests/DynamicImportTests.js +++ b/TestRunner/app/tests/DynamicImportTests.js @@ -450,3 +450,61 @@ describe("file module instances per query", function () { }); }); }); + +// A script's URL spells its path verbatim, so a '#' in a directory name is part +// of the path there, not a fragment. Written at run time: the fixture lives in +// the built app only for the duration of the spec. +describe("a script in a directory whose name contains '#'", function () { + var fileManager = NSFileManager.defaultManager; + var fixtureDir = NSBundle.mainBundle.resourcePath + "/app/tests/esm/hash#dir"; + + function writeFile(path, body) { + var data = NSString.stringWithString(body).dataUsingEncoding(NSUTF8StringEncoding); + return fileManager.createFileAtPathContentsAttributes(path, data, null); + } + + beforeAll(function () { + fileManager.createDirectoryAtPathWithIntermediateDirectoriesAttributesError( + fixtureDir, true, null, null); + writeFile(fixtureDir + "/spawner.js", + "exports.start = function () { return new Worker(\"./w.js\"); };\n"); + writeFile(fixtureDir + "/w.js", "postMessage(\"hash-dir-worker\");\n"); + }); + + afterAll(function () { + if (fileManager.fileExistsAtPath(fixtureDir)) { + fileManager.removeItemAtPathError(fixtureDir, null); + } + }); + + it("starts a relative worker from that directory", function (done) { + var worker; + var timer = setTimeout(function () { + if (worker) { + worker.terminate(); + } + expect("no message").toBe("hash-dir-worker"); + done(); + }, 10000); + function finish(actual) { + clearTimeout(timer); + if (worker) { + worker.terminate(); + } + expect(actual).toBe("hash-dir-worker"); + done(); + } + try { + worker = require(fixtureDir + "/spawner.js").start(); + } catch (e) { + finish("threw: " + String((e && e.message) || e)); + return; + } + worker.onerror = function (e) { + finish("error: " + String((e && e.message) || e)); + }; + worker.onmessage = function (msg) { + finish(msg.data); + }; + }); +}); From 9e2956a8a28128c831fc0efb424aa362609be9ea Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 16:53:39 -0300 Subject: [PATCH 7/7] fix(runtime): read file module paths as recorded, load mapped builtins, keep unparsed queries - The module-graph walk takes its root as the caller holds it: a native caller's whole path (entry module, worker entry, require() of an ES module), import()'s resolution, or an http(s) URL. It no longer reads a path containing '?' as path plus query, which evaluated the wrong file. Each file module's path is recorded when it is registered, and import resolution, import-map scopes and import.meta.dirname read that record, so such a module's relative imports use its real directory. - An import-map target that names a ns: or node: builtin resolves as that builtin, for static imports and import() from file and HTTP modules; a target naming a builtin that does not exist reports the builtin registry's error. A builtin written directly still bypasses the map. - A specifier the URL parser rejects keeps its query in the module's key, as written up to any fragment, so two queries are still two instances. --- NativeScript/runtime/ModuleInternal.mm | 8 +- .../runtime/ModuleInternalCallbacks.h | 34 +++- .../runtime/ModuleInternalCallbacks.mm | 162 +++++++++++++----- NativeScript/runtime/ModuleUrl.cpp | 18 +- NativeScript/runtime/ModuleUrl.h | 3 +- NativeScript/runtime/Runtime.mm | 2 +- TestRunner/app/tests/DynamicImportTests.js | 129 ++++++++++++++ .../esm/import-pin/static-builtin-missing.mjs | 1 + .../esm/import-pin/static-builtin-node.mjs | 1 + .../esm/import-pin/static-builtin-ns.mjs | 1 + docs/ns-builtin-modules.md | 16 +- 11 files changed, 313 insertions(+), 62 deletions(-) create mode 100644 TestRunner/app/tests/esm/import-pin/static-builtin-missing.mjs create mode 100644 TestRunner/app/tests/esm/import-pin/static-builtin-node.mjs create mode 100644 TestRunner/app/tests/esm/import-pin/static-builtin-ns.mjs diff --git a/NativeScript/runtime/ModuleInternal.mm b/NativeScript/runtime/ModuleInternal.mm index ff07dfaa..65da6312 100644 --- a/NativeScript/runtime/ModuleInternal.mm +++ b/NativeScript/runtime/ModuleInternal.mm @@ -1542,7 +1542,8 @@ throw NativeScriptException("Module evaluation interrupted by isolate terminatio // boot handoff for static HTTP entries). Afterwards the load below is a // registry hit and instantiation resolves as pure lookup. On timeout or // partial coverage the legacy synchronous path still owns correctness. - RunModuleGraphLoadPumped(isolate, context, requestPath, kModuleEvaluateDeadlineSeconds); + RunModuleGraphLoadPumped(isolate, context, ModuleGraphRoot::HttpUrl(requestPath), + kModuleEvaluateDeadlineSeconds); ThrowIfLoadInterruptedByTermination(isolate, canonicalPath); MaybeLocal maybeMod = LoadHttpModuleForUrl(isolate, context, requestPath); if (!maybeMod.ToLocal(&module)) { @@ -1566,7 +1567,8 @@ throw NativeScriptException("Module evaluation interrupted by isolate terminatio // settle window: a strict require refuses an async EVALUATION, not an // async fetch, so it legitimately waits here and then evaluates // synchronously. - RunModuleGraphLoadPumped(isolate, context, canonicalPath, kModuleEvaluateDeadlineSeconds); + RunModuleGraphLoadPumped(isolate, context, ModuleGraphRoot::FilePath(canonicalPath), + kModuleEvaluateDeadlineSeconds); ThrowIfLoadInterruptedByTermination(isolate, canonicalPath); auto walkedIt = registry.find(canonicalPath); if (walkedIt != registry.end()) { @@ -1618,7 +1620,7 @@ throw NativeScriptException(isolate, tcCompile, requestPath.c_str(), canonicalPath.c_str(), it != registry.end() ? "yes" : "no"); } registry[canonicalPath].Reset(isolate, module); - IndexModuleForIsolate(isolate, canonicalPath, module); + IndexModuleForIsolate(isolate, canonicalPath, module, canonicalPath); } // 5) Instantiate (link) with its own TryCatch diff --git a/NativeScript/runtime/ModuleInternalCallbacks.h b/NativeScript/runtime/ModuleInternalCallbacks.h index ca23d328..56e5a4a8 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.h +++ b/NativeScript/runtime/ModuleInternalCallbacks.h @@ -97,11 +97,18 @@ void RemoveModuleFromRegistry(v8::Isolate* isolate, std::string LookupModuleKeyForModule(v8::Isolate* isolate, v8::Local mod); -// Record `mod` in the identity-hash index under `canonicalKey`. Call alongside -// every registry insert performed outside ModuleInternalCallbacks.mm. +// Record `mod` in the identity-hash index under `canonicalKey`, and, for a +// file module, the file it was read from. Call alongside every registry +// insert performed outside ModuleInternalCallbacks.mm. void IndexModuleForIsolate(v8::Isolate* isolate, const std::string& canonicalKey, - v8::Local mod); + v8::Local mod, + const std::string& filePath); + +// The file a file module's registry key names: the path recorded when it was +// registered, or, for a key never registered, the key read as a path plus a +// query (FileModulePath). Empty for an http(s), blob: or other URL key. +std::string ModuleFilePathForKey(v8::Isolate* isolate, const std::string& key); // The require(esm) exports facade: a synthetic source-text module that // re-exports everything from `target` and adds `__esModule = true`, so @@ -159,9 +166,25 @@ v8::MaybeLocal LoadHttpModuleForUrl( // root — is left unregistered for the resolver (or the caller's own load // path) to report with its own message, so the walk introduces no new failure // modes and steals no error text. +// +// `root` says what the caller holds; the walk never infers it from a string. +struct ModuleGraphRoot { + bool http = false; + std::string url; // http: the absolute URL + std::string path; // file: the file read and probed, used whole + std::string key; // file: the registry key + std::string query; // file: the query `key` carries after the path + + // A filesystem path a native caller holds (entry module, worker entry, + // require() of an ES module): the whole string names the file, and the + // module is the instance without a query. + static ModuleGraphRoot FilePath(const std::string& path); + static ModuleGraphRoot HttpUrl(const std::string& url); +}; + void StartModuleGraphLoad( v8::Isolate* isolate, v8::Local context, - const std::string& root, double fetchDeadline, + const ModuleGraphRoot& root, double fetchDeadline, std::function context)> onComplete); @@ -175,7 +198,8 @@ void StartModuleGraphLoad( // caller's own load path reports root failures). bool RunModuleGraphLoadPumped(v8::Isolate* isolate, v8::Local context, - const std::string& root, double timeoutSeconds); + const ModuleGraphRoot& root, + double timeoutSeconds); // True while any async graph load (any isolate) has fetches or compiles // outstanding. Read by the boot handoff in [NativeScript runMainApplication] diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 63c58355..5e3d7298 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -278,6 +278,12 @@ void CloseAndDrain(const std::function& serviceGcRequests) { // stale ones lazily, so staleness is tolerated, never trusted. robin_hood::unordered_map> keysByModuleHash; + // The file each registered file module was read from, by registry key. A + // key is the path plus the query it was imported with, and a path may itself + // contain '?', so the split is recorded where it is known rather than parsed + // back out of the key. + robin_hood::unordered_map filePathByKey; + // require(esm) facades, keyed by the TARGET module's identity hash — same // bucket-plus-handle-compare shape as keysByModuleHash. Repeated require() // of one ES module must hand back the identical exports object, and a facade @@ -441,8 +447,29 @@ void SetRegisteredModule(ModuleLoaderState& state, v8::Isolate* isolate, const s state.registry[key].Reset(isolate, mod); IndexRegisteredModule(state, key, mod); } + +void SetRegisteredFileModule(ModuleLoaderState& state, v8::Isolate* isolate, const std::string& key, + const std::string& filePath, v8::Local mod) { + SetRegisteredModule(state, isolate, key, mod); + state.filePathByKey[key] = filePath; +} } // namespace +std::string ModuleFilePathForKey(v8::Isolate* isolate, const std::string& key) { + auto* state = isolate != nullptr ? ModuleLoaderStateFor(isolate) : nullptr; + if (state != nullptr) { + auto it = state->filePathByKey.find(key); + if (it != state->filePathByKey.end()) { + return it->second; + } + } + return FileModulePath(key); +} + +static std::string FilePathForModuleKey(const std::string& key) { + return ModuleFilePathForKey(v8::Isolate::GetCurrent(), key); +} + v8::MaybeLocal GetOrCreateRequireFacade(v8::Isolate* isolate, v8::Local context, v8::Local target, @@ -515,12 +542,15 @@ throw NativeScriptException(isolate, tc, } void IndexModuleForIsolate(v8::Isolate* isolate, const std::string& canonicalKey, - v8::Local mod) { + v8::Local mod, const std::string& filePath) { auto* state = ModuleLoaderStateFor(isolate); if (state == nullptr) { return; } IndexRegisteredModule(*state, canonicalKey, mod); + if (!filePath.empty()) { + state->filePathByKey[canonicalKey] = filePath; + } } // Turn a value JS handed us into a real v8::Promise. @@ -799,9 +829,16 @@ static bool ShouldTraceRegistryKey(const std::string& rawKey, const std::string& traceEvenWithoutChange = true; } else { // Standardizing must not reach the query: its dot segments and - // slashes are not path syntax. - const std::string path = FileModulePath(key); - registryKey = NormalizePath(path) + key.substr(path.size()); + // slashes are not path syntax. A registered key is already canonical, + // and its path may itself contain '?'. + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + auto* state = isolate != nullptr ? ModuleLoaderStateFor(isolate) : nullptr; + if (state != nullptr && state->filePathByKey.count(key) != 0) { + registryKey = key; + } else { + const std::string path = FileModulePath(key); + registryKey = NormalizePath(path) + key.substr(path.size()); + } } } @@ -1158,7 +1195,7 @@ static bool IsVolatileUrl(const std::string& url) { if (vocabulary == nullptr) { return ""; } - const std::string importerPath = FileModulePath(importerKey); + const std::string importerPath = FilePathForModuleKey(importerKey); const std::string& referrerKey = importerPath.empty() ? importerKey : importerPath; for (const auto& scope : vocabulary->importMap.scopes) { const std::string& prefix = scope.first; @@ -1729,6 +1766,13 @@ static ModuleResolution ResolveSpecifierToPath( result.specifier = spec; + // An import-map target may name a builtin; it is not looked up in the map + // again, as no target is. + if (mappedByImportMap && NsBuiltinModules::IsBuiltinScheme(spec)) { + result.kind = ModuleResolution::Kind::kBuiltin; + return result; + } + const std::string blobUrl = BlobStoreUrl(spec); if (!blobUrl.empty()) { result.kind = ModuleResolution::Kind::kBlob; @@ -1789,7 +1833,7 @@ static ModuleResolution ResolveSpecifierToPath( const bool specIsRelative = spec[0] == '.'; const bool specIsRootAbs = spec[0] == '/'; - const std::string referrerPath = FileModulePath(referrerKey); + const std::string referrerPath = FilePathForModuleKey(referrerKey); const std::string& referrerBase = referrerPath.empty() ? referrerKey : referrerPath; size_t slash = referrerBase.find_last_of("/\\"); std::string baseDir = slash == std::string::npos ? "" : referrerBase.substr(0, slash + 1); @@ -1943,7 +1987,7 @@ static ModuleResolution ResolveSpecifierToPath( result.kind = ModuleResolution::Kind::kFile; result.path = absPath; result.query = query; - result.key = CanonicalizeRegistryKey(absPath) + query; + result.key = absPath + query; } return result; } @@ -2165,7 +2209,7 @@ static void AsyncGraphCompileLocalModule(const std::shared_ptr& } } - SetRegisteredModule(*moduleState, isolate, key, mod); + SetRegisteredFileModule(*moduleState, isolate, key, path, mod); load->compiledCount++; AsyncGraphWalkModuleRequests(load, context, mod, key); } @@ -2260,31 +2304,46 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, }); } -// Classify a walk root. The root arrives already resolved — an absolute URL -// from the HTTP loader, a canonical path from LoadESModule, or a file module's -// registry key from import() — so it needs only scheme dispatch, not the full -// specifier resolution. -static ModuleResolution ResolutionForRoot(const std::string& root) { +ModuleGraphRoot ModuleGraphRoot::FilePath(const std::string& path) { + ModuleGraphRoot root; + root.path = path; + root.key = NormalizePath(path); + return root; +} + +ModuleGraphRoot ModuleGraphRoot::HttpUrl(const std::string& url) { + ModuleGraphRoot root; + root.http = true; + root.url = url; + return root; +} + +// The walk's first edge, from what the caller holds. A file root that is not a +// regular file, or an http(s) root the URL parser rejects, stays kUnresolved: +// there is nothing to walk, and the caller's own load path reports why. +static ModuleResolution ResolutionForRoot(const ModuleGraphRoot& root) { ModuleResolution resolution; - resolution.specifier = root; - const std::string httpUrl = NormalizeHttpModuleUrl(root); - const std::string path = FileModulePath(root); - if (!httpUrl.empty()) { - resolution.kind = ModuleResolution::Kind::kHttp; - resolution.url = httpUrl; - } else if (!path.empty() && IsRegularFile(path)) { - resolution.kind = ModuleResolution::Kind::kFile; - resolution.path = path; - resolution.key = CanonicalizeRegistryKey(root); - resolution.query = root.substr(path.size()); - } - // Anything else stays kUnresolved: there is nothing to walk, and the - // caller's own load path reports why. + if (root.http) { + resolution.specifier = root.url; + const std::string httpUrl = NormalizeHttpModuleUrl(root.url); + if (!httpUrl.empty()) { + resolution.kind = ModuleResolution::Kind::kHttp; + resolution.url = httpUrl; + } + } else { + resolution.specifier = root.key; + if (IsRegularFile(root.path)) { + resolution.kind = ModuleResolution::Kind::kFile; + resolution.path = root.path; + resolution.key = root.key; + resolution.query = root.query; + } + } return resolution; } void StartModuleGraphLoad( - v8::Isolate* isolate, v8::Local context, const std::string& root, + v8::Isolate* isolate, v8::Local context, const ModuleGraphRoot& root, double fetchDeadline, std::function context)> onComplete) { @@ -2292,9 +2351,11 @@ void StartModuleGraphLoad( auto load = std::make_shared(); load->isolate = isolate; load->context.Reset(isolate, context); - load->rootKey = rootResolution.kind == ModuleResolution::Kind::kHttp - ? CanonicalizeNormalizedHttpUrlKey(rootResolution.url) - : CanonicalizeRegistryKey(root); + if (rootResolution.kind == ModuleResolution::Kind::kHttp) { + load->rootKey = CanonicalizeNormalizedHttpUrlKey(rootResolution.url); + } else { + load->rootKey = root.http ? CanonicalizeRegistryKey(root.url) : root.key; + } load->startUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); load->fetchDeadline = fetchDeadline; load->onComplete = std::move(onComplete); @@ -2302,7 +2363,8 @@ void StartModuleGraphLoad( AsyncGraphLoad::g_asyncGraphLoadsInFlightCounter().fetch_add(1, std::memory_order_acq_rel); RegisterAsyncGraphLoad(isolate, load); - TNS_DEBUG(Esm, "[graph][start] root=%s key=%s", root.c_str(), load->rootKey.c_str()); + TNS_DEBUG(Esm, "[graph][start] root=%s key=%s", rootResolution.specifier.c_str(), + load->rootKey.c_str()); if (rootResolution.kind != ModuleResolution::Kind::kUnresolved) { AsyncGraphEnqueue(load, rootResolution); @@ -2313,7 +2375,7 @@ void StartModuleGraphLoad( } bool RunModuleGraphLoadPumped(v8::Isolate* isolate, v8::Local context, - const std::string& root, double timeoutSeconds) { + const ModuleGraphRoot& root, double timeoutSeconds) { if (timeoutSeconds <= 0.0) { timeoutSeconds = 60.0; } @@ -2347,7 +2409,8 @@ bool RunModuleGraphLoadPumped(v8::Isolate* isolate, v8::Local conte // takes JS this wait may never run. if (isolate->IsExecutionTerminating() || (runtime != nullptr && runtime->IsTerminationRequested())) { - TNS_DEBUG(Esm, "[graph][pumped] execution terminating, abandoning wait for %s", root.c_str()); + TNS_DEBUG(Esm, "[graph][pumped] execution terminating, abandoning wait for %s", + (root.http ? root.url : root.key).c_str()); return false; } if (*done) { @@ -2368,7 +2431,7 @@ bool RunModuleGraphLoadPumped(v8::Isolate* isolate, v8::Local conte } if (!*done) { TNS_DEBUG(Esm, "[graph][pumped][timeout] root=%s after %.1fs (sync loader takes over)", - root.c_str(), timeoutSeconds); + (root.http ? root.url : root.key).c_str(), timeoutSeconds); } return *done; } @@ -2420,6 +2483,7 @@ void RemoveModuleFromRegistry(v8::Isolate* isolate, const std::string& canonical UnindexRegisteredModule(*moduleState, isolate, registryKey); it->second.Reset(); registry.erase(it); + moduleState->filePathByKey.erase(registryKey); } else if (tns::LogCategoryEnabled(tns::LogCategory::Esm)) { TNS_DEBUG(Esm, "[resolver][remove:miss] key not found, proceed to clear fallbacks (%s)", registryKey.c_str()); @@ -2861,7 +2925,7 @@ static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate, // importer's instantiation with it. return v8::MaybeLocal(); } - SetRegisteredModule(*moduleState, isolate, registryKey, mod); + SetRegisteredFileModule(*moduleState, isolate, registryKey, absPath, mod); return v8::MaybeLocal(mod); } catch (NativeScriptException& ex) { ex.ReThrowToV8(isolate); @@ -2896,13 +2960,14 @@ static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate, switch (resolution.kind) { case ModuleResolution::Kind::kBuiltin: { + const std::string& name = resolution.specifier; v8::Local builtin; - if (NsBuiltinModules::GetModule(context, rawSpec).ToLocal(&builtin)) { + if (NsBuiltinModules::GetModule(context, name).ToLocal(&builtin)) { return v8::MaybeLocal(builtin); } - if (!NsBuiltinModules::IsRegistered(rawSpec)) { + if (!NsBuiltinModules::IsRegistered(name)) { isolate->ThrowException(v8::Exception::Error( - tns::ToV8String(isolate, NsBuiltinModules::NotFoundMessage(rawSpec)))); + tns::ToV8String(isolate, NsBuiltinModules::NotFoundMessage(name)))); } return v8::MaybeLocal(); } @@ -3165,15 +3230,16 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local switch (resolution.kind) { case ModuleResolution::Kind::kBuiltin: { + const std::string& name = resolution.specifier; v8::TryCatch tc(isolate); v8::Local builtin; - if (NsBuiltinModules::GetModule(context, rawSpec).ToLocal(&builtin)) { + if (NsBuiltinModules::GetModule(context, name).ToLocal(&builtin)) { resolver->Resolve(context, builtin->GetModuleNamespace()).FromMaybe(false); } else { - v8::Local error = - tc.HasCaught() ? tc.Exception() - : v8::Exception::Error(tns::ToV8String( - isolate, NsBuiltinModules::NotFoundMessage(rawSpec))); + v8::Local error = tc.HasCaught() + ? tc.Exception() + : v8::Exception::Error(tns::ToV8String( + isolate, NsBuiltinModules::NotFoundMessage(name))); // Reject must not run with the exception still pending on the isolate. tc.Reset(); resolver->Reject(context, error).FromMaybe(false); @@ -3712,7 +3778,7 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local // immediately — no synchronous fetch, no runloop pump. const std::string requestUrl = normalizedSpec; StartModuleGraphLoad( - isolate, context, requestUrl, /*fetchDeadline=*/0, + isolate, context, ModuleGraphRoot::HttpUrl(requestUrl), /*fetchDeadline=*/0, [key, requestUrl, isolate](bool ok, const std::string& errorMessage, v8::Local completionContext) { // JS thread; isolate entered and context scoped by the pipeline. @@ -3733,7 +3799,11 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local // resolver cold and fetch serially, one blocking round trip each. A graph // with no HTTP edges settles inside the call, so a local-only dynamic // import neither waits nor touches the runloop. - RunModuleGraphLoadPumped(isolate, context, resolution.key, tns::kModuleEvaluateDeadlineSeconds); + ModuleGraphRoot root; + root.path = resolution.path; + root.key = resolution.key; + root.query = resolution.query; + RunModuleGraphLoadPumped(isolate, context, root, tns::kModuleEvaluateDeadlineSeconds); // The walk leaves JSON, and any module it could not compile, for this // step, which also replaces an errored registry entry. A compile failure diff --git a/NativeScript/runtime/ModuleUrl.cpp b/NativeScript/runtime/ModuleUrl.cpp index 081e2348..c28139fa 100644 --- a/NativeScript/runtime/ModuleUrl.cpp +++ b/NativeScript/runtime/ModuleUrl.cpp @@ -189,11 +189,23 @@ std::string ModuleQuery(const std::string& specifier) { } static const auto base = ada::parse("file:///", nullptr); auto url = ada::parse(specifier, &base.value()); - if (!url || !url->has_search()) { + if (url) { + if (!url->has_search()) { + return std::string(); + } + const std::string_view search = url->get_search(); + return search.empty() ? std::string("?") : std::string(search); + } + // A specifier the parser rejects (`//host:port/x.mjs?v=1` against a file + // base) can still name a file; its query must not be lost, or two queries + // would share one instance. + const size_t query = specifier.find('?'); + const size_t fragment = specifier.find('#'); + if (fragment != std::string::npos && fragment < query) { return std::string(); } - const std::string_view search = url->get_search(); - return search.empty() ? std::string("?") : std::string(search); + return specifier.substr( + query, fragment == std::string::npos ? fragment : fragment - query); } std::string FileModulePath(const std::string& keyOrUrl) { diff --git a/NativeScript/runtime/ModuleUrl.h b/NativeScript/runtime/ModuleUrl.h index 2eedaff7..a1bda360 100644 --- a/NativeScript/runtime/ModuleUrl.h +++ b/NativeScript/runtime/ModuleUrl.h @@ -55,7 +55,8 @@ std::string ReportedModuleUrl(const std::string& keyOrPath); // The query of `specifier` as the URL parser serializes it, '?' included, the // fragment dropped: what a file module's registry key carries after its path. // "?" for an empty query, which the URL standard keeps distinct from none; -// empty when there is no query. +// empty when there is no query. When the parser rejects the specifier, the +// text from its first '?' up to any '#', as written. std::string ModuleQuery(const std::string& specifier); // The filesystem path a file module's registry key, or a `file://` URL as diff --git a/NativeScript/runtime/Runtime.mm b/NativeScript/runtime/Runtime.mm index de66d255..8cba9874 100644 --- a/NativeScript/runtime/Runtime.mm +++ b/NativeScript/runtime/Runtime.mm @@ -102,7 +102,7 @@ static void InitializeImportMetaObject(Local context, Local mod dirname = "/app"; } else { const std::string appRelative = - tns::ReplaceAll(tns::FileModulePath(modulePath), RuntimeConfig.BaseDir, ""); + tns::ReplaceAll(tns::ModuleFilePathForKey(isolate, modulePath), RuntimeConfig.BaseDir, ""); size_t lastSlash = appRelative.find_last_of("/\\"); if (lastSlash != std::string::npos && lastSlash > 0) { dirname = appRelative.substr(0, lastSlash); diff --git a/TestRunner/app/tests/DynamicImportTests.js b/TestRunner/app/tests/DynamicImportTests.js index b4bba223..425d675a 100644 --- a/TestRunner/app/tests/DynamicImportTests.js +++ b/TestRunner/app/tests/DynamicImportTests.js @@ -86,6 +86,16 @@ describe("import() resolution table", function () { return m.load(spec); }); }, + // A static import: `spec` names the importing fixture, whose `dep` + // re-exports what it imports. + esmStatic: function (fixture) { + return import(dir + fixture).then(function (m) { return m.dep; }); + }, + // The test server's static.mjs statically imports its `spec` param. + httpStatic: function (spec) { + return import(origin + "/esm/resolve/import-pin/static.mjs?spec=" + + encodeURIComponent(spec)).then(function (m) { return m.dep; }); + }, }; beforeAll(function () { @@ -96,6 +106,9 @@ describe("import() resolution table", function () { "ns-pin-relative-target": "./leaf.mjs", "ns-pin-chain": "ns-pin-mapped", "ns-pin-dir/": "~/tests/esm/import-pin/dir/", + "ns-pin-builtin-ns": "ns:module", + "ns-pin-builtin-node": "node:url", + "ns-pin-builtin-missing": "ns:import-pin-missing", }, }, }); @@ -218,6 +231,30 @@ describe("import() resolution table", function () { ["http", function () { return blobUrl + "#f"; }, "ok:blob"], ]; + // Import-map targets naming a builtin, from both forms of import. A + // static row names the fixture (or, from HTTP, the specifier) it imports. + var builtinTargetRows = [ + ["esm", "ns-pin-builtin-ns", "ok:createRequire=function"], + ["esm", "ns-pin-builtin-node", "ok:keys=URL,URLSearchParams,default"], + ["esm", "ns-pin-builtin-missing", + "rejected:Error:No such built-in module: ns:import-pin-missing"], + ["esmStatic", "static-builtin-ns.mjs", "ok:createRequire=function"], + ["esmStatic", "static-builtin-node.mjs", "ok:keys=URL,URLSearchParams,default"], + ["esmStatic", "static-builtin-missing.mjs", + "rejected:Error:Failed to instantiate module: ~/tests/esm/import-pin/static-builtin-missing.mjs" + + " — Error: No such built-in module: ns:import-pin-missing"], + ["http", "ns-pin-builtin-ns", "ok:createRequire=function"], + ["http", "ns-pin-builtin-node", "ok:keys=URL,URLSearchParams,default"], + ["http", "ns-pin-builtin-missing", + "rejected:Error:No such built-in module: ns:import-pin-missing"], + ["httpStatic", "ns-pin-builtin-ns", "ok:createRequire=function"], + ["httpStatic", "ns-pin-builtin-node", "ok:keys=URL,URLSearchParams,default"], + ["httpStatic", "ns-pin-builtin-missing", + "rejected:Error:Instantiation failed (http-loader): " + + "/esm/resolve/import-pin/static.mjs?spec=ns-pin-builtin-missing" + + " — Uncaught Error: No such built-in module: ns:import-pin-missing"], + ]; + var rowCount = 0; function addRow(row, needsOrigin) { var label = typeof row[1] === "function" @@ -244,6 +281,9 @@ describe("import() resolution table", function () { httpRows.forEach(function (row) { addRow(row, true); }); + builtinTargetRows.forEach(function (row) { + addRow(row, row[0] === "http" || row[0] === "httpStatic"); + }); it("from esm: the same namespace for a repeated import", function (done) { Promise.all([importers.esm("./leaf.mjs"), importers.esm("./leaf.mjs")]).then(function (r) { @@ -508,3 +548,92 @@ describe("a script in a directory whose name contains '#'", function () { }; }); }); + +// Fixtures written into the built app at run time, for file names the +// repository does not check in. +function writeAppFile(path, body) { + var fileManager = NSFileManager.defaultManager; + fileManager.createDirectoryAtPathWithIntermediateDirectoriesAttributesError( + NSString.stringWithString(path).stringByDeletingLastPathComponent, true, null, null); + var data = NSString.stringWithString(body).dataUsingEncoding(NSUTF8StringEncoding); + return fileManager.createFileAtPathContentsAttributes(path, data, null); +} + +function removeAppPath(path) { + var fileManager = NSFileManager.defaultManager; + if (fileManager.fileExistsAtPath(path)) { + fileManager.removeItemAtPathError(path, null); + } +} + +// A native caller names a file by its whole path, so a '?' in it is part of a +// directory name, not a query: the module loaded is the file at that path, and +// its relative imports and import.meta.dirname use that directory. +describe("an ES module whose path contains '?', loaded by require()", function () { + var fixtureDir = NSBundle.mainBundle.resourcePath + "/app/tests/esm/qmark-tmp"; + + beforeAll(function () { + writeAppFile(fixtureDir + "/theme.mjs", "export const name = \"theme-file\";\n"); + writeAppFile(fixtureDir + "/sibling.mjs", "export const name = \"outer-sibling\";\n"); + writeAppFile(fixtureDir + "/theme.mjs?v=1/sibling.mjs", + "export const name = \"inner-sibling\";\n"); + writeAppFile(fixtureDir + "/theme.mjs?v=1/entry.mjs", + "import { name as siblingName } from \"./sibling.mjs\";\n" + + "export const name = \"entry\";\n" + + "export const sibling = siblingName;\n" + + "export const dirname = import.meta.dirname;\n"); + }); + + afterAll(function () { + removeAppPath(fixtureDir); + }); + + it("evaluates that file, with its directory as the base of its imports", function () { + var ns; + try { + ns = require(fixtureDir + "/theme.mjs?v=1/entry.mjs"); + } catch (e) { + expect("threw: " + String((e && e.message) || e)).toBe("loaded"); + return; + } + expect([ns.name, ns.sibling, ns.dirname]) + .toEqual(["entry", "inner-sibling", "/app/tests/esm/qmark-tmp/theme.mjs?v=1"]); + }); +}); + +// `//host:port/…` does not parse against a file: base, yet as a root-absolute +// specifier it names a file under the app root; its query still separates +// instances. +describe("a file specifier the URL parser rejects, with a query", function () { + var fixtureDir = NSBundle.mainBundle.resourcePath + "/app/import-pin-colon:dir"; + + beforeAll(function () { + writeAppFile(fixtureDir + "/leaf.mjs", + "const counts = (globalThis.__colonDirEvaluations ??= {});\n" + + "counts[import.meta.url] = (counts[import.meta.url] || 0) + 1;\n" + + "export const url = import.meta.url;\n"); + }); + + afterAll(function () { + removeAppPath(fixtureDir); + }); + + it("gives each query its own instance", function (done) { + import("~/tests/esm/import-pin/importer.mjs").then(function (m) { + return Promise.all([m.load("//import-pin-colon:dir/leaf.mjs?v=1"), + m.load("//import-pin-colon:dir/leaf.mjs?v=2"), + m.load("//import-pin-colon:dir/leaf.mjs")]); + }).then(function (r) { + var base = "file:///app/import-pin-colon:dir/leaf.mjs"; + expect(r.map(function (ns) { return ns.url; })) + .toEqual([base + "?v=1", base + "?v=2", base]); + expect([r[0] === r[1], r[0] === r[2], r[1] === r[2]]).toEqual([false, false, false]); + expect(r.map(function (ns) { return globalThis.__colonDirEvaluations[ns.url]; })) + .toEqual([1, 1, 1]); + done(); + }, function (e) { + expect("rejected: " + String((e && e.message) || e)).toBe("resolved"); + done(); + }); + }); +}); diff --git a/TestRunner/app/tests/esm/import-pin/static-builtin-missing.mjs b/TestRunner/app/tests/esm/import-pin/static-builtin-missing.mjs new file mode 100644 index 00000000..145df47f --- /dev/null +++ b/TestRunner/app/tests/esm/import-pin/static-builtin-missing.mjs @@ -0,0 +1 @@ +export * as dep from "ns-pin-builtin-missing"; diff --git a/TestRunner/app/tests/esm/import-pin/static-builtin-node.mjs b/TestRunner/app/tests/esm/import-pin/static-builtin-node.mjs new file mode 100644 index 00000000..af1fa1a2 --- /dev/null +++ b/TestRunner/app/tests/esm/import-pin/static-builtin-node.mjs @@ -0,0 +1 @@ +export * as dep from "ns-pin-builtin-node"; diff --git a/TestRunner/app/tests/esm/import-pin/static-builtin-ns.mjs b/TestRunner/app/tests/esm/import-pin/static-builtin-ns.mjs new file mode 100644 index 00000000..c1b9d771 --- /dev/null +++ b/TestRunner/app/tests/esm/import-pin/static-builtin-ns.mjs @@ -0,0 +1 @@ +export * as dep from "ns-pin-builtin-ns"; diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 00971a8c..19e9dc60 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -967,9 +967,13 @@ unmodified where a shim exists: ### 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. +and `import()` alike, as below. `ns:`/`node:` builtins resolve first, without +the import map, and the [import map](#import-maps-and-scopes) is consulted +next; an entry whose target names a builtin (`{ "alias": "node:module" }`) +loads that builtin, from any importer and either form of import, and a target +naming a builtin that does not exist fails with the builtin registry's +`No such built-in module` error. The table covers a specifier the map does not +match. | specifier | from an http(s) importer | |---|---| @@ -1030,6 +1034,12 @@ cache is per file, shared by every instance. File modules are not listed by The Android runtime keeps one instance per file for now, whatever the query. +A file named by its whole path rather than a specifier — the entry module, a +worker's script, `require()` of an ES module — is read at that path even when +a directory or file name in it contains `?`; that module's relative imports +and `import.meta.dirname` use its real directory. A specifier, by contrast, +always reads a `?` as the start of a query. + `import()` resolves its specifier once, by the same rules and against the same importer as a static import from the module that calls it, so the import map is applied once: an entry's target is never looked up in the map again, and a