// ModuleInternalCallbacks.cpp #include "ModuleInternalCallbacks.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "ArgConverter.h" #include "EventLoop.h" #include "ExactUtf8.h" #include "HttpLoader.h" #include "JEnv.h" #include "ModuleInternal.h" #include "ModuleUrl.h" #include "NativeScriptAssert.h" #include "NativeScriptException.h" #include "NativeScriptPlatform.h" #include "NsBuiltinModules.h" #include "Runtime.h" #include "RuntimeState.h" #include "TraceLog.h" #include "robin_hood.h" using namespace v8; using namespace std; using namespace tns; namespace tns { // ───────────────────────────────────────────────────────────── // Small string helpers (kept file-local — used everywhere below). static inline bool StartsWith(const std::string& s, const char* prefix) { size_t n = strlen(prefix); return s.size() >= n && s.compare(0, n, prefix) == 0; } static inline bool EndsWith(const std::string& value, const std::string& suffix) { if (suffix.size() > value.size()) return false; return std::equal(suffix.rbegin(), suffix.rend(), value.rbegin()); } static inline v8::Local ToV8String(v8::Isolate* isolate, const char* str) { return ArgConverter::ConvertToV8String(isolate, str ? std::string(str) : std::string()); } static inline v8::Local ToV8String(v8::Isolate* isolate, const std::string& str) { return ArgConverter::ConvertToV8String(isolate, str); } // Filesystem: `path` names an existing regular file. static bool IsFile(const std::string& path) { struct stat st; if (stat(path.c_str(), &st) != 0) { return false; } return (st.st_mode & S_IFMT) == S_IFREG; } // Append `ext` if `path` doesn't already carry it. static std::string WithExtension(const std::string& path, const std::string& ext) { if (path.size() >= ext.size() && path.compare(path.size() - ext.size(), ext.size(), ext) == 0) { return path; } return path + ext; } // Application filesystem root for on-disk .mjs/.js resolution. // Mirrors Module.java's getApplicationFilesPath + "/app". Cached after first // JNI call — the value is process-stable, and re-entering JNI on every // resolver hit would add avoidable overhead to hot module-graph walks. static std::string GetApplicationPath() { static std::string cached; static std::once_flag flag; std::call_once(flag, []() { JEnv env; jstring applicationFilesPath = (jstring)env.CallStaticObjectMethod( ModuleInternal::MODULE_CLASS, ModuleInternal::GET_APPLICATION_FILES_PATH_METHOD_ID); if (applicationFilesPath != nullptr) { cached = ArgConverter::jstringToString(applicationFilesPath) + "/app"; } }); return cached; } // Collapse "." and ".." segments, preserving a leading "/". static std::string NormalizeDotSegments(const std::string& path) { std::vector stack; bool absolute = !path.empty() && path[0] == '/'; size_t i = 0; while (i <= path.size()) { size_t j = path.find('/', i); std::string seg = (j == std::string::npos) ? path.substr(i) : path.substr(i, j - i); if (seg.empty() || seg == ".") { // skip } else if (seg == "..") { if (!stack.empty()) stack.pop_back(); } else { stack.push_back(std::move(seg)); } if (j == std::string::npos) break; i = j + 1; } std::string norm = absolute ? "/" : std::string(); for (size_t k = 0; k < stack.size(); k++) { if (k > 0) norm += "/"; norm += stack[k]; } return norm; } // Normalize a filesystem path: collapse duplicate slashes, "./" and "../" // segments. Same intent as iOS's `stringByStandardizingPath`, minus the // Foundation dependency (no HOME expansion, which we never used anyway). static std::string NormalizePath(const std::string& path) { if (path.empty()) return path; return NormalizeDotSegments(path); } // Forward declarations for helpers referenced before their definitions. static const char* ModuleStatusToString(v8::Module::Status status); static void KillAsyncGraphLoadsForIsolate(v8::Isolate* isolate); static void DrainStreamedCompilesForIsolate(v8::Isolate* isolate); static v8::MaybeLocal CompileJsonTextAsEsModule( v8::Isolate* isolate, v8::Local context, const std::string& jsonText, const std::string& registryAbsPath, const std::string& displayUrl); static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate, v8::Local context, const std::string& registryKey); namespace { struct AsyncGraphLoad; // One require(esm) exports facade and the module it wraps. Held as a pair // because identity hashes collide: lookups compare the target handle. struct RequireFacadeEntry { v8::Global target; v8::Global facade; }; // ───────────────────────────────────────────────────────────── // Off-thread compile of large HTTP module bodies // // ScriptStreamingTask::Run() works on the isolate's heap from another thread // (it opens a LocalIsolate), so the isolate must outlive every Run() and a // task that has run must be destroyed before the isolate is disposed. Hence: // - StreamedModuleCompile (StreamedSource + task) is owned by the isolate's // ModuleLoaderState and created, finalized and destroyed under the // isolate's Locker only; // - background threads hold a StreamTicket, which never owns V8 state; // - StreamCompileGate counts Run() calls in flight; teardown closes it and // waits for zero before the event loop stops and the state is destroyed. // The whole body in one chunk. Feed() and the GetMoreData() calls Run() makes // happen on the same thread, Feed() first. V8 takes ownership of the chunk // and delete[]s it. class BodySourceStream : public v8::ScriptCompiler::ExternalSourceStream { public: void Feed(std::unique_ptr chunk, size_t length) { chunk_ = std::move(chunk); length_ = length; } size_t GetMoreData(const uint8_t** src) override { if (chunk_ == nullptr) return 0; *src = chunk_.release(); return length_; } private: std::unique_ptr chunk_; size_t length_ = 0; }; class StreamCompileGate { public: // False once closed: no Run() may start after teardown began. bool TryEnter() { std::lock_guard lock(mutex_); if (closed_) return false; inFlight_++; return true; } void Leave() { std::lock_guard lock(mutex_); if (--inFlight_ == 0) { cv_.notify_all(); } } // Under the isolate's Locker. A Run() that needs a GC parks until the // isolate's thread performs it (CollectionBarrier::AwaitCollectionBackground), // and the waiting thread is not parked itself, so a plain wait could // deadlock: `serviceGcRequests` runs between short waits to let that GC // happen. True when a Run() was in flight. bool CloseAndDrain(const std::function& serviceGcRequests) { std::unique_lock lock(mutex_); closed_ = true; const bool waited = inFlight_ > 0; while (inFlight_ > 0) { if (cv_.wait_for(lock, std::chrono::milliseconds(2), [this] { return inFlight_ == 0; })) { break; } lock.unlock(); serviceGcRequests(); lock.lock(); } return waited; } private: std::mutex mutex_; std::condition_variable cv_; int inFlight_ = 0; bool closed_ = false; }; // The background threads' view of one streamed compile. `stream` and `task` // are owned by the isolate-side StreamedModuleCompile and may be used only // between a successful gate->TryEnter() and the matching Leave(). `ran` and // `ascii` are written before the completion task is posted and read after it // runs. struct StreamTicket { uint64_t id = 0; std::shared_ptr gate; BodySourceStream* stream = nullptr; v8::ScriptCompiler::ScriptStreamingTask* task = nullptr; bool ran = false; bool ascii = false; }; struct StreamedModuleCompile { // Declared before `task`, which points into it. std::unique_ptr source; std::unique_ptr task; }; // Which path each streamable body took, across all isolates. Read by the // debug-only `ns:module` streamedCompileStats() diagnostic. struct StreamedCompileCounters { std::atomic finalized{0}; // background compile finalized std::atomic discarded{0}; // background compile ran, key registered meanwhile std::atomic fellBack{0}; // compiled on the JS thread instead std::atomic running{0}; // Run() calls in progress std::atomic teardownWaits{0}; // isolate teardowns that waited out a Run() }; static StreamedCompileCounters g_streamedCompileCounters; // Set by NoteAppliedV8Flags before any isolate exists. static bool g_eagerStreamedCompiles = false; static size_t g_streamCompileStackBytes = 2 * 1024 * 1024; // ───────────────────────────────────────────────────────────── // Per-isolate module-loader state // // Why per-isolate (not process-global, not thread_local): v8::Global // handles are bound to the isolate that created them; reading their internal // state from a different isolate is undefined behaviour. NS Workers each run // a separate v8::Isolate on their own thread and, under HMR, may fetch the // same URLs the main thread already loaded — a shared map would hand the // worker isolate a Module the main isolate compiled, and V8's linker would // read the cross-isolate export table and emit bogus errors like: // SyntaxError: The requested module 'X' does not provide an export named 'Y' // // Lifetime: the state lives in a RuntimeState slot, so it is destroyed with // the runtime (Runtime::DestroyRuntime → RuntimeState::Clear), on the // runtime's own thread while the isolate is still alive — which lets the // v8::Global members Reset safely in their own destructors and leaves nothing // to static/thread destructors, where a post-disposal Reset would crash. // Access from the isolate's own thread only, per the slot contract. struct ModuleLoaderState { ModuleHandleMap registry; // canonical key -> compiled module // What the dev client taught THIS isolate's loader: import map, // canonicalization vocabulary, volatile patterns. LoaderVocabulary vocabulary; // In-flight async graph walks; entries are weak so a finished load frees // itself. A pending background fetch completion can hold a load's // shared_ptr past teardown, so QuiesceModuleLoadsForIsolate must flag these // dead and Reset their context Globals while the isolate is still alive — // the slot destructor alone is not enough for them. std::vector> asyncGraphLoads; // HTTP dynamic imports currently fetching/evaluating, for coalescing. robin_hood::unordered_set modulesInFlight; // Dynamic HTTP import waiters: resolve to the module namespace. robin_hood::unordered_map>> httpDynamicWaiters; // Reverse index: v8::Module::GetIdentityHash() -> registry keys, so // module→key lookups (resolver referrer discovery, import.meta) are O(1) // instead of a scan of the whole registry. Hashes collide, so a bucket holds // candidates; FindKeyForModule confirms each against the registry and prunes // the ones it no longer backs, so a stale candidate can never answer a // lookup. robin_hood::unordered_map> keysByModuleHash; // 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 // must never outlive the module it re-exports (UnindexRegistryKey drops the // entry as the target stops being the registry's answer for its key). robin_hood::unordered_map> requireFacadesByTargetHash; // Holds the facade target across that facade's InstantiateModule and nothing // else — the facade's resolve callback is the only reader. v8::Global pendingFacadeTarget; // Streamed compiles issued and not yet finalized or discarded, by ticket id. // QuiesceModuleLoadsForIsolate drains the gate before any of these die. std::shared_ptr streamGate = std::make_shared(); robin_hood::unordered_map> streamedCompiles; uint64_t nextStreamedCompileId = 1; }; // This isolate's loader state, or null once teardown has begun — callers must // bail, not recreate state. ModuleLoaderState* ModuleLoaderStateFor(v8::Isolate* isolate) { if (isolate == nullptr) return nullptr; return RuntimeState::For(isolate); } // Record `key` as a candidate for `mod`'s identity hash. Call alongside every // registry insert. void IndexRegisteredModule(ModuleLoaderState& state, const std::string& key, v8::Local mod) { if (mod.IsEmpty()) return; auto& keys = state.keysByModuleHash[mod->GetIdentityHash()]; if (std::find(keys.begin(), keys.end(), key) == keys.end()) { keys.push_back(key); } } // Drop any facade wrapping `target`. Called as the target stops being the // registry's answer for its key: a facade whose re-export source is gone would // serve a dead namespace. void DropRequireFacadesForTarget(ModuleLoaderState& state, v8::Isolate* isolate, v8::Local target) { if (target.IsEmpty()) return; auto bucketIt = state.requireFacadesByTargetHash.find(target->GetIdentityHash()); if (bucketIt == state.requireFacadesByTargetHash.end()) return; auto& entries = bucketIt->second; for (auto it = entries.begin(); it != entries.end();) { if (it->target.Get(isolate) == target) { it = entries.erase(it); } else { ++it; } } if (entries.empty()) { state.requireFacadesByTargetHash.erase(bucketIt); } } // Drop `key` from the bucket of whatever module the registry holds under it // right now. Call before replacing or erasing that entry, while the outgoing // handle is still reachable — afterwards its hash is unrecoverable. void UnindexRegistryKey(ModuleLoaderState& state, v8::Isolate* isolate, const std::string& key) { auto regIt = state.registry.find(key); if (regIt == state.registry.end() || regIt->second.IsEmpty()) return; v8::Local outgoing = regIt->second.Get(isolate); if (outgoing.IsEmpty()) return; DropRequireFacadesForTarget(state, isolate, outgoing); auto bucketIt = state.keysByModuleHash.find(outgoing->GetIdentityHash()); if (bucketIt == state.keysByModuleHash.end()) return; auto& keys = bucketIt->second; keys.erase(std::remove(keys.begin(), keys.end(), key), keys.end()); if (keys.empty()) { state.keysByModuleHash.erase(bucketIt); } } // The registry key whose live entry is `mod`, or empty. Prunes candidates the // registry no longer confirms. std::string FindKeyForModule(ModuleLoaderState& state, v8::Isolate* isolate, v8::Local mod) { if (mod.IsEmpty()) return std::string(); auto bucketIt = state.keysByModuleHash.find(mod->GetIdentityHash()); if (bucketIt == state.keysByModuleHash.end()) return std::string(); auto& keys = bucketIt->second; for (auto it = keys.begin(); it != keys.end();) { auto regIt = state.registry.find(*it); if (regIt == state.registry.end() || regIt->second.IsEmpty()) { it = keys.erase(it); continue; } if (regIt->second.Get(isolate) == mod) { return *it; } ++it; } if (keys.empty()) { state.keysByModuleHash.erase(bucketIt); } return std::string(); } } // namespace std::string LookupModuleKeyForModule(v8::Isolate* isolate, v8::Local mod) { auto* state = ModuleLoaderStateFor(isolate); if (state == nullptr) return std::string(); return FindKeyForModule(*state, isolate, mod); } namespace { // The single module request in the facade source, and the source itself. Both // match Node's required_module_facade_source_string so the semantics (live // bindings, enumerable re-exports, overridable __esModule) stay identical. constexpr const char* kRequireFacadeSpecifier = "original"; constexpr const char* kRequireFacadeSource = "export * from 'original'; export { default } from 'original'; " "export const __esModule = true;"; // Resolves the facade's one request. Passed only to a facade's // InstantiateModule, so the general resolver never sees 'original' and user // code can never reach this slot. v8::MaybeLocal ResolveRequireFacadeTarget( v8::Local context, v8::Local specifier, v8::Local /*import_assertions*/, v8::Local /*referrer*/) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); auto* state = ModuleLoaderStateFor(isolate); v8::String::Utf8Value specUtf8(isolate, specifier); const std::string spec = *specUtf8 ? *specUtf8 : ""; if (state == nullptr || state->pendingFacadeTarget.IsEmpty() || spec != kRequireFacadeSpecifier) { DEBUG_WRITE_FORCE("FATAL: require(esm) facade resolve for '%s' with no pending target", spec.c_str()); isolate->ThrowException(v8::Exception::Error(ArgConverter::ConvertToV8String( isolate, "require(esm) facade could not be linked to its target module"))); return v8::MaybeLocal(); } return v8::MaybeLocal(state->pendingFacadeTarget.Get(isolate)); } } // namespace v8::MaybeLocal GetOrCreateRequireFacade( v8::Isolate* isolate, v8::Local context, v8::Local target, const std::string& targetCanonicalPath) { if (target.IsEmpty()) return v8::MaybeLocal(); auto* state = ModuleLoaderStateFor(isolate); if (state == nullptr) return v8::MaybeLocal(); auto bucketIt = state->requireFacadesByTargetHash.find(target->GetIdentityHash()); if (bucketIt != state->requireFacadesByTargetHash.end()) { for (auto& entry : bucketIt->second) { if (entry.target.Get(isolate) == target) { return v8::MaybeLocal(entry.facade.Get(isolate)); } } } v8::EscapableHandleScope hs(isolate); const std::string facadeUrl = "ns:require-facade:" + targetCanonicalPath; v8::Local urlV8; if (!v8::String::NewFromUtf8(isolate, facadeUrl.c_str(), v8::NewStringType::kNormal) .ToLocal(&urlV8)) { return v8::MaybeLocal(); } v8::ScriptOrigin origin(urlV8, 0, 0, false, -1, v8::Local(), false, false, true /* is_module */); v8::ScriptCompiler::Source source( ArgConverter::ConvertToV8String(isolate, kRequireFacadeSource), origin); v8::TryCatch tc(isolate); v8::Local facade; if (!v8::ScriptCompiler::CompileModule(isolate, &source).ToLocal(&facade)) { throw NativeScriptException( tc, "Cannot compile the require() facade for " + targetCanonicalPath); } bool linked = false; { // The slot must be clear again whichever way instantiation ends. struct PendingTargetScope { ModuleLoaderState* state; ~PendingTargetScope() { state->pendingFacadeTarget.Reset(); } } pendingScope{state}; state->pendingFacadeTarget.Reset(isolate, target); linked = facade->InstantiateModule(context, &ResolveRequireFacadeTarget) .FromMaybe(false); } if (!linked) { throw NativeScriptException( tc, "Cannot link the require() facade for " + targetCanonicalPath); } // Three re-export statements over an already-evaluated module: trivially // synchronous, so the strict policy's settled-promise requirement holds. ModuleEvaluationOptions evalOptions; evalOptions.policy = ModuleEvaluationPolicy::kSyncStrict; EvaluateModuleGraph(isolate, context, facade, facadeUrl, evalOptions); // The facade is deliberately absent from the registry and the identity-hash // index: nothing resolves to it by name, and its source has no import.meta or // dynamic import, so no host callback ever needs to find it. RequireFacadeEntry entry; entry.target.Reset(isolate, target); entry.facade.Reset(isolate, facade); state->requireFacadesByTargetHash[target->GetIdentityHash()].push_back( std::move(entry)); return hs.Escape(facade); } void IndexModuleForIsolate(v8::Isolate* isolate, const std::string& canonicalKey, v8::Local mod) { auto* state = ModuleLoaderStateFor(isolate); if (state == nullptr) return; IndexRegisteredModule(*state, canonicalKey, mod); } void UnindexModuleForIsolate(v8::Isolate* isolate, const std::string& canonicalKey) { auto* state = ModuleLoaderStateFor(isolate); if (state == nullptr) return; UnindexRegistryKey(*state, isolate, canonicalKey); } static bool IsVolatileUrl(const LoaderVocabulary& vocabulary, const std::string& url); // ───────────────────────────────────────────────────────────── // AdoptThenable // // Turn any thenable value into a real v8::Promise. Promises returned by // V8 itself (Module::Evaluate) are genuine and take the fast path; // user-space thenables (e.g. Proxy'd Promises) fail v8::Value::IsPromise // but adopting them via Promise::Resolver::New + Resolve preserves their // state. static v8::MaybeLocal AdoptThenable(v8::Isolate* isolate, v8::Local context, v8::Local value) { if (value.IsEmpty()) return v8::MaybeLocal(); if (value->IsPromise()) return value.As(); if (!value->IsObject()) return v8::MaybeLocal(); v8::Local thenVal; if (!value.As() ->Get(context, ArgConverter::ConvertToV8String(isolate, "then")) .ToLocal(&thenVal) || !thenVal->IsFunction()) { return v8::MaybeLocal(); } v8::Local adopter; if (!v8::Promise::Resolver::New(context).ToLocal(&adopter) || adopter->Resolve(context, value).IsNothing()) { return v8::MaybeLocal(); } return adopter->GetPromise(); } // ───────────────────────────────────────────────────────────── // Compile helpers // "message (line L:C)" for a caught exception, or empty. The line/column are // the part no caller can reconstruct from a failure code. static std::string DescribeCaughtError(v8::Isolate* isolate, v8::Local context, const v8::TryCatch& tc) { if (!tc.HasCaught()) return std::string(); v8::Local message = tc.Message(); if (message.IsEmpty()) return std::string(); v8::String::Utf8Value text(isolate, message->Get()); std::string described = *text ? *text : ""; int line = message->GetLineNumber(context).FromMaybe(0); if (line > 0) { described += " (line " + std::to_string(line) + ":" + std::to_string(message->GetStartColumn()) + ")"; } return described; } // Compile-only variant used inside ResolveModuleCallback. Compiles a // v8::Module and registers it under urlStr but does NOT instantiate or // evaluate. V8 is currently instantiating the importer and will handle // instantiation of this dependency. // // On compile failure the exception is left PENDING, the same contract as // ModuleInternal::CompileFileEsModule: it names the file, line and column, // which nothing downstream can reconstruct. A caller that cannot let it // propagate must consume it through its own TryCatch and route the text into // its own failure channel — never drop it. // // `compile` produces the module for `origin`; it is not called when the key is // already registered. using ModuleCompileStep = std::function(const v8::ScriptOrigin& origin)>; static v8::MaybeLocal CompileAndRegisterModule( v8::Isolate* isolate, v8::Local context, const std::string& urlStr, const ModuleCompileStep& compile) { v8::EscapableHandleScope hs(isolate); auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) { return v8::MaybeLocal(); } auto& registry = moduleState->registry; const std::string registryKey = CanonicalizeRegistryKey(urlStr); // Checked before compiling: recompiling a key that is already registered // would mint a second module identity while importers hold the first. auto itExisting = registry.find(registryKey); if (itExisting != registry.end()) { v8::Local existing = itExisting->second.Get(isolate); if (!existing.IsEmpty()) { return hs.Escape(existing); } } v8::Local urlV8; if (!v8::String::NewFromUtf8(isolate, urlStr.c_str(), v8::NewStringType::kNormal) .ToLocal(&urlV8)) { return v8::MaybeLocal(); } v8::ScriptOrigin origin(urlV8, 0, 0, false, -1, v8::Local(), false, false, true /* is_module */); v8::Local mod; { v8::TryCatch tcCompile(isolate); if (!compile(origin).ToLocal(&mod)) { TNS_DEBUG(Esm, "[http-esm][compile][fail] %s %s", urlStr.c_str(), DescribeCaughtError(isolate, context, tcCompile).c_str()); tcCompile.ReThrow(); return v8::MaybeLocal(); } } UnindexRegistryKey(*moduleState, isolate, registryKey); registry[registryKey].Reset(isolate, mod); IndexRegisteredModule(*moduleState, registryKey, mod); return hs.Escape(mod); } static v8::MaybeLocal CompileModuleForResolveRegisterOnly( v8::Isolate* isolate, v8::Local context, const std::string& code, const std::string& urlStr) { return CompileAndRegisterModule( isolate, context, urlStr, [isolate, &code](const v8::ScriptOrigin& origin) { v8::ScriptCompiler::Source src( ArgConverter::ConvertToV8String(isolate, code), origin); return v8::ScriptCompiler::CompileModule(isolate, &src); }); } // A module body the isolate keeps as an external one-byte string. Valid only // for pure-ASCII bodies: a one-byte string is Latin-1, which matches the // UTF-8 bytes the streamed compile parsed only below 0x80. The bytes live // outside the V8 heap, so they are charged as external memory for as long as // the string holds them. class OwnedAsciiSource : public v8::String::ExternalOneByteStringResource { public: OwnedAsciiSource(std::string body, v8::Isolate* isolate) : body_(std::move(body)), isolate_(isolate) {} const char* data() const override { return body_.data(); } size_t length() const override { return body_.size(); } // Under the isolate's Locker, with the string held by a handle: the // increase can run a collection before it returns. void Charge() { accounter_.Increase(isolate_, body_.size()); charged_ = true; } // V8 calls this right before Dispose(), possibly on a GC worker thread or // during heap teardown; the decrease is a single atomic update. void Unaccount(v8::Isolate* isolate) override { if (charged_) { accounter_.Decrease(isolate, body_.size()); charged_ = false; } } private: std::string body_; v8::Isolate* isolate_; v8::ExternalMemoryAccounter accounter_; bool charged_ = false; }; // Finalizes a streamed compile whose ScriptStreamingTask::Run() has returned. // `body` must be the exact bytes the stream was fed. The compile is discarded // unfinalized when `urlStr` is registered already. static v8::MaybeLocal CompileStreamedModuleRegisterOnly( v8::Isolate* isolate, v8::Local context, StreamedModuleCompile& streamed, std::string body, bool ascii, const std::string& urlStr) { bool finalized = false; v8::MaybeLocal mod = CompileAndRegisterModule( isolate, context, urlStr, [isolate, context, &streamed, &body, ascii, &finalized](const v8::ScriptOrigin& origin) { finalized = true; v8::Local sourceText; if (ascii) { auto* resource = new OwnedAsciiSource(std::move(body), isolate); if (!v8::String::NewExternalOneByte(isolate, resource).ToLocal(&sourceText)) { delete resource; return v8::MaybeLocal(); } resource->Charge(); } else { sourceText = ArgConverter::ConvertToV8String(isolate, body); } return v8::ScriptCompiler::CompileModule(context, streamed.source.get(), sourceText, origin); }); (finalized ? g_streamedCompileCounters.finalized : g_streamedCompileCounters.discarded) .fetch_add(1, std::memory_order_relaxed); return mod; } // Returns null once teardown has begun. ModuleHandleMap* ModuleRegistryFor(v8::Isolate* isolate) { auto* state = ModuleLoaderStateFor(isolate); return state == nullptr ? nullptr : &state->registry; } // Neutralize any in-flight async graph loads for `isolate`: their fetch // completions check the dead flag before touching V8, and their context // Globals are Reset here, while the isolate is still alive. Background compiles // are waited out for the same reason. The rest of the loader state is // destroyed with the isolate's RuntimeState. void QuiesceModuleLoadsForIsolate(v8::Isolate* isolate) { KillAsyncGraphLoadsForIsolate(isolate); DrainStreamedCompilesForIsolate(isolate); } // The calling isolate's vocabulary, or null once teardown has begun. static LoaderVocabulary* VocabularyForCurrentIsolate() { auto* state = ModuleLoaderStateFor(v8::Isolate::TryGetCurrent()); return state != nullptr ? &state->vocabulary : nullptr; } std::string CanonicalizeRegistryKey(const std::string& key) { if (key.empty()) return key; std::string registryKey; const char* classification = "path"; bool traceEvenWithoutChange = false; // Before any other scheme test: an http(s) URL in a spelling other than the // key's (`HTTP://`, `http:/host`) must not fall through as a custom scheme // and give the module a second identity. const std::string httpUrl = NormalizeHttpModuleUrl(key); if (!httpUrl.empty()) { registryKey = CanonicalizeNormalizedHttpUrlKey(httpUrl); classification = "http"; } else if (StartsWith(key, "file://")) { // The path is spelled verbatim, so a '#' before the query is part of it; // only after the query does one start a fragment. const size_t queryAt = key.find('?'); registryKey = NormalizePath(FileModulePath(key)) + (queryAt == std::string::npos ? std::string() : ModuleQuery(key.substr(queryAt))); classification = "file-url"; } else if (StartsWith(key, "blob:")) { registryKey = key; classification = "blob"; traceEvenWithoutChange = true; } else { // Preserve non-filesystem module namespaces such as node: // so synthetic/in-memory modules keep their exact registry identity. size_t schemePos = key.find(':'); size_t slashPos = key.find('/'); if (schemePos != std::string::npos && (slashPos == std::string::npos || schemePos < slashPos)) { registryKey = key; classification = "custom-scheme"; traceEvenWithoutChange = true; } else { // A file module key is its path plus a query; the query's slashes and // dot segments are not path syntax. const std::string path = FileModulePath(key); registryKey = NormalizePath(path) + key.substr(path.size()); } } if (traceEvenWithoutChange || registryKey != key) { TNS_DEBUG(Esm, "[resolver][registry-key][%s] raw=%s key=%s", classification, key.c_str(), registryKey.c_str()); } return registryKey; } v8::MaybeLocal LoadHttpModuleForUrl(v8::Isolate* isolate, v8::Local context, const std::string& requestedUrl) { auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) { return v8::MaybeLocal(); } auto& registry = moduleState->registry; const std::string registryKey = CanonicalizeNormalizedHttpUrlKey(requestedUrl); TNS_DEBUG(Esm, "[http-esm][load][begin] request=%s key=%s", requestedUrl.c_str(), registryKey.c_str()); auto itExisting = registry.find(registryKey); if (itExisting != registry.end()) { v8::Local existing = itExisting->second.Get(isolate); if (!existing.IsEmpty() && existing->GetStatus() != v8::Module::kErrored) { TNS_DEBUG(Esm, "[http-esm][load][cache-hit] key=%s", registryKey.c_str()); return v8::MaybeLocal(existing); } TNS_DEBUG(Esm, "[http-esm][load][drop-errored] key=%s", registryKey.c_str()); RemoveModuleFromRegistry(isolate, registryKey); } // Reaching this point means the graph walk did not discover this URL, so the // module is about to be fetched synchronously, blocking the JS thread for a // whole round trip. That is an invariant violation, not a mode — always // visible, in every build, so it cannot hide behind a disabled trace // category. The fallback itself stays: correctness first, diagnosis loud. DEBUG_WRITE_FORCE( "NativeScript: module graph walk missed %s — falling back to a blocking " "synchronous fetch. This should not happen; please report it.", requestedUrl.c_str()); ModuleFetchResult fetched; if (!HttpFetchModule(requestedUrl, fetched)) { TNS_DEBUG(Esm, "[http-esm][load][fetch-fail] request=%s key=%s status=%d", requestedUrl.c_str(), registryKey.c_str(), fetched.status); // The classifier's reason names the URL and the cause (status, MIME or // transport); a generic message here would lose all of it. V8 requires an // exception whenever a resolve callback returns empty, so this is thrown // in every build. isolate->ThrowException(v8::Exception::Error( ArgConverter::ConvertToV8String(isolate, fetched.failureReason))); return v8::MaybeLocal(); } if (fetched.kind == ModuleResponseKind::kJson) { return CompileJsonTextAsEsModule(isolate, context, fetched.body, registryKey, requestedUrl); } v8::Local loaded; { v8::TryCatch tcCompile(isolate); if (!CompileModuleForResolveRegisterOnly(isolate, context, fetched.body, registryKey) .ToLocal(&loaded)) { TNS_DEBUG(Esm, "[http-esm][load][compile-fail] request=%s key=%s bytes=%zu", requestedUrl.c_str(), registryKey.c_str(), fetched.body.size()); if (tcCompile.HasCaught()) { // The compile error names the module, line and column; replacing it // with a generic "compile failed" would strictly lose information. tcCompile.ReThrow(); } else { std::string msg = "HTTP import compile failed: " + requestedUrl; isolate->ThrowException(v8::Exception::Error( ArgConverter::ConvertToV8String(isolate, msg))); } return v8::MaybeLocal(); } } TNS_DEBUG(Esm, "[http-esm][load][ok] request=%s key=%s type=%s bytes=%zu", requestedUrl.c_str(), registryKey.c_str(), fetched.contentType.c_str(), fetched.body.size()); return loaded; } // ───────────────────────────────────────────────────────────── // Import map helpers // Read one imports-shaped section. Every rejection names the offending key so // a bad map is fixable from the message alone. static bool ParseImportMapEntries(v8::Isolate* isolate, v8::Local context, v8::Local source, const std::string& sectionLabel, ImportMapEntries* out, std::string* error) { v8::Local keys; if (!source->GetOwnPropertyNames(context).ToLocal(&keys)) { *error = sectionLabel + ": could not be read"; return false; } for (uint32_t i = 0; i < keys->Length(); i++) { v8::Local keyVal; if (!keys->Get(context, i).ToLocal(&keyVal) || !keyVal->IsString()) { *error = sectionLabel + ": every key must be a string"; return false; } // V8's JSON parser accepts lone surrogates, which have no UTF-8 form, so // a key or target holding one is reported as not a string. const std::optional keyUtf8 = ToExactUtf8(isolate, keyVal.As()); if (!keyUtf8.has_value()) { *error = sectionLabel + ": every key must be a string"; return false; } const std::string& specifier = *keyUtf8; if (specifier.empty()) { *error = sectionLabel + ": a specifier key must not be empty"; return false; } v8::Local value; if (!source->Get(context, keyVal).ToLocal(&value) || !value->IsString()) { *error = sectionLabel + ": the target for '" + specifier + "' must be a string"; return false; } const std::optional valueUtf8 = ToExactUtf8(isolate, value.As()); if (!valueUtf8.has_value()) { *error = sectionLabel + ": the target for '" + specifier + "' must be a string"; return false; } const std::string& target = *valueUtf8; if (target.empty()) { *error = sectionLabel + ": the target for '" + specifier + "' must not be empty"; return false; } // A target resolves as a filesystem path or is fetched as a URL, and both // go through C-string APIs that would end it at U+0000. if (target.find('\0') != std::string::npos) { *error = sectionLabel + ": the target for '" + specifier + "' must not contain U+0000"; return false; } // A trailing-slash key maps a whole subtree, so its target must name one // too — otherwise the remainder would be pasted onto a file path. if (specifier.back() == '/' && target.back() != '/') { *error = sectionLabel + ": the target for '" + specifier + "' must end with '/' because the specifier key does"; return false; } (*out)[specifier] = target; } return true; } // A scope key matches referrer registry keys by plain prefix, and an http(s) // referrer key is spelled by NormalizeHttpModuleUrl, so an http(s) scope key // is spelled the same way. A key written with no path at all stays path-less: // the parser gives it the path "/", which would narrow the prefix. Any other // trailing '/' is the parser's and stays, so dot segments can't widen a scope // past a path-segment boundary. static std::string ImportMapScopePrefix(const std::string& scopeKey) { std::string prefix = NormalizeHttpModuleUrl(scopeKey); if (prefix.empty()) { return scopeKey; } const size_t colon = scopeKey.find(':'); const size_t authority = colon == std::string::npos ? std::string::npos : scopeKey.find_first_not_of("/\\", colon + 1); const bool writtenWithoutPath = authority != std::string::npos && scopeKey.find_first_of("/\\?#", authority) == std::string::npos; if (writtenWithoutPath && prefix.back() == '/') { prefix.pop_back(); } return prefix; } // Parse without touching the live map. On any failure `error` explains what is // wrong and `out` is meaningless — the caller keeps whatever it already had. // V8's JSON parser stands in for iOS's NSJSONSerialization: escapes, nesting // and malformed input are handled by the engine rather than a hand-rolled // scanner, and this always runs on the isolate's own thread. static bool ParseImportMap(v8::Isolate* isolate, const std::string& json, ParsedImportMap* out, std::string* error) { if (json.empty()) { *error = "an import map must be a non-empty JSON object"; return false; } v8::Local context = isolate->GetCurrentContext(); v8::TryCatch tc(isolate); v8::Local parsed; if (!v8::JSON::Parse(context, ArgConverter::ConvertToV8String(isolate, json)) .ToLocal(&parsed)) { std::string detail = DescribeCaughtError(isolate, context, tc); *error = "an import map must be valid JSON" + (detail.empty() ? "" : ": " + detail); return false; } if (!parsed->IsObject() || parsed->IsArray()) { *error = "an import map must be a JSON object"; return false; } v8::Local top = parsed.As(); // Only the map's OWN keys are sections; reading through the prototype would // let a polluted Object.prototype smuggle one in. v8::Local sections; if (!top->GetOwnPropertyNames(context).ToLocal(§ions)) { *error = "an import map must be a JSON object"; return false; } bool hasImports = false; bool hasScopes = false; for (uint32_t i = 0; i < sections->Length(); i++) { v8::Local sectionVal; std::string name; if (sections->Get(context, i).ToLocal(§ionVal) && sectionVal->IsString()) { name = ToExactUtf8(isolate, sectionVal.As()).value_or(std::string()); } if (name == "imports") { hasImports = true; } else if (name == "scopes") { hasScopes = true; } else { *error = "unsupported import-map section '" + name + "'; only \"imports\" and \"scopes\" are supported"; return false; } } v8::Local imports; if (hasImports && top->Get(context, ArgConverter::ConvertToV8String(isolate, "imports")).ToLocal(&imports) && !imports->IsUndefined()) { if (!imports->IsObject() || imports->IsArray()) { *error = "the \"imports\" section must be an object"; return false; } if (!ParseImportMapEntries(isolate, context, imports.As(), "imports", &out->imports, error)) { return false; } } v8::Local scopes; if (hasScopes && top->Get(context, ArgConverter::ConvertToV8String(isolate, "scopes")).ToLocal(&scopes) && !scopes->IsUndefined()) { if (!scopes->IsObject() || scopes->IsArray()) { *error = "the \"scopes\" section must be an object"; return false; } v8::Local scopesObj = scopes.As(); v8::Local scopeKeys; if (!scopesObj->GetOwnPropertyNames(context).ToLocal(&scopeKeys)) { *error = "the \"scopes\" section must be an object"; return false; } for (uint32_t i = 0; i < scopeKeys->Length(); i++) { v8::Local scopeKeyVal; if (!scopeKeys->Get(context, i).ToLocal(&scopeKeyVal) || !scopeKeyVal->IsString()) { *error = "scopes: every scope key must be a string"; return false; } const std::optional scopeUtf8 = ToExactUtf8(isolate, scopeKeyVal.As()); if (!scopeUtf8.has_value()) { *error = "scopes: every scope key must be a string"; return false; } const std::string& scopePrefix = *scopeUtf8; if (scopePrefix.empty()) { *error = "scopes: a scope key must not be empty"; return false; } v8::Local scopeMap; if (!scopesObj->Get(context, scopeKeyVal).ToLocal(&scopeMap) || !scopeMap->IsObject() || scopeMap->IsArray()) { *error = "scopes: the map for scope '" + scopePrefix + "' must be an object"; return false; } ImportMapEntries entries; if (!ParseImportMapEntries(isolate, context, scopeMap.As(), "scope '" + scopePrefix + "'", &entries, error)) { return false; } out->scopes.emplace_back(ImportMapScopePrefix(scopePrefix), std::move(entries)); } } // Most specific first: a longer prefix is the more specific scope, and the // key comparison keeps the order deterministic for equal-length prefixes. std::sort(out->scopes.begin(), out->scopes.end(), [](const std::pair& a, const std::pair& b) { if (a.first.size() != b.first.size()) { return a.first.size() > b.first.size(); } return a.first > b.first; }); return true; } // Swaps in an already-parsed map. Split from SetImportMap so configureLoader // can validate every section before installing any of them. static bool InstallParsedImportMap(ParsedImportMap parsedMap, std::string* error) { LoaderVocabulary* vocabulary = VocabularyForCurrentIsolate(); if (vocabulary == nullptr) { if (error != nullptr) { *error = "the isolate is shutting down"; } return false; } vocabulary->importMap = std::move(parsedMap); TNS_DEBUG(Esm, "[import-map] loaded %lu entries, %lu scopes", (unsigned long)vocabulary->importMap.imports.size(), (unsigned long)vocabulary->importMap.scopes.size()); return true; } bool SetImportMap(const std::string& json, std::string* error) { // Parse-validate-swap: the live vocabulary is replaced only once a complete // map has been built, so a rejected update leaves resolution exactly as it // was rather than silently emptying it. ParsedImportMap parsedMap; std::string localError; std::string* sink = error != nullptr ? error : &localError; if (!ParseImportMap(v8::Isolate::GetCurrent(), json, &parsedMap, sink)) { return false; } return InstallParsedImportMap(std::move(parsedMap), sink); } void SetVolatilePatterns(const std::vector& patterns) { LoaderVocabulary* vocabulary = VocabularyForCurrentIsolate(); if (vocabulary == nullptr) return; vocabulary->volatilePatterns = patterns; TNS_DEBUG(Esm, "[import-map] volatile patterns: %lu", (unsigned long)vocabulary->volatilePatterns.size()); } LoaderVocabulary CaptureLoaderVocabulary(v8::Isolate* isolate) { auto* state = ModuleLoaderStateFor(isolate); return state != nullptr ? state->vocabulary : LoaderVocabulary(); } void InstallLoaderVocabulary(v8::Isolate* isolate, LoaderVocabulary vocabulary) { auto* state = ModuleLoaderStateFor(isolate); if (state == nullptr) return; state->vocabulary = std::move(vocabulary); TNS_DEBUG(Esm, "[import-map] inherited %lu entries, %lu scopes, %lu volatile patterns", (unsigned long)state->vocabulary.importMap.imports.size(), (unsigned long)state->vocabulary.importMap.scopes.size(), (unsigned long)state->vocabulary.volatilePatterns.size()); } const CanonicalizationConfig* CanonicalizationConfigForCurrentIsolate() { const LoaderVocabulary* vocabulary = VocabularyForCurrentIsolate(); if (vocabulary == nullptr || !vocabulary->canonicalizationConfigured) { return nullptr; } return &vocabulary->canonicalization; } void SetCanonicalizationConfig(CanonicalizationConfig config) { LoaderVocabulary* vocabulary = VocabularyForCurrentIsolate(); if (vocabulary == nullptr) return; vocabulary->canonicalization = std::move(config); vocabulary->canonicalizationConfigured = true; TNS_DEBUG(Esm, "[ns:module configureLoader] canonicalization set (strip=%lu " "devPrefixes=%lu preserve=%lu)", (unsigned long)vocabulary->canonicalization.stripParams.size(), (unsigned long)vocabulary->canonicalization.devPathPrefixes.size(), (unsigned long)vocabulary->canonicalization.preserveQueryPrefixes.size()); } static bool IsVolatileUrl(const LoaderVocabulary& vocabulary, const std::string& url) { for (const auto& pat : vocabulary.volatilePatterns) { if (url.find(pat) != std::string::npos) return true; } return false; } // Look up a specifier in ONE import-map section: exact match first, then the // longest trailing-slash prefix entry, whose remainder is appended to the // target. Returns empty when the section has no answer. static std::string LookupInEntries(const ImportMapEntries& entries, const std::string& specifier) { auto it = entries.find(specifier); if (it != entries.end()) { TNS_DEBUG(Esm, "[import-map] exact: %s -> %s", specifier.c_str(), it->second.c_str()); return it->second; } std::string bestKey; std::string bestValue; for (const auto& kv : entries) { const std::string& key = kv.first; if (key.back() != '/') continue; // only trailing-slash entries map subtrees if (specifier.size() > key.size() && specifier.compare(0, key.size(), key) == 0) { if (key.size() > bestKey.size()) { bestKey = key; bestValue = kv.second; } } } if (bestKey.empty()) return ""; std::string resolved = bestValue + specifier.substr(bestKey.size()); TNS_DEBUG(Esm, "[import-map] prefix: %s -> %s (via %s)", specifier.c_str(), resolved.c_str(), bestKey.c_str()); return resolved; } // The import-map resolution cascade: the most specific applicable scope first, // then progressively less specific ones, then the top-level imports — each // consulted with the same per-section lookup. // // 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 — 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 LoaderVocabulary& vocabulary, const std::string& specifier, const std::string& importerKey) { 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) { continue; } std::string mapped = LookupInEntries(scope.second, specifier); if (!mapped.empty()) { TNS_DEBUG(Esm, "[import-map] scope '%s' matched referrer %s", prefix.c_str(), referrerKey.c_str()); return mapped; } } return LookupInEntries(vocabulary.importMap.imports, specifier); } // ───────────────────────────────────────────────────────────── // The shared resolution seam // // One module specifier resolved to something the loader can act on. Both // ResolveModuleCallback and the graph walk go through this, so a module gets // the same registry key whichever of them reaches it first — a divergence here // mints two identities for one file. // // Pure computation: it consults the import map and the filesystem, but never // compiles, registers, fetches, or throws. struct ModuleResolution { enum class Kind { kUnresolved, // nothing locatable; the caller decides how to report it kBuiltin, // ns:/node: — served from the builtin registry kHttp, // absolute http(s) URL kFile, // absolute filesystem path, confirmed to be a regular file }; Kind kind = Kind::kUnresolved; std::string url; // kHttp 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 // the complete error message, and nothing was probed on disk for it. std::string blocked; }; static std::string UnresolvedModuleMessage(const ModuleResolution& resolution) { if (!resolution.blocked.empty()) return resolution.blocked; return "Cannot find module '" + resolution.specifier + "' (tried " + resolution.attempted + ")"; } struct UrlSpecifier { enum class Kind { kHttpUrl, // an http(s) URL kOtherUrl, // an absolute URL with another scheme kInvalid, // a relative form that does not parse against the base kBare, // neither relative nor an absolute URL }; Kind kind = Kind::kBare; std::string href; // kHttpUrl, kOtherUrl }; // HTML "resolve a module specifier", import map aside, against an importer // whose URL is `baseUrl`. Only '/', './' and '../' prefixes are relative // ('//host/x' is a '/' form); '.x', '.' and '..' are bare. static UrlSpecifier ResolveModuleSpecifierAgainstUrl(const std::string& spec, const std::string& baseUrl) { UrlSpecifier result; const bool relative = StartsWith(spec, "/") || StartsWith(spec, "./") || StartsWith(spec, "../"); const ModuleUrl url = ParseModuleUrl(spec, relative ? baseUrl : std::string()); result.href = url.href; if (!url.parsed) { result.kind = relative ? UrlSpecifier::Kind::kInvalid : UrlSpecifier::Kind::kBare; } else { result.kind = url.http ? UrlSpecifier::Kind::kHttpUrl : UrlSpecifier::Kind::kOtherUrl; } return result; } static std::string BlockedFromHttpMessage(const std::string& rawSpec, const std::string& referrerKey, const char* reason) { return "Cannot resolve module specifier \"" + rawSpec + "\" imported from " + referrerKey + ": " + reason; } // `referrerKey` is the registry key of the importing module — empty when the // importer is unknown (a dynamic import with no compiled referrer). static ModuleResolution ResolveSpecifierToPath(const std::string& rawSpec, const std::string& referrerKey) { ModuleResolution result; if (rawSpec.empty()) return result; // Builtins resolve before any path handling, so a file can never shadow one. // The whole scheme is claimed, registered or not, so an unknown `node:` name // fails as a missing builtin instead of falling through to the filesystem. if (NsBuiltinModules::IsBuiltinScheme(rawSpec)) { result.kind = ModuleResolution::Kind::kBuiltin; result.specifier = rawSpec; return result; } // blob: names a registry key, never a filesystem path — the callers' blob // branches own it, so it must not burn stat() probes under the app root. if (StartsWith(rawSpec, "blob:")) { result.specifier = rawSpec; return result; } std::string spec = rawSpec; TNS_DEBUG(Esm, "[resolver][spec] %s", spec.c_str()); // The import map is consulted before any other resolution: bare specifiers // resolve through it to vendor or HTTP URLs. A client that rewrites // specifiers must map every form it emits — keys are matched literally. const LoaderVocabulary* vocabularyPtr = VocabularyForCurrentIsolate(); bool mappedByImportMap = false; if (vocabularyPtr != nullptr && !vocabularyPtr->importMap.empty()) { const LoaderVocabulary& vocabulary = *vocabularyPtr; std::string mapped = LookupImportMap(vocabulary, spec, referrerKey); if (!mapped.empty()) { TNS_DEBUG(Esm, "[resolver][import-map] rewrite: %s -> %s", spec.c_str(), mapped.c_str()); spec = mapped; mappedByImportMap = true; } else { // A bare-looking specifier the map didn't match either falls back to // filesystem resolution and almost certainly fails, or — from an HTTP // importer — is refused; surface the missing entry before that error. bool looksBare = spec[0] != '/' && spec[0] != '.' && spec.find("://") == std::string::npos && spec.find('\\') == std::string::npos; if (looksBare) { TNS_DEBUG(Esm, "[resolver][import-map][miss] bare='%s' importMap.size=%lu", spec.c_str(), (unsigned long)vocabulary.importMap.imports.size()); } } } result.specifier = spec; // An HTTP importer resolves the way a browser does and reaches the // filesystem only explicitly: through an import-map entry (whatever its // target, handled below) or a file:// URL. Every other form is refused // here, before anything is probed on disk. const bool referrerIsHttp = IsHttpRegistryKey(referrerKey); if (referrerIsHttp && !mappedByImportMap) { const UrlSpecifier url = ResolveModuleSpecifierAgainstUrl(spec, referrerKey); switch (url.kind) { case UrlSpecifier::Kind::kHttpUrl: TNS_DEBUG(Esm, "[resolver][http-importer] base=%s spec=%s -> %s", referrerKey.c_str(), spec.c_str(), url.href.c_str()); result.kind = ModuleResolution::Kind::kHttp; result.url = url.href; return result; case UrlSpecifier::Kind::kInvalid: result.blocked = BlockedFromHttpMessage( rawSpec, referrerKey, "it does not form an http(s) URL against the importer's URL."); return result; case UrlSpecifier::Kind::kBare: if (spec[0] == '~') { result.blocked = BlockedFromHttpMessage( rawSpec, referrerKey, "app-relative \"~/\" paths are not available to modules loaded over " "HTTP (use a file:// URL, an import-map entry, or createRequire)."); } else { result.blocked = BlockedFromHttpMessage( rawSpec, referrerKey, "it is not in the import map (bare specifiers from an HTTP module " "must be mapped)."); } return result; case UrlSpecifier::Kind::kOtherUrl: if (StartsWith(spec, "file://")) break; // Not a file (data:, …); import() serves blob: itself. result.attempted = spec; return result; } } const std::string httpUrl = NormalizeHttpModuleUrl(spec); if (!httpUrl.empty()) { result.kind = ModuleResolution::Kind::kHttp; result.url = httpUrl; return result; } TNS_DEBUG(Esm, "[resolver] resolving '%s'", spec.c_str()); const bool specIsRelative = spec[0] == '.'; const bool specIsRootAbs = spec[0] == '/'; const std::string referrerPath = FileModulePath(referrerKey); std::string referrer = referrerPath.empty() ? referrerKey : referrerPath; if (referrer.empty() && specIsRelative) { TNS_DEBUG(Esm, "[resolver] No referrer for relative '%s' - assuming app root", spec.c_str()); referrer = GetApplicationPath() + "/index.mjs"; } size_t slash = referrer.find_last_of("/\\"); const std::string baseDir = slash == std::string::npos ? "" : referrer.substr(0, slash + 1); // An HTTP importer's relative or root-absolute import-map target resolves // against the importer's URL. if (referrerIsHttp && (specIsRelative || specIsRootAbs)) { const ModuleUrl resolved = ParseModuleUrl(spec, referrerKey); if (resolved.http) { TNS_DEBUG(Esm, "[resolver][http-rel] base=%s spec=%s -> %s", referrerKey.c_str(), spec.c_str(), resolved.href.c_str()); result.kind = ModuleResolution::Kind::kHttp; result.url = resolved.href; return result; } } // A query or fragment is URL syntax, never part of a file name, so // `import './x.js?v=1'` reads x.js. The query stays part of the module's // identity, in its key, as it is for a served module; the fragment does not. // Split in this one seam, so a static import and an import() of // `./x.js?v=1` name the same module. const std::string query = ModuleQuery(spec); { size_t cut = spec.find_first_of("?#"); if (cut != std::string::npos) { std::string stripped = spec.substr(0, cut); TNS_DEBUG(Esm, "[resolver][strip-query] %s -> %s", spec.c_str(), stripped.c_str()); spec = stripped; } if (spec.empty()) return result; } // Build the filesystem candidates for this specifier shape. The specifier may // omit its extension or name a directory, so each candidate is probed with // Node-style extension and index fallbacks below. const std::string appPath = GetApplicationPath(); std::vector candidateBases; if (specIsRelative) { std::string cleanSpec = spec.rfind("./", 0) == 0 ? spec.substr(2) : spec; std::string candidate = NormalizePath(baseDir + cleanSpec); candidateBases.push_back(candidate); TNS_DEBUG(Esm, "[resolver][normalize-rel] %s + %s -> %s", baseDir.c_str(), cleanSpec.c_str(), candidate.c_str()); } else if (StartsWith(spec, "file://")) { // Absolute file URL. Handle the two virtual roots the runtime emits. std::string tail = spec.substr(7); if (tail.empty() || tail[0] != '/') tail = "/" + tail; const std::string appVirtualRoot = "/app/"; const std::string androidAssetAppRoot = "/android_asset/app/"; std::string candidate; if (tail.rfind(appVirtualRoot, 0) == 0) { candidate = appPath + "/" + tail.substr(appVirtualRoot.size()); } else if (tail.rfind(androidAssetAppRoot, 0) == 0) { candidate = appPath + "/" + tail.substr(androidAssetAppRoot.size()); } else { candidate = tail; } candidateBases.push_back(NormalizePath(candidate)); TNS_DEBUG(Esm, "[resolver][file-url] tail=%s -> %s", tail.c_str(), candidateBases.back().c_str()); } else if (spec[0] == '~') { std::string tail = spec.size() >= 2 && spec[1] == '/' ? spec.substr(2) : spec.substr(1); std::string base = NormalizePath(appPath + "/" + tail); candidateBases.push_back(base); // Also try appPath/app for projects that bundle JS under an app folder. std::string baseApp = NormalizePath(appPath + "/app/" + tail); if (baseApp != base) candidateBases.push_back(baseApp); TNS_DEBUG(Esm, "[resolver][tilde] spec=%s base=%s appBase=%s", spec.c_str(), base.c_str(), baseApp.c_str()); } else if (specIsRootAbs) { // Dynamic import may already have resolved a relative specifier to a real // filesystem path under the application root; use that as-is so we don't // prefix ApplicationPath twice. Bundle-relative paths like /app/... or // /src/... still resolve against appPath. if (!appPath.empty() && spec.rfind(appPath, 0) == 0) { candidateBases.push_back(NormalizePath(spec)); TNS_DEBUG(Esm, "[resolver][abs-fs] spec=%s", spec.c_str()); } else { std::string base = NormalizePath(appPath + spec); candidateBases.push_back(base); const std::string appPrefix = "/app/"; if (spec.rfind(appPrefix, 0) == 0) { std::string tailNoApp = spec.substr(appPrefix.size() - 1); std::string baseNoApp = NormalizePath(appPath + tailNoApp); if (baseNoApp != base) candidateBases.push_back(baseNoApp); } TNS_DEBUG(Esm, "[resolver][abs] spec=%s base=%s", spec.c_str(), base.c_str()); } } else { // Bare specifier — resolve relative to the application root. std::string base = NormalizePath(appPath + "/" + spec); candidateBases.push_back(base); } std::string absPath; bool found = false; for (const std::string& baseCandidate : candidateBases) { absPath = baseCandidate; if (IsFile(absPath)) { found = true; break; } for (const char* e : {".mjs", ".js"}) { std::string cand = NormalizePath(WithExtension(absPath, e)); if (IsFile(cand)) { absPath = cand; found = true; break; } } if (found) break; for (const char* idx : {"/index.mjs", "/index.js"}) { std::string cand = NormalizePath(absPath + idx); if (IsFile(cand)) { absPath = cand; found = true; break; } } if (found) break; } if (found) { result.kind = ModuleResolution::Kind::kFile; result.path = NormalizePath(absPath); result.query = query; result.key = CanonicalizeRegistryKey(result.path) + query; return result; } result.attempted = absPath; return result; } // Monotonic microseconds since some fixed epoch — matches iOS's // CFAbsoluteTimeGetCurrent() semantic (used for internal timing only, never // exposed to JS). static uint64_t MonotonicUs() { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000000ull + (uint64_t)(ts.tv_nsec / 1000); } // ───────────────────────────────────────────────────────────── // The module-graph walk // // See the contract comment in ModuleInternalCallbacks.h. Mechanically, per // edge — local edges never leave the JS thread: // // Enqueue(root) // → local: CompileFileEsModule + register under the canonical key // → http: FetchModuleBodyAsync (background thread — see HttpLoader.cpp) // → JavaScript bodies of kStreamingCompileThresholdBytes or // more: parse + bytecode generation on a StreamCompilePool // thread (V8 streaming) // → back to the isolate's own event loop as a nestable v8 task // → CompileModuleForResolveRegisterOnly, or the streamed // compile's finalization (registers under the canonical URL // key — the exact entry the resolver looks up) // → GetModuleRequests() → ResolveSpecifierToPath → Enqueue(…) // → when pendingFetches drains, onComplete fires on the JS thread. // // Thread discipline: `visited`, `pendingFetches`, `failed`, `completed` are // touched ONLY on the isolate's JS thread (every fetch completion hops there // first). Off-thread work is the I/O and ScriptStreamingTask::Run(). The one // crossing signal is `dead`, an atomic set by isolate teardown so in-flight // completions become no-ops instead of touching a disposed isolate. namespace { struct AsyncGraphLoad { v8::Isolate* isolate = nullptr; // Reset on the JS thread when the walk completes or teardown kills it: the // last reference to a load may drop on a transport or compile thread. v8::Global context; std::string rootKey; // canonical registry key of the root robin_hood::unordered_set visited; // canonical keys (JS thread only) int pendingFetches = 0; // JS thread only bool failed = false; // JS thread only (root failure) bool completed = false; // JS thread only std::string failureMessage; size_t fetchedCount = 0; size_t compiledCount = 0; uint64_t startUs = 0; ModuleFetchDeadline fetchDeadline; std::atomic dead{false}; // set by isolate teardown (any thread) std::function context)> onComplete; ~AsyncGraphLoad() { g_asyncGraphLoadsInFlightCounter().fetch_sub(1, std::memory_order_acq_rel); } static std::atomic& g_asyncGraphLoadsInFlightCounter() { static std::atomic counter{0}; return counter; } }; // Adapter so fetch completions ride the isolate's foreground task queue // (EventLoop::PostV8Task) like any other v8 platform task. class FetchCompletionTask : public v8::Task { public: explicit FetchCompletionTask(std::function fn) : fn_(std::move(fn)) {} void Run() override { fn_(); } private: std::function fn_; }; // Registration and quiesce both run on the isolate's thread (the slot // contract); background fetch completions only ever touch the AsyncGraphLoad // they retain, never this list, so no lock is needed. void RegisterAsyncGraphLoad(v8::Isolate* isolate, const std::shared_ptr& load) { auto* state = ModuleLoaderStateFor(isolate); if (state == nullptr) return; auto& loads = state->asyncGraphLoads; // Prune expired entries opportunistically so the vector stays small. loads.erase(std::remove_if(loads.begin(), loads.end(), [](const std::weak_ptr& w) { return w.expired(); }), loads.end()); loads.push_back(load); } // Smaller JavaScript bodies compile on the isolate thread: for them the round // trip through a background thread costs more than the compile it moves. constexpr size_t kStreamingCompileThresholdBytes = 32 * 1024; // Threads that run ScriptStreamingTask::Run(). The background parser checks // for stack overflow against V8's --stack-size (984 KB on arm64) below the // stack pointer at which Run() starts, so a thread with less stack than that // overflows for real before the parser can report a RangeError. Bionic's // default thread stack is just under 1 MB, hence dedicated threads sized from // the applied --stack-size (g_streamCompileStackBytes). When such a thread // cannot be started, the module compiles on the isolate thread instead. Run() // needs no JNI, so the threads are not attached to the JVM. class StreamCompilePool { public: static StreamCompilePool& Shared() { // Never destroyed: its threads wait on its members for the life of the // process. static StreamCompilePool* pool = new StreamCompilePool(); return *pool; } // False when no thread could be started to run `job`, which is then // dropped without running. bool Post(std::function job) { { std::lock_guard lock(mutex_); if (jobs_.size() >= idle_ && threads_ < maxThreads_ && StartThreadLocked()) { threads_++; } if (threads_ == 0) return false; jobs_.push_back(std::move(job)); } cv_.notify_one(); return true; } private: StreamCompilePool() { const unsigned cpus = std::thread::hardware_concurrency(); maxThreads_ = std::clamp(cpus > 1 ? cpus - 1 : 1u, 1u, 4u); } bool StartThreadLocked() { pthread_attr_t attr; if (pthread_attr_init(&attr) != 0) return false; if (pthread_attr_setstacksize(&attr, g_streamCompileStackBytes) != 0) { pthread_attr_destroy(&attr); return false; } pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_t thread; const bool started = pthread_create(&thread, &attr, &ThreadMain, this) == 0; pthread_attr_destroy(&attr); return started; } static void* ThreadMain(void* arg) { pthread_setname_np(pthread_self(), "ns-esm-compile"); auto* pool = static_cast(arg); for (;;) { std::function job; { std::unique_lock lock(pool->mutex_); pool->idle_++; pool->cv_.wait(lock, [pool] { return !pool->jobs_.empty(); }); pool->idle_--; job = std::move(pool->jobs_.front()); pool->jobs_.pop_front(); } job(); } return nullptr; } std::mutex mutex_; std::condition_variable cv_; std::deque> jobs_; size_t idle_ = 0; unsigned threads_ = 0; unsigned maxThreads_ = 1; }; // `flags` split the way V8's SetFlagsFromString splits them: on whitespace, // with nothing after a bare "--". V8 has no public flag getter. std::vector V8FlagArgs(const std::string& flags) { static constexpr const char* kSpace = " \t\n\v\f\r"; std::vector args; size_t pos = 0; while (pos < flags.size()) { const size_t start = flags.find_first_not_of(kSpace, pos); if (start == std::string::npos) break; size_t end = flags.find_first_of(kSpace, start); if (end == std::string::npos) end = flags.size(); pos = end; std::string arg = flags.substr(start, end - start); if (arg == "--") break; args.push_back(std::move(arg)); } return args; } // Whether `flags` turn lazy compilation off, read the way V8 reads a bool // flag: an optional second dash, a "no"/"no-" negation, `_` and `-` alike, the // last occurrence winning. bool FlagsDisableLazyCompile(const std::string& flags) { bool lazy = true; for (std::string arg : V8FlagArgs(flags)) { if (arg.size() < 2 || arg[0] != '-') continue; std::replace(arg.begin(), arg.end(), '_', '-'); size_t name = arg[1] == '-' ? 2 : 1; bool negated = false; if (arg.compare(name, 2, "no") == 0) { name += 2; if (name < arg.size() && arg[name] == '-') name++; negated = true; } if (arg.compare(name, std::string::npos, "lazy") == 0 || arg.compare(name, 5, "lazy=") == 0) { lazy = !negated; } } return !lazy; } // The --stack-size (in KB) that `flags` set, read the way V8 reads an int // flag: an optional second dash, `_` and `-` alike, the value after '=' or as // the next argument, the last occurrence winning. 0 when none is set. size_t FlagsStackSizeKb(const std::string& flags) { const std::vector args = V8FlagArgs(flags); size_t kb = 0; for (size_t i = 0; i < args.size(); i++) { std::string arg = args[i]; if (arg.size() < 2 || arg[0] != '-') continue; std::replace(arg.begin(), arg.end(), '_', '-'); const size_t name = arg[1] == '-' ? 2 : 1; std::string value; if (arg.compare(name, std::string::npos, "stack-size") == 0) { if (i + 1 >= args.size()) break; value = args[++i]; } else if (arg.compare(name, 11, "stack-size=") == 0) { value = arg.substr(name + 11); } else { continue; } char* end = nullptr; errno = 0; const long long parsed = std::strtoll(value.c_str(), &end, 10); if (errno == 0 && end != value.c_str() && *end == '\0' && parsed > 0) { kb = static_cast(parsed); } } return kb; } // Isolate's Locker, at fetch issue. Null when V8 declines to stream; otherwise // the compile is parked in the loader state, its stream empty until the // transport feeds it. std::shared_ptr BeginStreamedCompile(v8::Isolate* isolate, ModuleLoaderState& state) { auto compile = std::make_unique(); auto stream = std::make_unique(); BodySourceStream* streamPtr = stream.get(); compile->source = std::make_unique( std::move(stream), v8::ScriptCompiler::StreamedSource::UTF8); // Streaming follows --lazy-streaming, not --lazy, so an app's --no-lazy has // to be passed explicitly. const auto options = g_eagerStreamedCompiles ? v8::ScriptCompiler::kEagerCompile : v8::ScriptCompiler::kNoCompileOptions; compile->task.reset(v8::ScriptCompiler::StartStreaming( isolate, compile->source.get(), v8::ScriptType::kModule, options)); if (compile->task == nullptr) return nullptr; auto ticket = std::make_shared(); ticket->id = state.nextStreamedCompileId++; ticket->gate = state.streamGate; ticket->stream = streamPtr; ticket->task = compile->task.get(); state.streamedCompiles.emplace(ticket->id, std::move(compile)); return ticket; } // The issuing isolate's compile for `ticket`, now owned by the caller. // Isolate's Locker only. std::unique_ptr TakeStreamedCompile( v8::Isolate* isolate, const StreamTicket* ticket) { auto* state = ticket != nullptr ? ModuleLoaderStateFor(isolate) : nullptr; if (state == nullptr) return nullptr; auto it = state->streamedCompiles.find(ticket->id); if (it == state->streamedCompiles.end()) return nullptr; std::unique_ptr compile = std::move(it->second); state->streamedCompiles.erase(it); return compile; } bool IsAscii(const std::string& bytes) { const unsigned char* p = reinterpret_cast(bytes.data()); const size_t n = bytes.size(); size_t i = 0; for (; i + sizeof(uint64_t) <= n; i += sizeof(uint64_t)) { uint64_t word; memcpy(&word, p + i, sizeof(word)); if (word & 0x8080808080808080ull) return false; } for (; i < n; i++) { if (p[i] & 0x80) return false; } return true; } bool IsStreamableBody(const ModuleFetchResult& result) { // The stream skips a leading UTF-8 BOM that the full source string would // keep, which would shift every position the finalized script reports. return result.ok && result.kind == ModuleResponseKind::kJavaScript && result.body.size() >= kStreamingCompileThresholdBytes && !StartsWith(result.body, "\xEF\xBB\xBF"); } // Transport thread. Feeds `result` to the ticket's stream and runs the compile // on the StreamCompilePool, which calls `postCompletion` once Run() has // returned. Returns false, without running anything, when the body is not to // be streamed; the caller then posts the completion itself. bool DispatchStreamedCompile(const std::shared_ptr& load, const std::shared_ptr& ticket, const std::shared_ptr& result, std::function postCompletion) { if (!IsStreamableBody(*result)) return false; if (!ticket->gate->TryEnter()) return false; if (load->dead.load(std::memory_order_acquire)) { ticket->gate->Leave(); return false; } const bool posted = StreamCompilePool::Shared().Post( [load = load, ticket = ticket, result = result, postCompletion = std::move(postCompletion)]() mutable { if (!load->dead.load(std::memory_order_acquire)) { const std::string& body = result->body; std::unique_ptr chunk(new uint8_t[body.size()]); memcpy(chunk.get(), body.data(), body.size()); ticket->ascii = IsAscii(body); ticket->stream->Feed(std::move(chunk), body.size()); g_streamedCompileCounters.running.fetch_add(1, std::memory_order_relaxed); ticket->task->Run(); g_streamedCompileCounters.running.fetch_sub(1, std::memory_order_relaxed); ticket->ran = true; // Posted before Leave(): teardown stops the event loop only after // the gate drains, so this post cannot be dropped off the isolate // thread. postCompletion(); } // Released before Leave(): once the gate drains, teardown may drop the // runtime's own references, and the last one to the event loop must // not be released on this thread. postCompletion = nullptr; load.reset(); result.reset(); ticket->gate->Leave(); }); if (!posted) { ticket->gate->Leave(); return false; } return true; } } // namespace void NoteAppliedV8Flags(const std::string& flags) { g_eagerStreamedCompiles = FlagsDisableLazyCompile(flags); // Room for the frames above Run() and the guard page, as the 2 MB floor // leaves for V8's default --stack-size. constexpr size_t kHeadroomBytes = 1024 * 1024; constexpr size_t kMinStackBytes = 2 * 1024 * 1024; const size_t stackKb = FlagsStackSizeKb(flags); const size_t maxKb = (SIZE_MAX - kHeadroomBytes) / 1024; g_streamCompileStackBytes = stackKb == 0 ? kMinStackBytes : std::max(kMinStackBytes, std::min(stackKb, maxKb) * 1024 + kHeadroomBytes); } bool HasPendingAsyncModuleGraphWork() { return AsyncGraphLoad::g_asyncGraphLoadsInFlightCounter().load( std::memory_order_acquire) > 0; } // Isolate-teardown hook: mark every in-flight load owned by `isolate` dead // (pending fetch completions become no-ops) and Reset their context Globals // NOW, while the isolate is still alive — nothing may destroy a v8::Global // after isolate disposal, and a pending background fetch completion can hold a // load's shared_ptr past teardown, so the slot destructor alone cannot cover // these. Called from QuiesceModuleLoadsForIsolate. static void KillAsyncGraphLoadsForIsolate(v8::Isolate* isolate) { auto* state = ModuleLoaderStateFor(isolate); if (state == nullptr) return; for (auto& weak : state->asyncGraphLoads) { if (auto load = weak.lock()) { load->dead.store(true, std::memory_order_release); load->context.Reset(); } } state->asyncGraphLoads.clear(); } // Isolate-teardown hook, after KillAsyncGraphLoadsForIsolate and before the // event loop stops: closes the streaming gate, waits out every Run() in flight // and destroys the compiles that will never be finalized, all while the // isolate is alive and locked. A Run() parked on a GC request is released by // running the loop's nestable v8 tasks, where V8 posted the request; that // drain reads the loop's queues directly and never polls the looper, so it is // safe from inside a looper callback. // // No JS may run in that drain: the runtime is half torn down (Java side // detached, child workers terminated, loads killed). A terminated isolate can // still hold microtasks, which the per-task checkpoint would run, so they are // suppressed; a V8 task that calls into JS directly (a wasm start function // run by an async instantiate) gets an exception instead. static void DrainStreamedCompilesForIsolate(v8::Isolate* isolate) { auto* state = ModuleLoaderStateFor(isolate); if (state == nullptr) return; Runtime* runtime = Runtime::TryGetRuntime(isolate); std::shared_ptr loop = runtime != nullptr ? runtime->GetEventLoop() : nullptr; { v8::Isolate::SuppressMicrotaskExecutionScope noMicrotasks(isolate); v8::Isolate::DisallowJavascriptExecutionScope noJs( isolate, v8::Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE); const bool waited = state->streamGate->CloseAndDrain([&loop]() { if (loop != nullptr) { loop->RunNestableV8Tasks(); } }); if (waited) { g_streamedCompileCounters.teardownWaits.fetch_add(1, std::memory_order_relaxed); } } state->streamedCompiles.clear(); } static void AsyncGraphEnqueue(const std::shared_ptr& load, const ModuleResolution& resolution); // A specifier's UTF-8, sized by length, or nullopt when it contains U+0000: // the path and URL APIs behind resolution read C strings and would load // whatever precedes it. static std::optional ModuleSpecifierUtf8(v8::Isolate* isolate, v8::Local specifier) { v8::String::Utf8Value utf8(isolate, specifier); std::string spec = *utf8 ? std::string(*utf8, utf8.length()) : std::string(); if (spec.find('\0') != std::string::npos) { return std::nullopt; } return spec; } static std::string NulSpecifierMessage(v8::Isolate* isolate, v8::Local specifier) { v8::String::Utf8Value utf8(isolate, specifier); std::string shown; if (*utf8) { for (int i = 0; i < utf8.length(); i++) { if ((*utf8)[i] == '\0') { shown += "\\u0000"; } else { shown += (*utf8)[i]; } } } return "Cannot resolve module specifier \"" + shown + "\": a module specifier must not contain U+0000"; } // Walk `mod`'s static module requests and enqueue every edge the walk can // resolve. JS thread only; `moduleKey` is the registry key the module was // registered under, which is also the referrer for relative resolution. static void AsyncGraphWalkModuleRequests( const std::shared_ptr& load, v8::Local context, v8::Local mod, const std::string& moduleKey) { v8::Isolate* isolate = load->isolate; v8::Local requests = mod->GetModuleRequests(); const int length = requests->Length(); for (int i = 0; i < length; i++) { v8::Local request = requests->Get(i).As(); if (request.IsEmpty()) continue; // A specifier holding U+0000 is left for the resolver to refuse at link. const std::optional spec = ModuleSpecifierUtf8(isolate, request->GetSpecifier()); if (!spec.has_value()) continue; // Builtins are served by the resolver from the builtin registry, and an // unresolved specifier (typically a bare name with no import-map entry, // or one an HTTP importer may not use) stays on the resolver's lazy path — // where it either resolves later or fails with the resolver's own // message. An unmapped bare specifier's subtree is therefore not // discovered here; any HTTP edge inside it is pathological and lands on // the synchronous anomaly guard. const ModuleResolution resolution = ResolveSpecifierToPath(*spec, moduleKey); if (resolution.kind != ModuleResolution::Kind::kHttp && resolution.kind != ModuleResolution::Kind::kFile) { continue; } AsyncGraphEnqueue(load, resolution); } } // Fire onComplete exactly once, when the frontier has drained. JS thread only. static void AsyncGraphMaybeComplete(const std::shared_ptr& load, v8::Local context) { if (load->completed || load->pendingFetches > 0) return; load->completed = true; // No completion can arrive for this load any more, while transport and // compile threads may still hold references to it and drop the last one. load->context.Reset(); if (LogCategoryEnabled(LogCategory::Esm)) { const uint64_t endUs = MonotonicUs(); const uint64_t ms = endUs > load->startUs ? (endUs - load->startUs) / 1000ull : 0ull; TNS_DEBUG( Esm, "[graph][done] root=%s urls=%lu fetched=%lu compiled=%lu ms=%llu ok=%d", load->rootKey.c_str(), (unsigned long)load->visited.size(), (unsigned long)load->fetchedCount, (unsigned long)load->compiledCount, (unsigned long long)ms, load->failed ? 0 : 1); } auto onComplete = std::move(load->onComplete); load->onComplete = nullptr; if (onComplete) { v8::TryCatch tc(load->isolate); onComplete(!load->failed, load->failureMessage, context); (void)tc; // swallow any pending exception; failures already surface as rejections } } // A fetch verdict arrived on the isolate's JS thread: compile + register the // module, then walk its requests. Runs outside any V8 scope, so it enters the // isolate the same way other cross-thread callbacks do. static void AsyncGraphOnFetchCompleted( const std::shared_ptr& load, const std::string& url, const std::shared_ptr& fetched, const std::shared_ptr& ticket) { // Dead loads leave their streamed compile to DrainStreamedCompilesForIsolate. if (load->dead.load(std::memory_order_acquire)) return; v8::Isolate* isolate = load->isolate; if (Runtime::TryGetRuntime(isolate) == nullptr) return; v8::Locker locker(isolate); v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handle_scope(isolate); std::unique_ptr streamed = TakeStreamedCompile(isolate, ticket.get()); const bool streamedRan = streamed != nullptr && ticket->ran; v8::Local context = load->context.Get(isolate); if (context.IsEmpty()) return; v8::Context::Scope context_scope(context); load->pendingFetches--; const std::string key = CanonicalizeNormalizedHttpUrlKey(url); const bool isRoot = (key == load->rootKey); if (!load->failed) { if (!fetched->ok) { if (isRoot) { load->failed = true; load->failureMessage = fetched->failureReason; } else { TNS_DEBUG(Esm, "[graph][dep-fetch-fail] %s (left to sync resolver)", fetched->failureReason.c_str()); } } else if (fetched->kind == ModuleResponseKind::kJson) { // JSON compiles, instantiates and evaluates in one step and carries no // module requests, so there is nothing further to walk from here. load->fetchedCount++; v8::TryCatch tcJson(isolate); if (CompileJsonTextAsEsModule(isolate, context, fetched->body, key, url) .IsEmpty()) { std::string reason = DescribeCaughtError(isolate, context, tcJson); if (isRoot) { load->failed = true; load->failureMessage = "JSON module failed to compile: " + url; if (!reason.empty()) { load->failureMessage += " — " + reason; } } else { TNS_DEBUG(Esm, "[graph][dep-json-fail] %s %s (left to sync resolver)", url.c_str(), reason.c_str()); } } else { load->compiledCount++; } } else { load->fetchedCount++; v8::Local mod; bool compiled = false; std::string compileError; { // This callback runs on to completion and a microtask checkpoint, so a // compile exception must be consumed here rather than left pending; its // text goes into the load's own failure channel instead. v8::TryCatch tcCompile(isolate); if (streamedRan) { compiled = CompileStreamedModuleRegisterOnly( isolate, context, *streamed, std::move(fetched->body), ticket->ascii, key) .ToLocal(&mod); streamed.reset(); } else { if (IsStreamableBody(*fetched)) { g_streamedCompileCounters.fellBack.fetch_add(1, std::memory_order_relaxed); } compiled = CompileModuleForResolveRegisterOnly(isolate, context, fetched->body, key) .ToLocal(&mod); } if (!compiled) { compileError = DescribeCaughtError(isolate, context, tcCompile); } } if (!compiled) { if (isRoot) { load->failed = true; load->failureMessage = "HTTP import compile failed: " + url; if (!compileError.empty()) { load->failureMessage += " — " + compileError; } } else { TNS_DEBUG(Esm, "[graph][dep-compile-fail] %s %s (left to sync resolver)", url.c_str(), compileError.c_str()); } } else { load->compiledCount++; AsyncGraphWalkModuleRequests(load, context, mod, key); } } } AsyncGraphMaybeComplete(load, context); isolate->PerformMicrotaskCheckpoint(); } // A local edge: read + compile + register it inline, then keep walking. No // thread hop — the bytes are already on disk, and a hop would only reorder // discovery. A compile failure is deliberately swallowed here: the walk is a // discovery optimization, and the resolver (or LoadESModule, for the root) // 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 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, resolution.query) .ToLocal(&mod); } catch (NativeScriptException& ex) { TNS_DEBUG(Esm, "[graph][local-compile-fail] %s %s (left to the resolver)", path.c_str(), ex.GetErrorMessage().c_str()); return; } if (!compiled) { TNS_DEBUG(Esm, "[graph][local-compile-fail] %s (left to the resolver)", path.c_str()); return; } } UnindexRegistryKey(*moduleState, isolate, key); moduleState->registry[key].Reset(isolate, mod); IndexRegisteredModule(*moduleState, key, mod); load->compiledCount++; AsyncGraphWalkModuleRequests(load, context, mod, key); } // Enqueue one resolved edge into the walk frontier. JS thread only. 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 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; v8::Isolate* isolate = load->isolate; auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) return; auto& registry = moduleState->registry; auto it = registry.find(key); if (it != registry.end()) { v8::Local existing = it->second.Get(isolate); if (!existing.IsEmpty() && existing->GetStatus() != v8::Module::kErrored) { if (existing->GetStatus() == v8::Module::kUninstantiated) { v8::Local context = load->context.Get(isolate); if (!context.IsEmpty()) { AsyncGraphWalkModuleRequests(load, context, existing, key); } } return; // instantiated/evaluated → its closure is already resolved } // Errored entry: drop and reload, mirroring LoadHttpModuleForUrl. RemoveModuleFromRegistry(isolate, key); } if (!isHttp) { // JSON carries no module requests, and it compiles through a different // path; there is nothing for the walk to discover in it. if (EndsWith(target, ".json")) return; v8::Local context = load->context.Get(isolate); if (!context.IsEmpty()) { AsyncGraphCompileLocalModule(load, context, resolution); } return; } load->pendingFetches++; std::shared_ptr loadRef = load; const std::string url = target; std::shared_ptr ticket = BeginStreamedCompile(isolate, *moduleState); const ModuleFetchDeadline deadline = load->fetchDeadline; FetchModuleBodyAsync(url, deadline, [loadRef, url, ticket](ModuleFetchResult result) { // Arbitrary thread. Hop to the isolate's home thread as a nestable v8 // foreground task — delivery is a property of the isolate, not of the // thread that started the fetch, and the pumped walk's // RunNestableV8Tasks can drain it with JS frames on the stack. A null // lookup means the isolate is gone; drop everything, and since teardown // quiesces the loads before shutting the loop down, a dropped post holds // only already-Reset state. if (loadRef->dead.load(std::memory_order_acquire)) return; auto* platform = NativeScriptPlatform::Instance(); std::shared_ptr loop = platform != nullptr ? platform->LookupEventLoop(loadRef->isolate) : nullptr; if (loop == nullptr) return; auto resultPtr = std::make_shared(std::move(result)); auto postCompletion = [loop, loadRef, url, resultPtr, ticket]() { loop->PostV8Task( std::make_unique([loadRef, url, resultPtr, ticket]() { AsyncGraphOnFetchCompleted(loadRef, url, resultPtr, ticket); }), /*nestable=*/true, /*delaySeconds=*/0); }; if (ticket != nullptr && DispatchStreamedCompile(loadRef, ticket, resultPtr, postCompletion)) { return; } postCompletion(); }); } // 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) { 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() && IsFile(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. return resolution; } void StartModuleGraphLoad( v8::Isolate* isolate, v8::Local context, const std::string& root, ModuleFetchDeadline fetchDeadline, std::function context)> onComplete) { const ModuleResolution rootResolution = ResolutionForRoot(root); 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); load->startUs = MonotonicUs(); load->fetchDeadline = fetchDeadline; load->onComplete = std::move(onComplete); 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()); if (rootResolution.kind != ModuleResolution::Kind::kUnresolved) { AsyncGraphEnqueue(load, rootResolution); } // Nothing left pending (a disk-only graph finishes entirely here): complete // inline, so the pumped runner below never enters its wait loop. AsyncGraphMaybeComplete(load, context); } bool RunModuleGraphLoadPumped(v8::Isolate* isolate, v8::Local context, const std::string& root, double timeoutSeconds) { if (timeoutSeconds <= 0.0) timeoutSeconds = kModuleEvaluateDeadlineSeconds; // Taken before the walk starts: local modules compile inline inside // StartModuleGraphLoad, and that time spends the same budget. const auto deadline = std::chrono::steady_clock::now() + std::chrono::duration_cast( std::chrono::duration(timeoutSeconds)); auto done = std::make_shared(false); StartModuleGraphLoad(isolate, context, root, deadline, [done](bool /*ok*/, const std::string& /*errorMessage*/, v8::Local) { *done = true; }); // Fetch completions are nestable v8 foreground tasks on the isolate's event // loop, which the pump drains directly. A graph with no HTTP edges is // already done here, so the pump never runs. The walk always takes the // looper-equivalent drain — it stands where iOS pumps its runloop, so a // fetch that needs a timer or a worker reply to complete still progresses. Runtime* runtime = Runtime::TryGetRuntime(isolate); std::shared_ptr eventLoop = runtime != nullptr ? runtime->GetEventLoop() : nullptr; if (!*done && eventLoop != nullptr) { const double remainingSeconds = std::chrono::duration(deadline - std::chrono::steady_clock::now()).count(); if (eventLoop->PumpUntil(remainingSeconds, [&]() { return *done; }, /*drainLooperWork=*/true) == EventLoop::PumpResult::kTerminated) { // terminating isolate or stopped loop: nothing can complete the walk, // and the sync takeover below must not start a blocking fetch TNS_DEBUG(Esm, "[graph][pumped][terminated] root=%s", root.c_str()); return *done; } } if (!*done) { TNS_DEBUG( Esm, "[graph][pumped][timeout] root=%s after %.1fs (sync loader takes over)", root.c_str(), timeoutSeconds); } return *done; } // ───────────────────────────────────────────────────────────── // Registry mutation + diagnostics static const char* ModuleStatusToString(v8::Module::Status status) { switch (status) { case v8::Module::kUninstantiated: return "Uninstantiated"; case v8::Module::kInstantiating: return "Instantiating"; case v8::Module::kInstantiated: return "Instantiated"; case v8::Module::kEvaluating: return "Evaluating"; case v8::Module::kEvaluated: return "Evaluated"; case v8::Module::kErrored: return "Errored"; } return "Unknown"; } void RemoveModuleFromRegistry(v8::Isolate* isolate, const std::string& canonicalPath) { auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) return; auto& registry = moduleState->registry; const std::string registryKey = CanonicalizeRegistryKey(canonicalPath); const LoaderVocabulary& vocabulary = moduleState->vocabulary; auto classify = [&vocabulary](const std::string& s) -> const char* { bool http = IsHttpRegistryKey(s); if (http) { // `http:volatile` is client-configured, via volatilePatterns; every other // arm is derived from the URL's own shape, never from a client's // conventions. if (IsVolatileUrl(vocabulary, s)) return "http:volatile"; return "http:other"; } if (StartsWith(s, "file://")) return "file-url"; return "path"; }; if (registryKey != canonicalPath) { TNS_DEBUG(Esm, "[resolver][remove:pre] raw=%s key=%s class=%s", canonicalPath.c_str(), registryKey.c_str(), classify(registryKey)); } else { TNS_DEBUG(Esm, "[resolver][remove:pre] key=%s class=%s", registryKey.c_str(), classify(registryKey)); } size_t regPre = registry.size(); auto it = registry.find(registryKey); if (it != registry.end()) { bool isHttpKey = IsHttpRegistryKey(registryKey); if (!isHttpKey) { TNS_DEBUG(Esm, "[resolver] removing stale module %s", registryKey.c_str()); } UnindexRegistryKey(*moduleState, isolate, registryKey); it->second.Reset(); registry.erase(it); } else { TNS_DEBUG(Esm, "[resolver][remove:miss] key not found (%s)", registryKey.c_str()); } TNS_DEBUG(Esm, "[resolver][remove:post] reg %lu->%lu", (unsigned long)regPre, (unsigned long)registry.size()); } std::vector GetLoadedModuleUrls() { std::vector urls; v8::Isolate* isolate = v8::Isolate::GetCurrent(); auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) return urls; auto& registry = moduleState->registry; urls.reserve(registry.size()); for (const auto& entry : registry) { const std::string& key = entry.first; // 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); } } std::sort(urls.begin(), urls.end()); urls.erase(std::unique(urls.begin(), urls.end()), urls.end()); return urls; } void InvalidateModules(v8::Isolate* isolate, v8::Local context, const std::vector& urls) { auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) return; auto& registry = moduleState->registry; if (urls.empty()) return; robin_hood::unordered_set seen; std::vector uniqueUrls; uniqueUrls.reserve(urls.size()); for (const auto& url : urls) { if (url.empty()) continue; std::string registryKey = CanonicalizeRegistryKey(url); if (registryKey.empty()) continue; if (!seen.insert(registryKey).second) continue; uniqueUrls.push_back(registryKey); } size_t hits = 0, misses = 0; for (const auto& url : uniqueUrls) { bool present = registry.find(url) != registry.end(); if (present) hits++; else misses++; TNS_DEBUG(Registry, "invalidate %s key=%s", present ? "HIT " : "MISS", url.c_str()); RejectAndClearInvalidatedModuleState(isolate, context, url); RemoveModuleFromRegistry(isolate, url); } TNS_DEBUG(Registry, "invalidate summary unique=%lu hits=%lu misses=%lu " "(registry now=%lu)", (unsigned long)uniqueUrls.size(), (unsigned long)hits, (unsigned long)misses, (unsigned long)registry.size()); } // ───────────────────────────────────────────────────────────── // Resolver state // // The dynamic-import in-flight set and waiter lists live in ModuleLoaderState // (per isolate, in a RuntimeState slot). static bool IsModuleEvaluationInProgress(v8::Module::Status status) { return status == v8::Module::kInstantiating || status == v8::Module::kEvaluating; } static void ResolveResolversWithModuleNamespace( v8::Isolate* isolate, v8::Local context, std::vector>& resolvers, v8::Local module, const std::string& registryKey) { if (resolvers.empty()) return; if (module.IsEmpty() || module->GetStatus() != v8::Module::kEvaluated) { std::string msg = "Module did not finish evaluation: " + registryKey; v8::Local errObj = v8::Exception::Error(ArgConverter::ConvertToV8String(isolate, msg)); for (auto& resGlobal : resolvers) { v8::Local resolver = resGlobal.Get(isolate); if (!resolver.IsEmpty()) { resolver->Reject(context, errObj).FromMaybe(false); } resGlobal.Reset(); } return; } v8::Local moduleNamespace = module->GetModuleNamespace(); for (auto& resGlobal : resolvers) { v8::Local resolver = resGlobal.Get(isolate); if (!resolver.IsEmpty()) { resolver->Resolve(context, moduleNamespace).FromMaybe(false); } resGlobal.Reset(); } } static void RejectResolversWithReason( v8::Isolate* isolate, v8::Local context, std::vector>& resolvers, v8::Local reason) { if (resolvers.empty()) return; for (auto& resGlobal : resolvers) { v8::Local resolver = resGlobal.Get(isolate); if (!resolver.IsEmpty()) { resolver->Reject(context, reason).FromMaybe(false); } resGlobal.Reset(); } } // Park `resolver` on `registryKey`'s waiter list when that key is mid-flight. // // A queued waiter is settled by exactly one thing: the top-level-await // continuation the pass that began evaluating this key attached to the // module's capability promise. Every site that queues a waiter and returns // while the module is already kEvaluating therefore depends on such a pass // existing for that key. static bool QueueHttpDynamicWaiterIfInFlight( v8::Isolate* isolate, const std::string& registryKey, v8::Local module, v8::Local resolver) { auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) return false; auto& modulesInFlight = moduleState->modulesInFlight; if (registryKey.empty() || module.IsEmpty() || !IsModuleEvaluationInProgress(module->GetStatus()) || modulesInFlight.find(registryKey) == modulesInFlight.end()) { return false; } moduleState->httpDynamicWaiters[registryKey].emplace_back(isolate, resolver); TNS_DEBUG(Esm, "[dyn-import][http-await] queued waiter for %s status=%s", registryKey.c_str(), ModuleStatusToString(module->GetStatus())); return true; } // Build a rejection reason that PRESERVES the underlying V8 exception text. static v8::Local BuildModuleFailureReason(v8::Isolate* isolate, v8::TryCatch& tc, const char* stage, const std::string& urlOrKey) { std::string message = std::string(stage) + ": " + urlOrKey; if (tc.HasCaught()) { v8::Local excMessage = tc.Message(); if (!excMessage.IsEmpty()) { v8::String::Utf8Value text(isolate, excMessage->Get()); if (*text != nullptr && strlen(*text) > 0) { message += std::string(" — ") + *text; } } else { v8::Local exception = tc.Exception(); if (!exception.IsEmpty()) { v8::String::Utf8Value text(isolate, exception); if (*text != nullptr && strlen(*text) > 0) { message += std::string(" — ") + *text; } } } } TNS_DEBUG(Esm, "[dyn-import][failure] %s", message.c_str()); return v8::Exception::Error(ArgConverter::ConvertToV8String(isolate, message)); } static void ResolveHttpDynamicWaiters(v8::Isolate* isolate, v8::Local context, const std::string& registryKey, v8::Local module) { auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) return; // Settling a promise can run its reactions immediately: with the default // microtask policy, a Resolve/Reject issued from a plain platform task (no // JS on the stack) drains the queue as the API call unwinds. A reaction that // re-imports this URL would then see stale routing state and park on a // waiter list that was just flushed — a promise nothing would ever settle. // So every piece of state that can route a new import onto the waiter list // is cleared FIRST; a re-entrant import then takes the registry-hit path. std::vector> resolvers; auto& httpDynamicWaiters = moduleState->httpDynamicWaiters; auto waitIt = httpDynamicWaiters.find(registryKey); if (waitIt != httpDynamicWaiters.end()) { resolvers.swap(waitIt->second); httpDynamicWaiters.erase(waitIt); } moduleState->modulesInFlight.erase(registryKey); ResolveResolversWithModuleNamespace(isolate, context, resolvers, module, registryKey); } static void RejectHttpDynamicWaiters(v8::Isolate* isolate, v8::Local context, const std::string& registryKey, v8::Local reason) { auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) return; // Cleared before rejecting, for the same reason as the resolve path: a // rejection handler that retries this URL must not join a flushed waiter // list. std::vector> resolvers; auto& httpDynamicWaiters = moduleState->httpDynamicWaiters; auto waitIt = httpDynamicWaiters.find(registryKey); if (waitIt != httpDynamicWaiters.end()) { resolvers.swap(waitIt->second); httpDynamicWaiters.erase(waitIt); } moduleState->modulesInFlight.erase(registryKey); RejectResolversWithReason(isolate, context, resolvers, reason); } static void RejectResolversForInvalidation( v8::Isolate* isolate, v8::Local context, std::vector>& resolvers, const std::string& registryKey) { if (resolvers.empty()) return; std::string message = "Module invalidated during dev reload: " + registryKey; v8::Local error = v8::Exception::Error(ArgConverter::ConvertToV8String(isolate, message)); for (auto& resolverGlobal : resolvers) { v8::Local resolver = resolverGlobal.Get(isolate); if (!resolver.IsEmpty()) { resolver->Reject(context, error).FromMaybe(false); } resolverGlobal.Reset(); } } static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate, v8::Local context, const std::string& registryKey) { auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) return; auto& httpDynamicWaiters = moduleState->httpDynamicWaiters; moduleState->modulesInFlight.erase(registryKey); auto dynamicWaitIt = httpDynamicWaiters.find(registryKey); if (dynamicWaitIt != httpDynamicWaiters.end()) { std::vector> resolvers; resolvers.swap(dynamicWaitIt->second); httpDynamicWaiters.erase(dynamicWaitIt); RejectResolversForInvalidation(isolate, context, resolvers, registryKey); } TNS_DEBUG(Esm, "[resolver][invalidate-state] cleared in-flight state for %s", registryKey.c_str()); } // ───────────────────────────────────────────────────────────── // JSON module → synthetic ES module // Wrap JSON source as an ES module with the parsed value as its default // export. Shared by the filesystem path and the HTTP path so a served JSON // module and an imported .json file behave identically; `displayUrl` only // names the module in stack traces. Handles registry insertion and eager // evaluation. static v8::MaybeLocal CompileJsonTextAsEsModule( v8::Isolate* isolate, v8::Local context, const std::string& jsonText, const std::string& registryAbsPath, const std::string& displayUrl) { auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) { return v8::MaybeLocal(); } auto& registry = moduleState->registry; // JSON modules are compiled eagerly to kEvaluated, so a registered entry is // complete and must be reused — recompiling would mint a second module // identity (and namespace) for the same source on every resolve. auto existingIt = registry.find(registryAbsPath); if (existingIt != registry.end()) { v8::Local existing = existingIt->second.Get(isolate); if (!existing.IsEmpty() && existing->GetStatus() == v8::Module::kEvaluated) { return v8::MaybeLocal(existing); } UnindexRegistryKey(*moduleState, isolate, registryAbsPath); existingIt->second.Reset(); registry.erase(existingIt); } TNS_DEBUG(Esm, "[json] wrapping %s", displayUrl.c_str()); std::string moduleSource = "export default " + jsonText + ";"; v8::Local sourceText = ArgConverter::ConvertToV8String(isolate, moduleSource); const std::string& url = displayUrl; v8::Local urlString; if (!v8::String::NewFromUtf8(isolate, url.c_str(), v8::NewStringType::kNormal) .ToLocal(&urlString)) { isolate->ThrowException(v8::Exception::Error(ArgConverter::ConvertToV8String( isolate, "Failed to create URL string for JSON module"))); return v8::MaybeLocal(); } v8::ScriptOrigin origin(urlString, 0, 0, false, -1, v8::Local(), false, false, true /* is_module */); v8::ScriptCompiler::Source src(sourceText, origin); v8::Local jsonModule; if (!v8::ScriptCompiler::CompileModule(isolate, &src).ToLocal(&jsonModule)) { isolate->ThrowException(v8::Exception::SyntaxError( ArgConverter::ConvertToV8String(isolate, "Failed to compile JSON module"))); return v8::MaybeLocal(); } if (!jsonModule->InstantiateModule(context, &ResolveModuleCallback) .FromMaybe(false)) { return v8::MaybeLocal(); } v8::MaybeLocal evalResult = jsonModule->Evaluate(context); if (evalResult.IsEmpty()) return v8::MaybeLocal(); UnindexRegistryKey(*moduleState, isolate, registryAbsPath); auto it = registry.find(registryAbsPath); if (it != registry.end()) it->second.Reset(); registry[registryAbsPath].Reset(isolate, jsonModule); IndexRegisteredModule(*moduleState, registryAbsPath, jsonModule); return v8::MaybeLocal(jsonModule); } // The filesystem entry point: read the file, then share the wrap. static v8::MaybeLocal CompileJsonAsEsModule( v8::Isolate* isolate, v8::Local context, const std::string& absPath, const std::string& registryKey) { Runtime* runtime = Runtime::TryGetRuntime(isolate); if (runtime == nullptr) { // Resolve-callback contract: an empty return needs an exception scheduled, // and a C++ throw here would unwind through InstantiateModule. isolate->ThrowException(v8::Exception::Error(ArgConverter::ConvertToV8String( isolate, "Cannot read JSON module " + absPath + ": the isolate has no runtime"))); return v8::MaybeLocal(); } const std::string jsonText = runtime->ReadFileText(absPath); return CompileJsonTextAsEsModule(isolate, context, jsonText, registryKey, ReportedModuleUrl(registryKey)); } // ───────────────────────────────────────────────────────────── // ResolveModuleCallback — invoked by V8 to resolve `import X from ''`. // // Every resolution decision belongs to ResolveSpecifierToPath, shared with the // graph walk; what stays here is the V8-facing half — serving builtins, // delegating HTTP, and compiling + registering a file. static v8::MaybeLocal LoadResolvedModule( v8::Isolate* isolate, v8::Local context, const ModuleResolution& resolution); v8::MaybeLocal ResolveModuleCallback( v8::Local context, v8::Local specifier, v8::Local /*import_assertions*/, v8::Local referrer) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) { return v8::MaybeLocal(); } const std::optional spec = ModuleSpecifierUtf8(isolate, specifier); if (!spec.has_value()) { isolate->ThrowException(v8::Exception::Error( ArgConverter::ConvertToV8String(isolate, NulSpecifierMessage(isolate, specifier)))); return v8::MaybeLocal(); } const std::string& rawSpec = *spec; if (rawSpec.empty()) return v8::MaybeLocal(); const std::string referrerPath = FindKeyForModule(*moduleState, isolate, referrer); return LoadResolvedModule(isolate, context, ResolveSpecifierToPath(rawSpec, referrerPath)); } // The loading half of resolution: everything that happens once a specifier has // become a ModuleResolution. Split out so dynamic import() can route an // already-resolved specifier here instead of resolving the string a second // time — resolving twice would apply the import map twice, and the second pass // has no referrer, so the two passes need not even agree. static v8::MaybeLocal LoadResolvedModule( v8::Isolate* isolate, v8::Local context, const ModuleResolution& resolution) { auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) { return v8::MaybeLocal(); } auto& registry = moduleState->registry; switch (resolution.kind) { case ModuleResolution::Kind::kBuiltin: { v8::Local builtin; if (NsBuiltinModules::GetModule(context, resolution.specifier) .ToLocal(&builtin)) { return v8::MaybeLocal(builtin); } if (!NsBuiltinModules::IsRegistered(resolution.specifier)) { isolate->ThrowException( v8::Exception::Error(ArgConverter::ConvertToV8String( isolate, NsBuiltinModules::NotFoundMessage(resolution.specifier)))); } return v8::MaybeLocal(); } case ModuleResolution::Kind::kHttp: // Security: HttpFetchModule gates remote module access centrally. return LoadHttpModuleForUrl(isolate, context, resolution.url); case ModuleResolution::Kind::kUnresolved: { // Surfaced as an exception rather than left to ReadFileText, which would // abort trying to open a directory. isolate->ThrowException(v8::Exception::Error(ArgConverter::ConvertToV8String( isolate, UnresolvedModuleMessage(resolution)))); return v8::MaybeLocal(); } case ModuleResolution::Kind::kFile: break; } const std::string& absPath = resolution.path; const std::string& registryKey = resolution.key; // JSON module: compile a synthetic ESM. if (EndsWith(absPath, ".json")) { return CompileJsonAsEsModule(isolate, context, absPath, registryKey); } // 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(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)", registryKey.c_str(), ModuleStatusToString(existing->GetStatus())); return v8::MaybeLocal(existing); } RemoveModuleFromRegistry(isolate, registryKey); } // 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", registryKey.c_str()); try { v8::Local 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(); } UnindexRegistryKey(*moduleState, isolate, registryKey); registry[registryKey].Reset(isolate, mod); IndexRegisteredModule(*moduleState, registryKey, mod); return v8::MaybeLocal(mod); } catch (NativeScriptException& ex) { TNS_DEBUG(Esm, "[resolver] failed to compile '%s' -> '%s'", resolution.specifier.c_str(), absPath.c_str()); ex.ReThrowToV8(); return v8::MaybeLocal(); } } // ───────────────────────────────────────────────────────────── // FinishHttpDynamicImport // // Called on the JS thread once the async graph walk has fetched (and // registered as uninstantiated) the transitive closure for an HTTP dynamic // import. Instantiates + evaluates the root and settles all queued // dynamic-import waiters. Top-level await is fanned out to a Then handler so // waiters only settle after the returned promise settles. static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local context, const std::string& key, const std::string& requestUrl) { if (LogCategoryEnabled(LogCategory::Esm)) { auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState != nullptr && moduleState->registry.find(key) == moduleState->registry.end()) { TNS_DEBUG(Esm, "[graph][fallback-sync-load] root missed walk: %s", key.c_str()); } } // The loader throws the classifier's reason (status, MIME or transport) on // failure; catch it here so it becomes the waiters' rejection instead of a // generic message left beside a pending exception. v8::TryCatch tcLoad(isolate); v8::MaybeLocal modMaybe = LoadHttpModuleForUrl(isolate, context, requestUrl); if (!modMaybe.IsEmpty()) { v8::Local mod; if (modMaybe.ToLocal(&mod)) { if (mod->GetStatus() == v8::Module::kUninstantiated) { v8::TryCatch tcInstantiate(isolate); if (!mod->InstantiateModule(context, &ResolveModuleCallback) .FromMaybe(false)) { RemoveModuleFromRegistry(isolate, key); v8::Local reason = BuildModuleFailureReason(isolate, tcInstantiate, "Instantiation failed (http-loader)", requestUrl); tcInstantiate.Reset(); RejectHttpDynamicWaiters(isolate, context, key, reason); return; } } if (IsModuleEvaluationInProgress(mod->GetStatus())) { TNS_DEBUG(Esm, "[dyn-import][http-loader] waiting on existing evaluation for %s status=%s", key.c_str(), ModuleStatusToString(mod->GetStatus())); return; } if (mod->GetStatus() != v8::Module::kEvaluated) { v8::Local evalResult; { v8::TryCatch tcEvaluate(isolate); if (!mod->Evaluate(context).ToLocal(&evalResult)) { RemoveModuleFromRegistry(isolate, key); v8::Local reason = BuildModuleFailureReason(isolate, tcEvaluate, "Evaluation failed (http-loader)", requestUrl); tcEvaluate.Reset(); RejectHttpDynamicWaiters(isolate, context, key, reason); return; } } if (!evalResult.IsEmpty() && evalResult->IsPromise()) { v8::Local p = evalResult.As(); struct EvalWaitData2 { std::string key; v8::Global ctx; v8::Global mod; }; auto* data2 = new EvalWaitData2{ key, v8::Global(isolate, context), v8::Global(isolate, mod)}; auto onFulfilled2 = [](const v8::FunctionCallbackInfo& info) { v8::Isolate* iso = info.GetIsolate(); v8::HandleScope hs(iso); if (!info.Data()->IsExternal()) return; auto* d = static_cast( info.Data().As()->Value( v8::kExternalPointerTypeTagDefault)); v8::Local ctx = d->ctx.Get(iso); std::string keyLocal = d->key; v8::Local modLocal = d->mod.Get(iso); ResolveHttpDynamicWaiters(iso, ctx, keyLocal, modLocal); delete d; }; auto onRejected2 = [](const v8::FunctionCallbackInfo& info) { v8::Isolate* iso = info.GetIsolate(); v8::HandleScope hs(iso); if (!info.Data()->IsExternal()) return; auto* d = static_cast( info.Data().As()->Value( v8::kExternalPointerTypeTagDefault)); v8::Local ctx = d->ctx.Get(iso); std::string keyLocal = d->key; v8::Local reason = (info.Length() > 0) ? info[0] : v8::Exception::Error(ArgConverter::ConvertToV8String( iso, "Evaluation failed (http-loader TLA)")); if (LogCategoryEnabled(LogCategory::Esm)) { v8::String::Utf8Value r(iso, reason); if (*r) { TNS_DEBUG(Esm, "[dyn-import][http-loader][tla] rejected: %s", *r); } } RejectHttpDynamicWaiters(iso, ctx, keyLocal, reason); delete d; }; v8::Local thenFulfillTpl2 = v8::FunctionTemplate::New( isolate, onFulfilled2, v8::External::New(isolate, data2, v8::kExternalPointerTypeTagDefault)); v8::Local thenFulfill2 = thenFulfillTpl2->GetFunction(context).ToLocalChecked(); v8::Local thenRejectTpl2 = v8::FunctionTemplate::New( isolate, onRejected2, v8::External::New(isolate, data2, v8::kExternalPointerTypeTagDefault)); v8::Local thenReject2 = thenRejectTpl2->GetFunction(context).ToLocalChecked(); p->Then(context, thenFulfill2, thenReject2) .FromMaybe(v8::Local()); return; } } ResolveHttpDynamicWaiters(isolate, context, key, mod); return; } } v8::Local reason = tcLoad.HasCaught() ? tcLoad.Exception() : v8::Exception::Error(ArgConverter::ConvertToV8String( isolate, "HTTP fetch/compile failed: " + requestUrl)); tcLoad.Reset(); RejectHttpDynamicWaiters(isolate, context, key, reason); } // ───────────────────────────────────────────────────────────── // ImportModuleDynamicallyCallback — host callback for `import()` expressions. // // Structure: builtins → one pass through the shared resolution seam → blob URL // path → HTTP fast path (with coalescing + cache) → local module load → // instantiate/evaluate/TLA settle. v8::MaybeLocal ImportModuleDynamicallyCallback( v8::Local context, v8::Local /*host_defined_options*/, v8::Local resource_name, v8::Local specifier, v8::Local /*import_assertions*/) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) { return v8::MaybeLocal(); } auto& registry = moduleState->registry; auto& modulesInFlight = moduleState->modulesInFlight; auto& httpDynamicWaiters = moduleState->httpDynamicWaiters; const std::optional specUtf8 = ModuleSpecifierUtf8(isolate, specifier); if (!specUtf8.has_value()) { v8::EscapableHandleScope nulScope(isolate); v8::Local nulResolver; if (!v8::Promise::Resolver::New(context).ToLocal(&nulResolver)) { return v8::MaybeLocal(); } nulResolver ->Reject(context, v8::Exception::Error(ArgConverter::ConvertToV8String( isolate, NulSpecifierMessage(isolate, specifier)))) .FromMaybe(false); return nulScope.Escape(nulResolver->GetPromise()); } std::string rawSpec = *specUtf8; TNS_DEBUG(Esm, "[dyn-import] -> %s", rawSpec.c_str()); if (LogCategoryEnabled(LogCategory::Esm)) { v8::Local resName = resource_name; if (!resName.IsEmpty() && resName->IsString()) { v8::String::Utf8Value rn(isolate, resName); if (*rn) { TNS_DEBUG(Esm, "[dyn-import][referrer] %s", *rn); } } } // Builtin modules never touch 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(ArgConverter::ConvertToV8String( isolate, NsBuiltinModules::NotFoundMessage(rawSpec))); // Reject must not run with a pending exception on the isolate. tc.Reset(); builtinResolver->Reject(context, error).FromMaybe(false); } return builtinScope.Escape(builtinResolver->GetPromise()); } // The specifier reaches the shared seam verbatim. Whether its query is // identity (a served module) or noise (a file) is the seam's decision, made // the same way for a static import and an import(). std::string normalizedSpec = rawSpec; v8::EscapableHandleScope scope(isolate); v8::Local resolver; if (!v8::Promise::Resolver::New(context).ToLocal(&resolver)) { return v8::MaybeLocal(); } // ── Resolution for dynamic import() ── // The specifier goes through the shared seam exactly once, with the referrer // key taken from the host-supplied resource name and canonicalized the way // the registry keys it: a scope matches an import() exactly as it matches a // static import from the same module. Everything below routes THIS // resolution — re-resolving the string further down would run the import map // a second time, and that pass would have no referrer. const LoaderVocabulary& vocabulary = moduleState->vocabulary; std::string dynamicReferrerKey; if (!resource_name.IsEmpty() && resource_name->IsString()) { v8::String::Utf8Value resourceUtf8(isolate, resource_name); if (*resourceUtf8) { dynamicReferrerKey = CanonicalizeRegistryKey(*resourceUtf8); } } const ModuleResolution dynamicResolution = ResolveSpecifierToPath(normalizedSpec, dynamicReferrerKey); if (!dynamicResolution.blocked.empty()) { resolver ->Reject(context, v8::Exception::Error(ArgConverter::ConvertToV8String( isolate, UnresolvedModuleMessage(dynamicResolution)))) .FromMaybe(false); return scope.Escape(resolver->GetPromise()); } if (!dynamicResolution.specifier.empty() && dynamicResolution.specifier != normalizedSpec) { normalizedSpec = dynamicResolution.specifier; 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.empty() && dynamicResolution.url != normalizedSpec) { TNS_DEBUG(Esm, "[dyn-import][http-rel] %s -> %s", normalizedSpec.c_str(), dynamicResolution.url.c_str()); normalizedSpec = dynamicResolution.url; } // A blob URL is looked up, and keyed, the way the File API resolves it: // without its fragment, with its query. { const std::string blobUrl = BlobStoreUrl(normalizedSpec); if (!blobUrl.empty()) { normalizedSpec = blobUrl; } } try { // ── Blob URL support (e.g. blob:nativescript/) ── // Retrieve the blob content from the global BLOB_STORE via // URL.InternalAccessor.getData() (installed by Android's blob-url.js) and // compile it as an ES module. if (!normalizedSpec.empty() && StartsWith(normalizedSpec, "blob:nativescript/")) { const std::string blobRegistryKey = CanonicalizeRegistryKey(normalizedSpec); TNS_DEBUG(Esm, "[dyn-import][blob] trying blob URL %s key=%s", normalizedSpec.c_str(), blobRegistryKey.c_str()); auto existingIt = registry.find(blobRegistryKey); if (existingIt != registry.end()) { v8::Local existing = existingIt->second.Get(isolate); if (!existing.IsEmpty()) { v8::Module::Status existingStatus = existing->GetStatus(); TNS_DEBUG(Esm, "[dyn-import][blob-cache] hit %s status=%s", blobRegistryKey.c_str(), ModuleStatusToString(existingStatus)); if (existingStatus == v8::Module::kErrored) { RemoveModuleFromRegistry(isolate, blobRegistryKey); } else if (IsModuleEvaluationInProgress(existingStatus)) { modulesInFlight.insert(blobRegistryKey); httpDynamicWaiters[blobRegistryKey].emplace_back(isolate, resolver); TNS_DEBUG(Esm, "[dyn-import][blob-await] queued waiter for %s status=%s", blobRegistryKey.c_str(), ModuleStatusToString(existingStatus)); return scope.Escape(resolver->GetPromise()); } else { resolver->Resolve(context, existing->GetModuleNamespace()) .FromMaybe(false); return scope.Escape(resolver->GetPromise()); } } else { RemoveModuleFromRegistry(isolate, blobRegistryKey); } } if (modulesInFlight.find(blobRegistryKey) != modulesInFlight.end()) { TNS_DEBUG(Esm, "[dyn-import][blob] coalesce in-flight %s", blobRegistryKey.c_str()); httpDynamicWaiters[blobRegistryKey].emplace_back(isolate, resolver); return scope.Escape(resolver->GetPromise()); } modulesInFlight.insert(blobRegistryKey); httpDynamicWaiters[blobRegistryKey].emplace_back(isolate, resolver); v8::TryCatch tc(isolate); v8::Local globalObj = context->Global(); v8::Local urlCtorVal; if (!globalObj ->Get(context, ArgConverter::ConvertToV8String(isolate, "URL")) .ToLocal(&urlCtorVal) || !urlCtorVal->IsFunction()) { TNS_DEBUG(Esm, "[dyn-import][blob] URL constructor not found"); RejectHttpDynamicWaiters( isolate, context, blobRegistryKey, v8::Exception::Error(ArgConverter::ConvertToV8String( isolate, "URL constructor not available"))); return scope.Escape(resolver->GetPromise()); } v8::Local urlCtor = urlCtorVal.As(); v8::Local internalAccessorVal; if (!urlCtor ->Get(context, ArgConverter::ConvertToV8String(isolate, "InternalAccessor")) .ToLocal(&internalAccessorVal) || !internalAccessorVal->IsObject()) { TNS_DEBUG(Esm, "[dyn-import][blob] URL.InternalAccessor not found"); RejectHttpDynamicWaiters( isolate, context, blobRegistryKey, v8::Exception::Error(ArgConverter::ConvertToV8String( isolate, "URL.InternalAccessor not available"))); return scope.Escape(resolver->GetPromise()); } v8::Local internalAccessor = internalAccessorVal.As(); v8::Local getDataVal; if (!internalAccessor ->Get(context, ArgConverter::ConvertToV8String(isolate, "getData")) .ToLocal(&getDataVal) || !getDataVal->IsFunction()) { TNS_DEBUG(Esm, "[dyn-import][blob] URL.InternalAccessor.getData not found"); RejectHttpDynamicWaiters( isolate, context, blobRegistryKey, v8::Exception::Error(ArgConverter::ConvertToV8String( isolate, "URL.InternalAccessor.getData not available"))); return scope.Escape(resolver->GetPromise()); } v8::Local getDataFn = getDataVal.As(); v8::Local urlArg = ArgConverter::ConvertToV8String(isolate, normalizedSpec); v8::Local blobDataVal; if (!getDataFn->Call(context, internalAccessor, 1, &urlArg) .ToLocal(&blobDataVal) || blobDataVal->IsNullOrUndefined()) { TNS_DEBUG(Esm, "[dyn-import][blob] blob not found in BLOB_STORE: %s", normalizedSpec.c_str()); std::string msg = "Blob not found: " + normalizedSpec; RejectHttpDynamicWaiters( isolate, context, blobRegistryKey, v8::Exception::Error(ArgConverter::ConvertToV8String(isolate, msg))); return scope.Escape(resolver->GetPromise()); } if (!blobDataVal->IsObject()) { TNS_DEBUG(Esm, "[dyn-import][blob] blob data is not an object"); RejectHttpDynamicWaiters( isolate, context, blobRegistryKey, v8::Exception::Error( ArgConverter::ConvertToV8String(isolate, "Invalid blob data"))); return scope.Escape(resolver->GetPromise()); } v8::Local blobData = blobDataVal.As(); v8::Local blobVal; if (!blobData ->Get(context, ArgConverter::ConvertToV8String(isolate, "blob")) .ToLocal(&blobVal) || !blobVal->IsObject()) { TNS_DEBUG(Esm, "[dyn-import][blob] blob property not found"); RejectHttpDynamicWaiters( isolate, context, blobRegistryKey, v8::Exception::Error(ArgConverter::ConvertToV8String( isolate, "Blob object not found"))); return scope.Escape(resolver->GetPromise()); } v8::Local blobObj = blobVal.As(); v8::Local textFnVal; if (!blobObj ->Get(context, ArgConverter::ConvertToV8String(isolate, "text")) .ToLocal(&textFnVal) || !textFnVal->IsFunction()) { TNS_DEBUG(Esm, "[dyn-import][blob] Blob.text() not available"); RejectHttpDynamicWaiters( isolate, context, blobRegistryKey, v8::Exception::Error(ArgConverter::ConvertToV8String( isolate, "Blob.text() not available"))); return scope.Escape(resolver->GetPromise()); } v8::Local textFn = textFnVal.As(); // Keep the two failure modes distinct — a throw out of text() and a // non-thenable return — and carry the thrown value's text into the // rejection to preserve diagnostics. v8::Local textResultVal; std::string textFailure; { v8::TryCatch textTc(isolate); if (!textFn->Call(context, blobObj, 0, nullptr) .ToLocal(&textResultVal)) { textFailure = "Blob.text() threw"; if (textTc.HasCaught()) { v8::String::Utf8Value thrown(isolate, textTc.Exception()); if (*thrown) { textFailure += std::string(": ") + *thrown; } } } } v8::Local textPromise; if (textFailure.empty() && !AdoptThenable(isolate, context, textResultVal).ToLocal(&textPromise)) { textFailure = "Blob.text() did not return a thenable"; } if (!textFailure.empty()) { TNS_DEBUG(Esm, "[dyn-import][blob] %s", textFailure.c_str()); RejectHttpDynamicWaiters( isolate, context, blobRegistryKey, v8::Exception::Error( ArgConverter::ConvertToV8String(isolate, textFailure))); return scope.Escape(resolver->GetPromise()); } struct BlobImportData { v8::Global ctx; std::string blobUrl; std::string registryKey; }; auto* data = new BlobImportData{v8::Global(isolate, context), normalizedSpec, blobRegistryKey}; auto onFulfilled = [](const v8::FunctionCallbackInfo& info) { v8::Isolate* iso = info.GetIsolate(); v8::HandleScope hs(iso); if (!info.Data()->IsExternal()) return; auto* d = static_cast( info.Data().As()->Value( v8::kExternalPointerTypeTagDefault)); v8::Local ctx = d->ctx.Get(iso); if (info.Length() < 1 || !info[0]->IsString()) { RejectHttpDynamicWaiters(iso, ctx, d->registryKey, v8::Exception::Error( ArgConverter::ConvertToV8String( iso, "Blob text is not a string"))); delete d; return; } v8::String::Utf8Value codeUtf8(iso, info[0]); std::string code = *codeUtf8 ? *codeUtf8 : ""; TNS_DEBUG(Esm, "[dyn-import][blob] compiling blob module, code length=%zu", code.size()); v8::Local mod; bool compiled = false; std::string compileError; { // A pending exception would escape this callback into V8's promise // machinery; the waiters are this path's failure channel. v8::TryCatch tcCompile(iso); compiled = CompileModuleForResolveRegisterOnly(iso, ctx, code, d->blobUrl) .ToLocal(&mod); if (!compiled) { compileError = DescribeCaughtError(iso, ctx, tcCompile); } } if (!compiled) { std::string msg = "Failed to compile blob module"; if (!compileError.empty()) { msg += ": " + compileError; } RejectHttpDynamicWaiters( iso, ctx, d->registryKey, v8::Exception::Error(ArgConverter::ConvertToV8String(iso, msg))); delete d; return; } if (mod->GetStatus() == v8::Module::kUninstantiated) { v8::TryCatch tcInstantiate(iso); if (!mod->InstantiateModule(ctx, &ResolveModuleCallback) .FromMaybe(false)) { RemoveModuleFromRegistry(iso, d->registryKey); v8::Local reason = BuildModuleFailureReason( iso, tcInstantiate, "Failed to instantiate blob module", d->registryKey); tcInstantiate.Reset(); RejectHttpDynamicWaiters(iso, ctx, d->registryKey, reason); delete d; return; } } if (IsModuleEvaluationInProgress(mod->GetStatus())) { TNS_DEBUG(Esm, "[dyn-import][blob] waiting on existing evaluation for %s status=%s", d->registryKey.c_str(), ModuleStatusToString(mod->GetStatus())); delete d; return; } if (mod->GetStatus() != v8::Module::kEvaluated) { v8::Local evalResult; { v8::TryCatch tcEvaluate(iso); if (!mod->Evaluate(ctx).ToLocal(&evalResult)) { RemoveModuleFromRegistry(iso, d->registryKey); v8::Local reason = BuildModuleFailureReason( iso, tcEvaluate, "Failed to evaluate blob module", d->registryKey); tcEvaluate.Reset(); RejectHttpDynamicWaiters(iso, ctx, d->registryKey, reason); delete d; return; } } if (!evalResult.IsEmpty() && evalResult->IsPromise()) { struct BlobEvalData { std::string registryKey; v8::Global ctx; v8::Global mod; }; auto* evalData = new BlobEvalData{ d->registryKey, v8::Global(iso, ctx), v8::Global(iso, mod)}; auto onEvalFulfilled = [](const v8::FunctionCallbackInfo& info) { v8::Isolate* iso = info.GetIsolate(); v8::HandleScope hs(iso); if (!info.Data()->IsExternal()) return; auto* d = static_cast( info.Data().As()->Value( v8::kExternalPointerTypeTagDefault)); v8::Local ctx = d->ctx.Get(iso); v8::Local mod = d->mod.Get(iso); ResolveHttpDynamicWaiters(iso, ctx, d->registryKey, mod); delete d; }; auto onEvalRejected = [](const v8::FunctionCallbackInfo& info) { v8::Isolate* iso = info.GetIsolate(); v8::HandleScope hs(iso); if (!info.Data()->IsExternal()) return; auto* d = static_cast( info.Data().As()->Value( v8::kExternalPointerTypeTagDefault)); v8::Local ctx = d->ctx.Get(iso); v8::Local reason = info.Length() > 0 ? info[0] : v8::Exception::Error( ArgConverter::ConvertToV8String( iso, "Blob module evaluation failed")); RemoveModuleFromRegistry(iso, d->registryKey); RejectHttpDynamicWaiters(iso, ctx, d->registryKey, reason); delete d; }; v8::Local evalPromise = evalResult.As(); v8::Local onEvalFulfilledFn = v8::Function::New( ctx, onEvalFulfilled, v8::External::New(iso, evalData, v8::kExternalPointerTypeTagDefault)) .ToLocalChecked(); v8::Local onEvalRejectedFn = v8::Function::New( ctx, onEvalRejected, v8::External::New(iso, evalData, v8::kExternalPointerTypeTagDefault)) .ToLocalChecked(); evalPromise->Then(ctx, onEvalFulfilledFn, onEvalRejectedFn) .FromMaybe(v8::Local()); delete d; return; } } ResolveHttpDynamicWaiters(iso, ctx, d->registryKey, mod); delete d; }; auto onRejected = [](const v8::FunctionCallbackInfo& info) { v8::Isolate* iso = info.GetIsolate(); v8::HandleScope hs(iso); if (!info.Data()->IsExternal()) return; auto* d = static_cast( info.Data().As()->Value( v8::kExternalPointerTypeTagDefault)); v8::Local ctx = d->ctx.Get(iso); v8::Local reason = info.Length() > 0 ? info[0] : v8::Exception::Error(ArgConverter::ConvertToV8String( iso, "Blob text() failed")); RejectHttpDynamicWaiters(iso, ctx, d->registryKey, reason); delete d; }; v8::Local onFulfilledFn = v8::Function::New( context, onFulfilled, v8::External::New(isolate, data, v8::kExternalPointerTypeTagDefault)) .ToLocalChecked(); v8::Local onRejectedFn = v8::Function::New( context, onRejected, v8::External::New(isolate, data, v8::kExternalPointerTypeTagDefault)) .ToLocalChecked(); textPromise->Then(context, onFulfilledFn, onRejectedFn) .FromMaybe(v8::Local()); return scope.Escape(resolver->GetPromise()); } // ── HTTP(S) fast path ── // Security: HttpFetchModule gates remote module access centrally. if (dynamicResolution.kind == ModuleResolution::Kind::kHttp) { TNS_DEBUG(Esm, "[dyn-import][http-loader] trying URL %s", normalizedSpec.c_str()); std::string key = CanonicalizeNormalizedHttpUrlKey(normalizedSpec); // Volatile-pattern eviction: if the URL matches any configured volatile // pattern, evict the registered module so every import requests it // again. Policy is supplied exclusively by JS via ns:module `configureLoader({ // volatilePatterns })` — the runtime carries no framework or server URL // vocabulary of its own. bool isVolatile = IsVolatileUrl(vocabulary, normalizedSpec); if (isVolatile) { auto ex = registry.find(key); if (ex != registry.end()) { TNS_DEBUG(Esm, "[dyn-import][http-cache] drop volatile %s", key.c_str()); RemoveModuleFromRegistry(isolate, key); } } // Coalesce concurrent dynamic imports for the same HTTP key. auto inflight = modulesInFlight.find(key) != modulesInFlight.end(); if (inflight) { TNS_DEBUG(Esm, "[dyn-import][http] coalesce in-flight %s", key.c_str()); httpDynamicWaiters[key].emplace_back(isolate, resolver); return scope.Escape(resolver->GetPromise()); } // If module was already compiled, resolve immediately. auto itExisting = registry.find(key); if (itExisting != registry.end()) { v8::Local existing = itExisting->second.Get(isolate); if (!existing.IsEmpty()) { TNS_DEBUG(Esm, "[dyn-import][http-cache] hit %s status=%s", key.c_str(), ModuleStatusToString(existing->GetStatus())); v8::Module::Status st = existing->GetStatus(); if (st == v8::Module::kErrored) { TNS_DEBUG(Esm, "[dyn-import][http-cache] dropping errored module for %s", key.c_str()); RemoveModuleFromRegistry(isolate, key); } else if (IsModuleEvaluationInProgress(st)) { if (QueueHttpDynamicWaiterIfInFlight(isolate, key, existing, resolver)) { return scope.Escape(resolver->GetPromise()); } TNS_DEBUG(Esm, "[dyn-import][http-cache] avoiding re-entrant Evaluate for %s status=%s", key.c_str(), ModuleStatusToString(st)); resolver->Resolve(context, existing->GetModuleNamespace()) .FromMaybe(false); return scope.Escape(resolver->GetPromise()); } else { if (st != v8::Module::kEvaluated) { modulesInFlight.insert(key); TNS_DEBUG(Esm, "[dyn-import][http-cache] awaiting evaluation %s", key.c_str()); httpDynamicWaiters[key].emplace_back(isolate, resolver); if (st == v8::Module::kUninstantiated) { v8::TryCatch tcInstantiate(isolate); if (!existing->InstantiateModule(context, &ResolveModuleCallback) .FromMaybe(false)) { RemoveModuleFromRegistry(isolate, key); v8::Local reason = BuildModuleFailureReason( isolate, tcInstantiate, "Instantiation failed (http-cache hit)", key); tcInstantiate.Reset(); RejectHttpDynamicWaiters(isolate, context, key, reason); return scope.Escape(resolver->GetPromise()); } } if (IsModuleEvaluationInProgress(existing->GetStatus())) { return scope.Escape(resolver->GetPromise()); } v8::Local evalResult; { v8::TryCatch tcEvaluate(isolate); if (!existing->Evaluate(context).ToLocal(&evalResult)) { RemoveModuleFromRegistry(isolate, key); v8::Local reason = BuildModuleFailureReason( isolate, tcEvaluate, "Evaluation failed (http-cache hit)", key); tcEvaluate.Reset(); RejectHttpDynamicWaiters(isolate, context, key, reason); return scope.Escape(resolver->GetPromise()); } } if (!evalResult.IsEmpty() && evalResult->IsPromise()) { v8::Local p = evalResult.As(); struct EvalWaitData { std::string key; v8::Global ctx; v8::Global mod; }; auto* data = new EvalWaitData{ key, v8::Global(isolate, context), v8::Global(isolate, existing)}; auto onFulfilled = [](const v8::FunctionCallbackInfo& info) { v8::Isolate* iso = info.GetIsolate(); v8::HandleScope hs(iso); if (!info.Data()->IsExternal()) return; auto* d = static_cast( info.Data().As()->Value( v8::kExternalPointerTypeTagDefault)); v8::Local ctx = d->ctx.Get(iso); std::string keyLocal = d->key; v8::Local modLocal = d->mod.Get(iso); ResolveHttpDynamicWaiters(iso, ctx, keyLocal, modLocal); delete d; }; auto onRejected = [](const v8::FunctionCallbackInfo& info) { v8::Isolate* iso = info.GetIsolate(); v8::HandleScope hs(iso); if (!info.Data()->IsExternal()) return; auto* d = static_cast( info.Data().As()->Value( v8::kExternalPointerTypeTagDefault)); v8::Local ctx = d->ctx.Get(iso); std::string keyLocal = d->key; v8::Local reason = (info.Length() > 0) ? info[0] : v8::Exception::Error( ArgConverter::ConvertToV8String( iso, "Evaluation failed (http-cache TLA)")); if (LogCategoryEnabled(LogCategory::Esm)) { v8::String::Utf8Value r(iso, reason); if (*r) { TNS_DEBUG(Esm, "[dyn-import][http-cache][tla] rejected: %s", *r); } } RejectHttpDynamicWaiters(iso, ctx, keyLocal, reason); delete d; }; v8::Local thenFulfillTpl = v8::FunctionTemplate::New( isolate, onFulfilled, v8::External::New(isolate, data, v8::kExternalPointerTypeTagDefault)); v8::Local thenFulfill = thenFulfillTpl->GetFunction(context).ToLocalChecked(); v8::Local thenRejectTpl = v8::FunctionTemplate::New( isolate, onRejected, v8::External::New(isolate, data, v8::kExternalPointerTypeTagDefault)); v8::Local thenReject = thenRejectTpl->GetFunction(context).ToLocalChecked(); p->Then(context, thenFulfill, thenReject) .FromMaybe(v8::Local()); return scope.Escape(resolver->GetPromise()); } ResolveHttpDynamicWaiters(isolate, context, key, existing); return scope.Escape(resolver->GetPromise()); } resolver->Resolve(context, existing->GetModuleNamespace()) .FromMaybe(false); return scope.Escape(resolver->GetPromise()); } } } // Mark in-flight and start the async graph load. modulesInFlight.insert(key); httpDynamicWaiters[key].emplace_back(isolate, resolver); const std::string requestUrl = normalizedSpec; StartModuleGraphLoad( isolate, context, requestUrl, /*fetchDeadline=*/std::nullopt, [key, requestUrl, isolate](bool ok, const std::string& errorMessage, v8::Local completionContext) { v8::Isolate* iso = isolate; if (!ok) { RejectHttpDynamicWaiters( iso, completionContext, key, v8::Exception::Error( ArgConverter::ConvertToV8String(iso, errorMessage))); return; } FinishHttpDynamicImport(iso, completionContext, key, requestUrl); }); return scope.Escape(resolver->GetPromise()); } // ── Local path ── // 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 looper. if (dynamicResolution.kind == ModuleResolution::Kind::kFile) { RunModuleGraphLoadPumped(isolate, context, dynamicResolution.key, kModuleEvaluateDeadlineSeconds); } v8::TryCatch resolveTc(isolate); v8::MaybeLocal maybeModule = LoadResolvedModule(isolate, context, dynamicResolution); TNS_DEBUG(Esm, "[dyn-import][resolver-call] raw=%s resolved=%s", rawSpec.c_str(), normalizedSpec.c_str()); if (maybeModule.IsEmpty()) { if (resolveTc.HasCaught()) { v8::Local resolveError = resolveTc.Exception(); resolveTc.Reset(); resolver->Reject(context, resolveError).FromMaybe(false); return scope.Escape(resolver->GetPromise()); } else { std::string msg = "Module resolution failed for dynamic import: "; msg += normalizedSpec.empty() ? "" : normalizedSpec; resolver ->Reject(context, v8::Exception::Error( ArgConverter::ConvertToV8String(isolate, msg))) .FromMaybe(false); return scope.Escape(resolver->GetPromise()); } } v8::Local module = maybeModule.ToLocalChecked(); if (module->GetStatus() == v8::Module::kUninstantiated) { v8::TryCatch ictc(isolate); if (!module->InstantiateModule(context, &ResolveModuleCallback) .FromMaybe(false)) { TNS_DEBUG(Esm, "[dyn-import] instantiate failed %s", normalizedSpec.c_str()); std::string msg = std::string("Failed to instantiate module: ") + normalizedSpec; if (ictc.HasCaught()) { std::string exStr = ArgConverter::ToString(isolate, ictc.Exception()); if (!exStr.empty()) { msg.append(" — "); msg.append(exStr); } } ictc.Reset(); resolver ->Reject(context, v8::Exception::Error( ArgConverter::ConvertToV8String(isolate, msg))) .FromMaybe(false); return scope.Escape(resolver->GetPromise()); } } // A kEvaluating module (TLA in flight, or a cycle re-entry) falls through // deliberately: Evaluate() on an already-evaluating module returns its // existing top-level capability promise, so the TLA chain below coalesces // this import with the in-flight evaluation. if (module->GetStatus() != v8::Module::kEvaluated) { v8::Local evalResult; if (!module->Evaluate(context).ToLocal(&evalResult)) { TNS_DEBUG(Esm, "[dyn-import] evaluation failed %s", normalizedSpec.c_str()); v8::Local ex = BuildModuleFailureReason( isolate, resolveTc, "Evaluation failed for module", normalizedSpec); resolveTc.Reset(); resolver->Reject(context, ex).FromMaybe(false); return scope.Escape(resolver->GetPromise()); } if (!evalResult.IsEmpty() && evalResult->IsPromise()) { v8::Local p = evalResult.As(); struct DynEvalData { v8::Global ctx; v8::Global mod; v8::Global res; }; auto* d = new DynEvalData{ v8::Global(isolate, context), v8::Global(isolate, module), v8::Global(isolate, resolver)}; auto onFulfilled = [](const v8::FunctionCallbackInfo& info) { v8::Isolate* iso = info.GetIsolate(); v8::HandleScope hs(iso); if (!info.Data()->IsExternal()) return; auto* d = static_cast( info.Data().As()->Value( v8::kExternalPointerTypeTagDefault)); v8::Local ctx = d->ctx.Get(iso); v8::Local modLocal = d->mod.Get(iso); v8::Local res = d->res.Get(iso); TNS_DEBUG(Esm, "[dyn-import][tla] fulfilled, resolving namespace"); if (!res.IsEmpty()) res->Resolve(ctx, modLocal->GetModuleNamespace()).FromMaybe(false); delete d; }; auto onRejected = [](const v8::FunctionCallbackInfo& info) { v8::Isolate* iso = info.GetIsolate(); v8::HandleScope hs(iso); if (!info.Data()->IsExternal()) return; auto* d = static_cast( info.Data().As()->Value( v8::kExternalPointerTypeTagDefault)); v8::Local ctx = d->ctx.Get(iso); v8::Local res = d->res.Get(iso); v8::Local reason = (info.Length() > 0) ? info[0] : v8::Exception::Error(ArgConverter::ConvertToV8String( iso, "Evaluation failed (TLA)")); if (LogCategoryEnabled(LogCategory::Esm)) { v8::String::Utf8Value r(iso, reason); if (*r) { TNS_DEBUG(Esm, "[dyn-import][tla] rejected: %s", *r); } } if (!res.IsEmpty()) res->Reject(ctx, reason).FromMaybe(false); delete d; }; v8::Local fulfillTpl = v8::FunctionTemplate::New( isolate, onFulfilled, v8::External::New(isolate, d, v8::kExternalPointerTypeTagDefault)); v8::Local fulfill = fulfillTpl->GetFunction(context).ToLocalChecked(); v8::Local rejectTpl = v8::FunctionTemplate::New( isolate, onRejected, v8::External::New(isolate, d, v8::kExternalPointerTypeTagDefault)); v8::Local reject = rejectTpl->GetFunction(context).ToLocalChecked(); p->Then(context, fulfill, reject).FromMaybe(v8::Local()); return scope.Escape(resolver->GetPromise()); } } // Final verify before resolving for non-HTTP paths. v8::Local nsFinal = module->GetModuleNamespace(); if (nsFinal->IsObject()) { v8::Local o = nsFinal.As(); v8::TryCatch tc3(isolate); v8::Local defVal; if (!o->Get(context, ArgConverter::ConvertToV8String(isolate, "default")) .ToLocal(&defVal)) { TNS_DEBUG(Esm, "[dyn-import][verify] ns.default threw after eval (generic) %s", normalizedSpec.c_str()); v8::Local tdzError = tc3.HasCaught() ? tc3.Exception() : v8::Exception::Error(ArgConverter::ConvertToV8String( isolate, "TDZ on default after eval (generic)")); tc3.Reset(); resolver->Reject(context, tdzError).FromMaybe(false); return scope.Escape(resolver->GetPromise()); } } { // Resolving reads `then` off the namespace; a module exporting `then` // can make that read throw (TDZ in a cycle) — that is the importer's // rejection, never a CHECK. v8::TryCatch tcResolve(isolate); if (resolver->Resolve(context, module->GetModuleNamespace()).IsNothing()) { v8::Local reason = tcResolve.HasCaught() ? tcResolve.Exception() : v8::Exception::Error(ArgConverter::ConvertToV8String( isolate, "Cannot resolve the namespace of " + normalizedSpec)); tcResolve.Reset(); resolver->Reject(context, reason).FromMaybe(false); return scope.Escape(resolver->GetPromise()); } } TNS_DEBUG(Esm, "[dyn-import] resolved %s", normalizedSpec.c_str()); } catch (NativeScriptException& ex) { TNS_DEBUG(Esm, "[dyn-import] native failed %s", normalizedSpec.c_str()); // v8-callbacks.h: this callback must reject the promise it returns and // leave nothing scheduled on the isolate, so the exception is caught back // out of ReThrowToV8 and becomes the rejection reason instead. v8::TryCatch nativeTc(isolate); ex.ReThrowToV8(); v8::Local error = nativeTc.HasCaught() ? nativeTc.Exception() : v8::Exception::Error(ArgConverter::ConvertToV8String( isolate, "Native error during dynamic import")); nativeTc.Reset(); resolver->Reject(context, error).FromMaybe(false); } return scope.Escape(resolver->GetPromise()); } // ───────────────────────────────────────────────────────────── // InitializeImportMetaObject — populates `import.meta.url` and // `import.meta.dirname`. `import.meta.hot` is JS policy and is deliberately // NOT set here (matches the port spec). void InitializeImportMetaObject(v8::Local context, v8::Local module, v8::Local meta) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) return; const std::string modulePath = FindKeyForModule(*moduleState, isolate, module); const std::string moduleUrl = ReportedModuleUrl(modulePath); // `dirname` is a filesystem notion; a URL-backed module has no directory, so // it gets the URL with its last path segment stripped — stable and useful in // a log line. A key with no path beyond the host or scheme body has nothing // to strip and keeps its identity. std::string moduleDirname; if (modulePath.empty()) { moduleDirname = "/app"; } else if (HasUrlScheme(modulePath)) { size_t schemeEnd = modulePath.find("://"); size_t pathStart = (schemeEnd == std::string::npos) ? std::string::npos : modulePath.find('/', schemeEnd + 3); size_t lastSlash = modulePath.find_last_of('/'); if (pathStart != std::string::npos && lastSlash != std::string::npos && lastSlash > pathStart) { moduleDirname = modulePath.substr(0, lastSlash); } else { moduleDirname = modulePath; } } else { const std::string path = FileModulePath(modulePath); size_t lastSlash = path.find_last_of("/\\"); moduleDirname = lastSlash == std::string::npos ? "/app" : path.substr(0, lastSlash); } meta->CreateDataProperty( context, ArgConverter::ConvertToV8String(isolate, "url"), ArgConverter::ConvertToV8String(isolate, moduleUrl)) .FromMaybe(false); meta->CreateDataProperty( context, ArgConverter::ConvertToV8String(isolate, "dirname"), ArgConverter::ConvertToV8String(isolate, moduleDirname)) .FromMaybe(false); } // ───────────────────────────────────────────────────────────── // The `ns:module` dev surface // // The runtime's dev surface is deliberately small: it exposes *mechanism* // only (resolution config, registry eviction, registry introspection). All // HMR *policy* — boot orchestration, `import.meta.hot`, full reload, CSS // apply, WebSocket protocol, worker teardown — lives in the JS dev client // (`@nativescript/vite`). The surface is reachable exclusively through the // `ns:module` builtin module (require / static import / import()); there is // no global. namespace { void InstallDevFunction(v8::Isolate* isolate, v8::Local context, v8::Local target, const char* name, v8::FunctionCallback callback) { v8::Local fnTpl = v8::FunctionTemplate::New(isolate, callback); v8::Local fn = fnTpl->GetFunction(context).ToLocalChecked(); fn->SetName(ToV8String(isolate, name)); target->CreateDataProperty(context, ToV8String(isolate, name), fn).Check(); } // The only sections configureLoader understands. An unlisted key is a typo the // caller hears about rather than a setting that silently does nothing. constexpr const char* kLoaderConfigKeys[] = {"importMap", "volatilePatterns", "canonicalization"}; void ConfigureLoaderCallback(const v8::FunctionCallbackInfo& info) { v8::Isolate* isolate = info.GetIsolate(); v8::HandleScope scope(isolate); v8::Local ctx = isolate->GetCurrentContext(); try { auto throwTypeError = [&](const std::string& message) { isolate->ThrowException(v8::Exception::TypeError(ToV8String(isolate, message))); }; if (info.Length() < 1 || !info[0]->IsObject()) { throwTypeError("configureLoader expects a config object"); return; } v8::Local config = info[0].As(); // ── Validation phase ───────────────────────────────────────────── // Nothing below mutates the vocabulary. The whole config is checked first // so a rejected call leaves every section exactly as it was — the // atomicity the import map alone used to have, now covering the entire // call. // Unknown top-level keys. v8::Local configKeys; if (!config->GetOwnPropertyNames(ctx, v8::PropertyFilter::ONLY_ENUMERABLE, v8::KeyConversionMode::kConvertToString) .ToLocal(&configKeys)) { return; // pending exception } for (uint32_t i = 0; i < configKeys->Length(); i++) { v8::Local keyVal; if (!configKeys->Get(ctx, i).ToLocal(&keyVal)) { return; } std::string key = ArgConverter::ToString(isolate, keyVal); bool known = false; for (const char* candidate : kLoaderConfigKeys) { if (key == candidate) { known = true; break; } } if (!known) { throwTypeError("configureLoader: unknown option '" + key + "'"); return; } } // Reads `obj[key]` as an array of strings into `out`. `label` names the // section in any error. Returns false with an exception pending on a type // failure; `present` distinguishes "absent" from "present and valid". auto readStringArray = [&](v8::Local obj, const char* key, const std::string& label, std::vector& out, bool* present) -> bool { *present = false; v8::Local val; if (!obj->Get(ctx, ToV8String(isolate, key)).ToLocal(&val)) { return false; } if (val->IsUndefined()) { return true; } if (!val->IsArray()) { throwTypeError("configureLoader: " + label + " must be an array of strings"); return false; } v8::Local arr = val.As(); for (uint32_t i = 0; i < arr->Length(); i++) { v8::Local elem; if (!arr->Get(ctx, i).ToLocal(&elem)) { return false; } if (!elem->IsString()) { throwTypeError("configureLoader: " + label + "[" + std::to_string(i) + "] must be a string"); return false; } out.push_back(ArgConverter::ToString(isolate, elem)); } *present = true; return true; }; // importMap: an object or a JSON string. Parsed here, installed below. ParsedImportMap parsedMap; bool haveImportMap = false; size_t importMapBytes = 0; v8::Local importMapVal; if (!config->Get(ctx, ToV8String(isolate, "importMap")).ToLocal(&importMapVal)) { return; } if (!importMapVal->IsUndefined()) { std::string jsonStr; if (importMapVal->IsString()) { jsonStr = ArgConverter::ToString(isolate, importMapVal); } else if (importMapVal->IsObject() && !importMapVal->IsFunction()) { // A function is an object to V8, and JSON::Stringify hands one back // as the literal text "undefined" rather than failing — so it is // excluded here and falls through to the TypeError below. v8::Local stringified; if (!v8::JSON::Stringify(ctx, importMapVal).ToLocal(&stringified)) { return; // a throwing toJSON / getter propagates unchanged } std::string text = ArgConverter::ToString(isolate, stringified); // The same "undefined" answer reaches a plain object whose toJSON // returns undefined; leaving jsonStr empty routes it to the same // TypeError. if (text != "undefined") { jsonStr = std::move(text); } } if (jsonStr.empty()) { throwTypeError("configureLoader: importMap must be an object or a JSON string"); return; } std::string importMapError; if (!ParseImportMap(isolate, jsonStr, &parsedMap, &importMapError)) { // The previous map is still installed: a rejected update changes // nothing, so a typo cannot empty a live session's vocabulary. throwTypeError("configureLoader: " + importMapError); return; } haveImportMap = true; importMapBytes = jsonStr.size(); } // volatilePatterns: array of strings. Presence of the array decides, not // its contents — an empty one is explicit policy meaning "nothing is // volatile any more", the same rule canonicalization follows, and the only // reading under which a present section replaces its state wholesale. std::vector patterns; bool havePatterns = false; if (!readStringArray(config, "volatilePatterns", "volatilePatterns", patterns, &havePatterns)) { return; } // canonicalization: { stripParams, forPathPrefixes, preserveQueryFor } — // the URL vocabulary CanonicalizeHttpUrlKey applies (see its doc block). // Presence of the object marks the vocabulary as configured, replacing the // built-in fallback entirely (empty arrays are honored as explicit policy). CanonicalizationConfig canon; bool haveCanon = false; v8::Local canonVal; if (!config->Get(ctx, ToV8String(isolate, "canonicalization")).ToLocal(&canonVal)) { return; } if (!canonVal->IsUndefined()) { if (!canonVal->IsObject()) { throwTypeError("configureLoader: canonicalization must be an object"); return; } v8::Local canonObj = canonVal.As(); bool ignored = false; if (!readStringArray(canonObj, "stripParams", "canonicalization.stripParams", canon.stripParams, &ignored) || !readStringArray(canonObj, "forPathPrefixes", "canonicalization.forPathPrefixes", canon.devPathPrefixes, &ignored) || !readStringArray(canonObj, "preserveQueryFor", "canonicalization.preserveQueryFor", canon.preserveQueryPrefixes, &ignored)) { return; } haveCanon = true; } // ── Apply phase ────────────────────────────────────────────────── // Everything validated; from here nothing can fail on the caller's input. if (haveImportMap) { std::string installError; if (!InstallParsedImportMap(std::move(parsedMap), &installError)) { throwTypeError("configureLoader: " + installError); return; } TNS_DEBUG(Esm, "[ns:module configureLoader] import map set (%zu bytes)", importMapBytes); } if (havePatterns) { SetVolatilePatterns(patterns); TNS_DEBUG(Esm, "[ns:module configureLoader] %zu volatile patterns set", patterns.size()); } if (haveCanon) { SetCanonicalizationConfig(std::move(canon)); } } catch (NativeScriptException& e) { e.ReThrowToV8(); } catch (std::exception& e) { NativeScriptException nsEx(std::string("Error: c++ exception: ") + e.what() + "\n"); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } void InvalidateModulesCallback(const v8::FunctionCallbackInfo& info) { v8::Isolate* isolate = info.GetIsolate(); v8::HandleScope scope(isolate); v8::Local ctx = isolate->GetCurrentContext(); try { if (info.Length() < 1 || !info[0]->IsArray()) { isolate->ThrowException(v8::Exception::TypeError( ToV8String(isolate, "invalidateModules expects an array of URL strings"))); return; } v8::Local urlsArray = info[0].As(); std::vector urls; urls.reserve(urlsArray->Length()); for (uint32_t index = 0; index < urlsArray->Length(); index++) { v8::Local value; if (!urlsArray->Get(ctx, index).ToLocal(&value)) { return; } if (!value->IsString()) { isolate->ThrowException(v8::Exception::TypeError(ToV8String( isolate, "invalidateModules: urls[" + std::to_string(index) + "] must be a string"))); return; } urls.push_back(ArgConverter::ToString(isolate, value)); } if (tns::LogCategoryEnabled(tns::LogCategory::Registry)) { TNS_DEBUG(Registry, "invalidate called urls.count=%zu", urls.size()); size_t shown = 0; for (const auto& u : urls) { if (shown >= 32) break; TNS_DEBUG(Registry, "invalidate url[%zu]=%s", shown, u.c_str()); shown++; } if (urls.size() > shown) { TNS_DEBUG(Registry, "invalidate (hidden %zu more URL(s))", urls.size() - shown); } } tns::InvalidateModules(isolate, ctx, urls); } catch (NativeScriptException& e) { e.ReThrowToV8(); } catch (std::exception& e) { NativeScriptException nsEx(std::string("Error: c++ exception: ") + e.what() + "\n"); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } void GetLoadedModuleUrlsCallback(const v8::FunctionCallbackInfo& info) { v8::Isolate* isolate = info.GetIsolate(); v8::HandleScope scope(isolate); v8::Local ctx = isolate->GetCurrentContext(); try { std::vector urls = tns::GetLoadedModuleUrls(); v8::Local result = v8::Array::New(isolate, static_cast(urls.size())); for (uint32_t index = 0; index < urls.size(); index++) { result->Set(ctx, index, ToV8String(isolate, urls[index])).FromMaybe(false); } info.GetReturnValue().Set(result); } catch (NativeScriptException& e) { e.ReThrowToV8(); } catch (std::exception& e) { NativeScriptException nsEx(std::string("Error: c++ exception: ") + e.what() + "\n"); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } // Debug-only: how the loader would fetch `url` — the active transport, the // URL's host class and that class's concurrency cap. void HttpFetchDiagnosticsCallback(const v8::FunctionCallbackInfo& info) { v8::Isolate* isolate = info.GetIsolate(); v8::Local context = isolate->GetCurrentContext(); if (info.Length() < 1 || !info[0]->IsString()) { isolate->ThrowException(v8::Exception::TypeError( ToV8String(isolate, "httpFetchDiagnostics expects a URL string"))); return; } const ModuleFetchHostClass hostClass = ModuleFetchHostClassOf(ArgConverter::ToString(isolate, info[0])); v8::Local result = v8::Object::New(isolate); if (!result->CreateDataProperty(context, ToV8String(isolate, "transport"), ToV8String(isolate, ActiveModuleTransportName())) .FromMaybe(false) || !result->CreateDataProperty(context, ToV8String(isolate, "hostClass"), ToV8String(isolate, ModuleFetchHostClassName(hostClass))) .FromMaybe(false) || !result->CreateDataProperty( context, ToV8String(isolate, "concurrency"), v8::Number::New(isolate, (double) ModuleFetchConcurrency(hostClass))) .FromMaybe(false)) { return; } info.GetReturnValue().Set(result); } // Debug-only: forcePlatformHttpTransport(force) — process-wide, for every // isolate, from the next fetch on. void ForcePlatformHttpTransportCallback(const v8::FunctionCallbackInfo& info) { v8::Isolate* isolate = info.GetIsolate(); if (info.Length() < 1 || !info[0]->IsBoolean()) { isolate->ThrowException(v8::Exception::TypeError( ToV8String(isolate, "forcePlatformHttpTransport expects a boolean"))); return; } SetForcePlatformModuleTransport(info[0]->BooleanValue(isolate)); } void SetHttpCacheEnabledCallback(const v8::FunctionCallbackInfo& info) { v8::Isolate* isolate = info.GetIsolate(); if (info.Length() < 1 || !info[0]->IsBoolean()) { isolate->ThrowException(v8::Exception::TypeError( ToV8String(isolate, "setHttpCacheEnabled expects a boolean"))); return; } SetModuleHttpCacheEnabled(info[0]->BooleanValue(isolate)); } void ClearHttpCacheCallback(const v8::FunctionCallbackInfo& info) { try { ClearModuleHttpCache(); } catch (NativeScriptException& e) { e.ReThrowToV8(); } catch (std::exception& e) { NativeScriptException nsEx(std::string("Error: c++ exception: ") + e.what() + "\n"); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } } // namespace bool BuildNsModuleBinding(v8::Local context, v8::Local binding) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); InstallDevFunction(isolate, context, binding, "configureLoader", ConfigureLoaderCallback); InstallDevFunction(isolate, context, binding, "invalidateModules", InvalidateModulesCallback); InstallDevFunction(isolate, context, binding, "getLoadedModuleUrls", GetLoadedModuleUrlsCallback); InstallDevFunction(isolate, context, binding, "setHttpCacheEnabled", SetHttpCacheEnabledCallback); InstallDevFunction(isolate, context, binding, "clearHttpCache", ClearHttpCacheCallback); if (!ModuleInternal::InstallCreateRequireBinding(context, binding)) { return false; } if (IsDebuggable()) { InstallDevFunction(isolate, context, binding, "httpFetchDiagnostics", HttpFetchDiagnosticsCallback); InstallDevFunction(isolate, context, binding, "forcePlatformHttpTransport", ForcePlatformHttpTransportCallback); auto canonicalizeCb = [](const v8::FunctionCallbackInfo& info) { v8::Isolate* iso = info.GetIsolate(); try { if (info.Length() < 1 || !info[0]->IsString()) { iso->ThrowException(v8::Exception::TypeError( ToV8String(iso, "canonicalizeHttpUrlKey expects a URL string"))); return; } std::string key = CanonicalizeHttpUrlKey(ArgConverter::ToString(iso, info[0])); info.GetReturnValue().Set(ToV8String(iso, key)); } catch (NativeScriptException& e) { e.ReThrowToV8(); } catch (std::exception& e) { NativeScriptException nsEx(std::string("Error: c++ exception: ") + e.what() + "\n"); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } }; v8::Local fn; if (!v8::Function::New(context, canonicalizeCb).ToLocal(&fn)) { // The member is absent-by-design in release, but a debug build // must not report the binding built with a pending exception. return false; } { fn->SetName(ToV8String(isolate, "canonicalizeHttpUrlKey")); if (!binding ->CreateDataProperty(context, ToV8String(isolate, "canonicalizeHttpUrlKey"), fn) .FromMaybe(false)) { return false; } } // The release allowlist rule, which debug builds never apply to // fetches. `url` is spelled as the loader spells the URL it fetches, // and `entries` goes through the same loading as the // `security.remoteModuleAllowlist` config array. auto allowlistCb = [](const v8::FunctionCallbackInfo& info) { v8::Isolate* iso = info.GetIsolate(); v8::Local ctx = iso->GetCurrentContext(); std::vector> entries; bool valid = info.Length() >= 2 && info[0]->IsString() && info[1]->IsArray(); if (valid) { v8::Local list = info[1].As(); for (uint32_t i = 0; valid && i < list->Length(); i++) { v8::Local item; if (!list->Get(ctx, i).ToLocal(&item)) { return; // the element getter threw } valid = item->IsString(); if (valid) { entries.push_back(ToExactUtf8(iso, item.As())); } } } if (!valid) { iso->ThrowException(v8::Exception::TypeError(ToV8String( iso, "remoteUrlMatchesAllowlist expects a URL string and an array of strings"))); return; } const std::string raw = ArgConverter::ToString(iso, info[0]); const std::string url = NormalizeHttpModuleUrl(raw); info.GetReturnValue().Set(RemoteUrlAllowedByAllowlist( url.empty() ? raw : url, RemoteModuleAllowlistFromConfig(entries))); }; v8::Local allowlistFn; if (!v8::Function::New(context, allowlistCb).ToLocal(&allowlistFn)) { return false; } allowlistFn->SetName(ToV8String(isolate, "remoteUrlMatchesAllowlist")); if (!binding ->CreateDataProperty(context, ToV8String(isolate, "remoteUrlMatchesAllowlist"), allowlistFn) .FromMaybe(false)) { return false; } auto statsCb = [](const v8::FunctionCallbackInfo& info) { v8::Isolate* iso = info.GetIsolate(); v8::Local ctx = iso->GetCurrentContext(); const std::pair fields[] = { {"finalized", (double) g_streamedCompileCounters.finalized.load()}, {"discarded", (double) g_streamedCompileCounters.discarded.load()}, {"fellBack", (double) g_streamedCompileCounters.fellBack.load()}, {"running", (double) g_streamedCompileCounters.running.load()}, {"teardownWaits", (double) g_streamedCompileCounters.teardownWaits.load()}, }; v8::Local stats = v8::Object::New(iso); for (const auto& field : fields) { if (!stats->CreateDataProperty(ctx, ToV8String(iso, field.first), v8::Number::New(iso, field.second)) .FromMaybe(false)) { return; } } info.GetReturnValue().Set(stats); }; v8::Local statsFn; if (!v8::Function::New(context, statsCb).ToLocal(&statsFn)) { return false; } statsFn->SetName(ToV8String(isolate, "streamedCompileStats")); if (!binding ->CreateDataProperty(context, ToV8String(isolate, "streamedCompileStats"), statsFn) .FromMaybe(false)) { return false; } } return true; } } // namespace tns