/* * Module.cpp * * Created on: Jun 24, 2015 * Author: gatanasov */ #include "ModuleInternal.h" #include "ModuleInternalCallbacks.h" #include "BuiltinLoader.h" #include "File.h" #include "HttpLoader.h" #include "ModuleUrl.h" #include "JniLocalRef.h" #include "ArgConverter.h" #include "NativeScriptAssert.h" #include "Constants.h" #include "CrashBreadcrumbs.h" #include "EventLoop.h" #include "NativeScriptException.h" #include "NsBuiltinModules.h" #include "napi/NapiModules.h" #include "Util.h" #include "SimpleProfiler.h" #include "CallbackHandlers.h" #include "ManualInstrumentation.h" #include "Runtime.h" #include "RuntimeState.h" #include "TraceLog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace v8; using namespace std; using namespace tns; bool ModuleInternal::IsHttpModulePath(const std::string& path) { return !NormalizeHttpModuleUrl(path).empty(); } // What a rejected evaluation promise says about itself. struct RejectionDetail { // The reason's own text: an Error's `message`, or the reason stringified. std::string message; // A bounded rendering of the reason's `stack`, filled only when asked for. std::string stackPreview; }; // `detail`, when non-null, receives the reason's parts unjoined; reading the // stack costs a property get plus a copy, so callers pass null unless a trace // is actually going to be emitted. static std::string PromiseRejectionMessage(Isolate* isolate, Local promise, const std::string& path, RejectionDetail* detail = nullptr) { std::string errorMessage = "Module evaluation promise rejected: " + path; TryCatch tc(isolate); Local reason = promise->Result(); if (reason.IsEmpty()) { return errorMessage; } std::string reasonText; Local context = isolate->GetCurrentContext(); if (reason->IsObject()) { Local errorObj = reason.As(); Local messageVal; if (errorObj->Get(context, ArgConverter::ConvertToV8String(isolate, "message")) .ToLocal(&messageVal) && messageVal->IsString()) { v8::String::Utf8Value messageUtf8(isolate, messageVal); if (*messageUtf8) { reasonText.assign(*messageUtf8); } } Local stackVal; if (detail != nullptr && errorObj->Get(context, ArgConverter::ConvertToV8String(isolate, "stack")) .ToLocal(&stackVal) && stackVal->IsString()) { v8::String::Utf8Value stackUtf8(isolate, stackVal); if (*stackUtf8) { std::string stack(*stackUtf8); detail->stackPreview = stack.size() > 240 ? stack.substr(0, 240) + "…" : stack; } } } else { auto maybeReasonStr = reason->ToString(context); if (!maybeReasonStr.IsEmpty()) { v8::String::Utf8Value reasonUtf8(isolate, maybeReasonStr.ToLocalChecked()); if (*reasonUtf8) { reasonText.assign(*reasonUtf8); } } } if (!reasonText.empty()) { errorMessage.append(" — "); errorMessage.append(reasonText); } if (detail != nullptr) { detail->message = std::move(reasonText); } if (tc.HasCaught()) { tc.Reset(); } return errorMessage; } // A package-style specifier: neither a path nor a scheme, so it may be claimed // by a registry rather than resolved on disk. static bool IsBareSpecifier(const std::string& specifier) { if (specifier.empty() || specifier[0] == '.' || specifier[0] == '/' || specifier[0] == '~') { return false; } return specifier.find(':') == std::string::npos; } static ModuleEvaluationOptions BootEntryEvaluationOptions(bool isHttpModule); static ModuleEvaluationOptions RequireEvaluationOptions(ModuleEvaluationPolicy policy); // Helper function to check if a file path is an ES module (.mjs) but not a source map (.mjs.map) bool ModuleInternal::IsESModule(const std::string& path) { return path.size() >= 4 && path.compare(path.size() - 4, 4, ".mjs") == 0 && !(path.size() >= 8 && path.compare(path.size() - 8, 8, ".mjs.map") == 0); } ModuleInternal::ModuleInternal() : m_isolate(nullptr), m_requireFunction(nullptr), m_requireFactoryFunction(nullptr) { } ModuleInternal::~ModuleInternal() { delete this->m_requireFunction; delete this->m_requireFactoryFunction; for (const auto& pair: this->m_requireCache) { delete pair.second; } this->m_requireCache.clear(); /* * Runs after Isolate::Dispose, so the handles are freed with the isolate and * only the wrappers are deleted -- v8::Persistent does not reset in its * destructor, which is what makes that safe here. * * Deduplicated by pointer: a module is cached under both its resolved path * and its cache key, and both entries hold the same Persistent. */ robin_hood::unordered_set*> freed; for (const auto& pair: this->m_loadedModules) { if (freed.insert(pair.second.obj).second) { delete pair.second.obj; } } this->m_loadedModules.clear(); } void ModuleInternal::Init(Isolate* isolate, const string& baseDir) { JEnv env; if (MODULE_CLASS == nullptr) { MODULE_CLASS = env.FindClass("com/tns/Module"); NS_CHECK(MODULE_CLASS != nullptr); RESOLVE_PATH_METHOD_ID = env.GetStaticMethodID(MODULE_CLASS, "resolvePath", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"); NS_CHECK(RESOLVE_PATH_METHOD_ID != nullptr); GET_APPLICATION_FILES_PATH_METHOD_ID = env.GetStaticMethodID(MODULE_CLASS, "getApplicationFilesPath", "()Ljava/lang/String;"); NS_CHECK(GET_APPLICATION_FILES_PATH_METHOD_ID != nullptr); } m_isolate = isolate; auto context = isolate->GetCurrentContext(); auto global = context->Global(); Local result; auto success = BuiltinLoader::RunBuiltin(context, BuiltinId::kRequireFactory).ToLocal(&result); NS_CHECK(success && result->IsFunction()); auto requireFactoryFunction = result.As(); m_requireFactoryFunction = new Persistent(isolate, requireFactoryFunction); auto external = External::New(isolate, this, v8::kExternalPointerTypeTagDefault); // Only the require factory receives this one, so the evaluation options it // forwards were validated at mint time. auto requireFuncTemplate = FunctionTemplate::New(isolate, RequireCallback, external); auto requireFunc = requireFuncTemplate->GetFunction(context).ToLocalChecked(); m_requireFunction = new Persistent(isolate, requireFunc); // App code can reach this one, so it reads nothing but the specifier and the // calling directory: a caller must not be able to hand itself a pumping // policy, an unbounded deadline or a looper-slicing require. auto publicRequireTemplate = FunctionTemplate::New(isolate, RequirePublicCallback, external); global->Set(context, ArgConverter::ConvertToV8String(isolate, "__nativeRequire"), publicRequireTemplate->GetFunction(context).ToLocalChecked()); // terminate() cannot reach this isolate yet - a worker's is published to its // parent only once the runtime is up - so this mint is checked as hard as // the factory's own load above. Local globalRequire; const bool minted = GetRequireFunction( isolate, baseDir.empty() ? Constants::APP_ROOT_FOLDER_PATH : baseDir, RequireEvaluationOptions(ModuleEvaluationPolicy::kSyncStrict)).ToLocal(&globalRequire); NS_CHECK(minted); global->Set(context, ArgConverter::ConvertToV8String(isolate, "require"), globalRequire); } // How an entry module's graph settles. For local modules the bound is a yield, // not a timeout: the default pump runs only nestable V8 tasks while these JS // frames are on the stack, so a TLA parked on anything else can never settle // in-place — give it one short window, then return and let the real event // loop (or the draining boot backstop) finish it after the turn. HTTP entries // must settle in-pump — the dev client needs the rejection reason // synchronously — so they get the full deadline and the looper-equivalent // drain, the same split iOS makes with its runloop slice. static ModuleEvaluationOptions BootEntryEvaluationOptions(bool isHttpModule) { ModuleEvaluationOptions options; options.policy = ModuleEvaluationPolicy::kSyncPumping; options.deadlineSeconds = isHttpModule ? kModuleEvaluateDeadlineSeconds : 1.0; options.timeoutBehavior = isHttpModule ? ModuleEvaluationOptions::TimeoutBehavior::kThrow : ModuleEvaluationOptions::TimeoutBehavior::kReturnPending; options.pumpRunLoop = isHttpModule; return options; } // How a graph reached through require() settles. A pumping require must settle // or throw — handing back a half-initialized namespace is what the strict // policy exists to prevent — so it gets the full deadline. By default the // pump runs nestable v8 tasks and microtasks only, matching iOS: running JS // timers or loop posts in the middle of an arbitrary require is opt-in // (pumpRunLoop), because those callbacks execute underneath the require's JS // frames. static ModuleEvaluationOptions RequireEvaluationOptions(ModuleEvaluationPolicy policy) { ModuleEvaluationOptions options; options.policy = policy; if (policy == ModuleEvaluationPolicy::kSyncPumping) { options.deadlineSeconds = kModuleEvaluateDeadlineSeconds; options.timeoutBehavior = ModuleEvaluationOptions::TimeoutBehavior::kThrow; options.pumpRunLoop = false; } return options; } // The require cache is keyed by directory AND by the options the require was // minted with: a pumping require for a directory must never be served from a // strict require cached for the same directory, in either direction. static std::string RequireCacheKey(const std::string& dirName, const ModuleEvaluationOptions& options) { std::string key = dirName; key += '\x1f'; key += std::to_string(static_cast(options.policy)); key += '\x1f'; key += std::to_string(options.deadlineSeconds); key += '\x1f'; key += (options.timeoutBehavior == ModuleEvaluationOptions::TimeoutBehavior::kThrow) ? '1' : '0'; key += options.pumpRunLoop ? '1' : '0'; return key; } MaybeLocal ModuleInternal::GetRequireFunction(Isolate* isolate, const string& dirName, const ModuleEvaluationOptions& options) { TNSPERF(); Local requireFunc; const std::string cacheKey = RequireCacheKey(dirName, options); auto itFound = m_requireCache.find(cacheKey); if (itFound != m_requireCache.end()) { requireFunc = Local::New(isolate, *itFound->second); } else { auto requireFuncFactory = Local::New(isolate, *m_requireFactoryFunction); auto context = isolate->GetCurrentContext(); auto requireInternalFunc = Local::New(isolate, *m_requireFunction); Local args[6] { requireInternalFunc, ArgConverter::ConvertToV8String(isolate, dirName), Integer::New(isolate, static_cast(options.policy)), Number::New(isolate, options.deadlineSeconds), v8::Boolean::New(isolate, options.timeoutBehavior == ModuleEvaluationOptions::TimeoutBehavior::kThrow), v8::Boolean::New(isolate, options.pumpRunLoop) }; Local result; auto thiz = Object::New(isolate); // The factory cannot throw, but entering it is an interrupt check: a // terminate() that reached this isolate since its last one surfaces // here and stays pending for the caller to unwind with. if (!requireFuncFactory->Call(context, thiz, 6, args).ToLocal(&result)) { return MaybeLocal(); } NS_CHECK(result->IsFunction()); requireFunc = result.As(); auto poFunc = new Persistent(isolate, requireFunc); m_requireCache.emplace(cacheKey, poFunc); } return requireFunc; } void ModuleInternal::CreateRequireCallback(const v8::FunctionCallbackInfo& args) { Isolate* isolate = args.GetIsolate(); if (args.Length() < 1 || !args[0]->IsString()) { isolate->ThrowException(Exception::TypeError(ArgConverter::ConvertToV8String( isolate, "createRequire expects a base directory string"))); return; } Runtime* runtime = Runtime::TryGetRuntime(isolate); ModuleInternal* moduleInternal = runtime != nullptr ? runtime->GetModuleInternal() : nullptr; if (moduleInternal == nullptr) { isolate->ThrowException(Exception::Error(ArgConverter::ConvertToV8String( isolate, "createRequire is unavailable: this isolate has no module loader"))); return; } string dirName = ArgConverter::ConvertToString(args[0].As()); const bool pumping = args.Length() > 1 && args[1]->BooleanValue(isolate); ModuleEvaluationOptions options = RequireEvaluationOptions( pumping ? ModuleEvaluationPolicy::kSyncPumping : ModuleEvaluationPolicy::kSyncStrict); // ns-module.js has already validated these and passes undefined for anything // the caller left out, so each present value simply overrides its default. if (args.Length() > 2 && args[2]->IsNumber()) { double deadlineSeconds = args[2].As()->Value(); // A NaN or infinite window makes the pump's deadline arithmetic // undefined, and a non-positive one is no window at all. if (std::isfinite(deadlineSeconds) && deadlineSeconds > 0.0) { options.deadlineSeconds = deadlineSeconds; } } if (args.Length() > 3 && args[3]->IsBoolean()) { options.timeoutBehavior = args[3]->BooleanValue(isolate) ? ModuleEvaluationOptions::TimeoutBehavior::kThrow : ModuleEvaluationOptions::TimeoutBehavior::kReturnPending; } if (args.Length() > 4 && args[4]->IsBoolean()) { options.pumpRunLoop = args[4]->BooleanValue(isolate); } Local require; if (moduleInternal->GetRequireFunction(isolate, dirName, options).ToLocal(&require)) { args.GetReturnValue().Set(require); } } bool ModuleInternal::InstallCreateRequireBinding(Local context, Local binding) { Isolate* isolate = v8::Isolate::GetCurrent(); Local fn; if (!Function::New(context, ModuleInternal::CreateRequireCallback).ToLocal(&fn)) { return false; } fn->SetName(ArgConverter::ConvertToV8String(isolate, "createRequire")); return binding->CreateDataProperty(context, ArgConverter::ConvertToV8String(isolate, "createRequire"), fn) .FromMaybe(false); } // Node's `determineSpecificType` (lib/internal/errors.js), so an // ERR_INVALID_ARG_TYPE-shaped message reads the same here as it does there. // Deliberately side-effect free: no getter, no user `toString`, no `inspect`. static std::string DescribeValueForTypeError(Isolate* isolate, Local value) { if (value.IsEmpty() || value->IsUndefined()) { return "undefined"; } if (value->IsNull()) { return "null"; } if (value->IsFunction()) { std::string name = ArgConverter::ToString(isolate, value.As()->GetName()); return name.empty() ? "an instance of Function" : "function " + name; } if (value->IsObject()) { std::string ctorName = ArgConverter::ToString(isolate, value.As()->GetConstructorName()); return ctorName.empty() ? "an object" : "an instance of " + ctorName; } // A primitive: `type ()`. const char* typeName = "object"; std::string rendered; if (value->IsBoolean()) { typeName = "boolean"; rendered = value->IsTrue() ? "true" : "false"; } else if (value->IsNumber()) { typeName = "number"; double number = value.As()->Value(); // String(-0) is "0", but Node renders the sign, and losing it here would // hide exactly the distinction the message is meant to surface. rendered = (number == 0 && std::signbit(number)) ? "-0" : ArgConverter::ToString(isolate, value); } else if (value->IsBigInt()) { typeName = "bigint"; rendered = ArgConverter::ToString(isolate, value) + "n"; } else if (value->IsSymbol()) { typeName = "symbol"; Local description = value.As()->Description(isolate); rendered = "Symbol(" + (description->IsUndefined() ? std::string() : ArgConverter::ToString(isolate, description)) + ")"; } else { rendered = ArgConverter::ToString(isolate, value); } if (rendered.size() > 28) { rendered = rendered.substr(0, 25) + "..."; } return "type " + std::string(typeName) + " (" + rendered + ")"; } void ModuleInternal::DispatchRequire(const v8::FunctionCallbackInfo& args, bool honorEvaluationOptions) { auto isolate = args.GetIsolate(); // Every path below assumes a string specifier — the builtin probe, the // http(s) guard and the filesystem resolution all read it — so reject a // non-string before any of them rather than casting one unchecked. if (args.Length() < 1 || !args[0]->IsString()) { Local received = args.Length() < 1 ? Local() : args[0]; isolate->ThrowException(Exception::TypeError(ArgConverter::ConvertToV8String( isolate, "The \"id\" argument must be of type string. Received " + DescribeValueForTypeError(isolate, received)))); return; } try { auto thiz = static_cast(args.Data().As()->Value(v8::kExternalPointerTypeTagDefault)); thiz->RequireCallbackImpl(args, honorEvaluationOptions); } catch (NativeScriptException& e) { e.ReThrowToV8(); } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; NativeScriptException nsEx(ss.str()); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } void ModuleInternal::RequireCallback(const v8::FunctionCallbackInfo& args) { DispatchRequire(args, true /* honorEvaluationOptions */); } void ModuleInternal::RequirePublicCallback(const v8::FunctionCallbackInfo& args) { DispatchRequire(args, false /* honorEvaluationOptions */); } void ModuleInternal::RequireCallbackImpl(const v8::FunctionCallbackInfo& args, bool honorEvaluationOptions) { auto isolate = args.GetIsolate(); if (args.Length() < 2) { throw NativeScriptException(string("require should be called with at least two parameters")); } if (!args[0]->IsString()) { throw NativeScriptException(string("require's first parameter should be string")); } if (!args[1]->IsString()) { throw NativeScriptException(string("require's second parameter should be string")); } string moduleName = ArgConverter::ConvertToString(args[0].As()); // Builtin modules resolve before any path handling, so they can never be // shadowed by a file or a package, and an unknown one fails as a missing // builtin rather than as a missing file. Only prefixed specifiers get // here: a bare `util` still resolves through npm. if (NsBuiltinModules::IsBuiltinScheme(moduleName)) { auto context = isolate->GetCurrentContext(); Local exports; if (NsBuiltinModules::GetExports(context, moduleName).ToLocal(&exports)) { args.GetReturnValue().Set(exports); } else if (!NsBuiltinModules::IsRegistered(moduleName)) { isolate->ThrowException(Exception::Error(ArgConverter::ConvertToV8String( isolate, NsBuiltinModules::NotFoundMessage(moduleName)))); } return; } // Node-API addons claim a bare name only, so a path can never be diverted // into the addon registry, and builtins keep priority over both. if (IsBareSpecifier(moduleName) && NapiModules::IsRegistered(moduleName)) { auto context = isolate->GetCurrentContext(); Local exports; if (NapiModules::GetExports(context, moduleName).ToLocal(&exports)) { args.GetReturnValue().Set(exports); } else if (!isolate->HasPendingException()) { isolate->ThrowException(Exception::Error(ArgConverter::ConvertToV8String( isolate, "Node-API module '" + moduleName + "' failed to initialize"))); } return; } // URL-based modules must be loaded via dynamic import(). if (!NormalizeHttpModuleUrl(moduleName).empty()) { throw NativeScriptException("NativeScript: require() of URL module is not supported: " + moduleName + ". Use dynamic import() instead."); } tns::instrumentation::Frame frame("RequireCallback " + moduleName); string callingModuleDirName = ArgConverter::ConvertToString(args[1].As()); auto isData = false; ModuleEvaluationOptions evaluationOptions = RequireEvaluationOptions(ModuleEvaluationPolicy::kSyncStrict); if (honorEvaluationOptions) { // The require factory forwards the options its require was minted with; // an absent policy is the strict default every ordinary require uses. ModuleEvaluationPolicy policy = ModuleEvaluationPolicy::kSyncStrict; if (args.Length() > 2 && args[2]->IsInt32() && args[2].As()->Value() == static_cast(ModuleEvaluationPolicy::kSyncPumping)) { policy = ModuleEvaluationPolicy::kSyncPumping; } evaluationOptions = RequireEvaluationOptions(policy); if (args.Length() > 3 && args[3]->IsNumber()) { double deadlineSeconds = args[3].As()->Value(); // A NaN or infinite window makes the pump's deadline arithmetic // undefined, and a non-positive one is no window at all. if (std::isfinite(deadlineSeconds) && deadlineSeconds > 0.0) { evaluationOptions.deadlineSeconds = deadlineSeconds; } } if (args.Length() > 4 && args[4]->IsBoolean()) { evaluationOptions.timeoutBehavior = args[4]->BooleanValue(isolate) ? ModuleEvaluationOptions::TimeoutBehavior::kThrow : ModuleEvaluationOptions::TimeoutBehavior::kReturnPending; } if (args.Length() > 5 && args[5]->IsBoolean()) { evaluationOptions.pumpRunLoop = args[5]->BooleanValue(isolate); } } auto moduleObj = LoadImpl(isolate, moduleName, callingModuleDirName, isData, evaluationOptions); if (isData) { NS_DCHECK(!moduleObj.IsEmpty()); args.GetReturnValue().Set(moduleObj); } else { auto context = isolate->GetCurrentContext(); Local exportsVal; moduleObj->Get(context, ArgConverter::ConvertToV8String(isolate, "exports")).ToLocal(&exportsVal); NS_DCHECK(!exportsVal.IsEmpty()); auto exportsObj = exportsVal.As(); args.GetReturnValue().Set(exportsObj); } } void ModuleInternal::RequireNativeCallback(const v8::FunctionCallbackInfo& args) { TNSPERF(); auto ext = args.Data().As(); auto funcPtr = reinterpret_cast(ext->Value(v8::kExternalPointerTypeTagDefault)); funcPtr(args); } void ModuleInternal::Load(Local context, const string& path) { TNSPERF(); auto isolate = m_isolate; // The ES module branch compiles and links against // isolate->GetCurrentContext(); a caller that enters the isolate through a // fresh Isolate::Scope has no current context, and CompileModule would // dereference a null native context. The require branch never needed this // because Function::Call enters the context it is handed. Context::Scope context_scope(context); const bool isHttpModule = IsHttpModulePath(path); if (isHttpModule || IsESModule(path)) { if (isHttpModule) { TNS_DEBUG(Esm, "run-module http-esm begin %s", NormalizeHttpModuleUrl(path).c_str()); } // The entry runs before this thread's event loop does, so its graph can // only make progress from the pump inside LoadESModule. LoadESModule(isolate, path, BootEntryEvaluationOptions(isHttpModule)); if (isHttpModule) { TNS_DEBUG(Esm, "run-module http-esm ok %s", NormalizeHttpModuleUrl(path).c_str()); } return; } auto globalObject = context->Global(); auto require = globalObject->Get(context, ArgConverter::ConvertToV8String(isolate, "require")).ToLocalChecked().As(); Local args[] = { ArgConverter::ConvertToV8String(isolate, path) }; // A failed entry must throw through this boundary in every build — the // caller (boot, or a worker's onerror routing) owns the report, and the // boot backstop must never pump with an exception pending on the isolate. TryCatch tc(isolate); Local result; const bool ok = require->Call(context, globalObject, 1, args).ToLocal(&result); if (!ok || tc.HasCaught()) { throw NativeScriptException(tc, "require() failed for module " + path); } } void ModuleInternal::LoadWorker(Local context, const string& path) { TNSPERF(); auto isolate = m_isolate; TryCatch tc(isolate); try { Load(context, path); } catch (NativeScriptException& e) { e.ReThrowToV8(); } if (tc.HasCaught()) { // This will handle any errors that occur when first loading a script (new worker) // exceptions include: syntax errors, throw statements, access of properties of undefined objects // Check if `onerror` handle is implemented // Web behaviour - if onerror handle comes before exception throw - execute it, else - bubble up to main's worker object CallbackHandlers::CallWorkerScopeOnErrorHandle(isolate, tc); } } std::string ModuleInternal::CheckFileExists(Isolate* isolate, const std::string& path, const std::string& baseDir) { JEnv env; JniLocalRef jsModulename(env.NewStringUTF(path.c_str())); JniLocalRef jsBaseDir(env.NewStringUTF(baseDir.c_str())); // Throws a NativeScriptException (through JEnv's pending-exception check) // when nothing resolves, so the conversion below only ever sees a hit. JniLocalRef jsModulePath(env.CallStaticObjectMethod(MODULE_CLASS, RESOLVE_PATH_METHOD_ID, (jstring) jsModulename, (jstring) jsBaseDir)); return ArgConverter::jstringToString((jstring) jsModulePath); } // The trailing extension without its dot, or an empty string when the last // segment has none. A leading dot names a hidden file, not an extension. static std::string PathExtension(const std::string& path) { size_t dot = path.find_last_of('.'); if (dot == std::string::npos || dot + 1 >= path.size()) { return std::string(); } size_t slash = path.find_last_of('/'); if (slash != std::string::npos && (dot < slash || dot == slash + 1)) { return std::string(); } return path.substr(dot + 1); } Local ModuleInternal::LoadImpl(Isolate* isolate, const string& moduleName, const string& baseDir, bool& isData, const ModuleEvaluationOptions& options) { auto pathKind = GetModulePathKind(moduleName); auto cachePathKey = (pathKind == ModulePathKind::Global) ? moduleName : (baseDir + "*" + moduleName); Local result; DEBUG_WRITE(">>LoadImpl cachePathKey=%s", cachePathKey.c_str()); auto it = m_loadedModules.find(cachePathKey); if (it == m_loadedModules.end()) { std::string path; // Search App System libs std::string sys_lib("system_lib://"); if (moduleName.rfind(sys_lib, 0) == 0) { auto pos = moduleName.find(sys_lib); path = std::string(moduleName); path.replace(pos, sys_lib.length(), ""); } else { // Handle tilde path resolution before calling Java path resolution std::string resolvedModuleName = moduleName; if (!moduleName.empty() && moduleName[0] == '~') { // Convert ~/path to ApplicationPath/path std::string tail = moduleName.size() >= 2 && moduleName[1] == '/' ? moduleName.substr(2) : moduleName.substr(1); resolvedModuleName = Constants::APP_ROOT_FOLDER_PATH + "/" + tail; // For .mjs files with tilde paths, use resolved path directly if (Util::EndsWith(resolvedModuleName, ".mjs")) { path = resolvedModuleName; } else { // For non-.mjs files, still use Java resolution with the resolved name JEnv env; JniLocalRef jsModulename(env.NewStringUTF(resolvedModuleName.c_str())); JniLocalRef jsBaseDir(env.NewStringUTF(baseDir.c_str())); JniLocalRef jsModulePath( env.CallStaticObjectMethod(MODULE_CLASS, RESOLVE_PATH_METHOD_ID, (jstring) jsModulename, (jstring) jsBaseDir)); path = ArgConverter::jstringToString((jstring) jsModulePath); } } else { JEnv env; JniLocalRef jsModulename(env.NewStringUTF(moduleName.c_str())); JniLocalRef jsBaseDir(env.NewStringUTF(baseDir.c_str())); JniLocalRef jsModulePath( env.CallStaticObjectMethod(MODULE_CLASS, RESOLVE_PATH_METHOD_ID, (jstring) jsModulename, (jstring) jsBaseDir)); path = ArgConverter::jstringToString((jstring) jsModulePath); } } auto it2 = m_loadedModules.find(path); if (it2 == m_loadedModules.end()) { if (Util::EndsWith(path, ".js") || Util::EndsWith(path, ".mjs") || Util::EndsWith(path, ".so")) { isData = false; result = LoadModule(isolate, path, cachePathKey, options); } else if (Util::EndsWith(path, ".json")) { isData = true; result = LoadData(isolate, path); } else { string errMsg = "Unsupported file extension: " + PathExtension(path); throw NativeScriptException(errMsg); } } else { auto& cacheEntry = it2->second; isData = cacheEntry.isData; result = Local::New(isolate, *cacheEntry.obj); } } else { auto& cacheEntry = it->second; isData = cacheEntry.isData; result = Local::New(isolate, *cacheEntry.obj); } return result; } static bool NamespaceHasOwn(Isolate* isolate, Local context, Local ns, const char* name) { return ns->HasOwnProperty(context, ArgConverter::ConvertToV8String(isolate, name)) .FromMaybe(false); } // The live compiled module behind a registry key, or empty. static Local RegisteredModuleForPath(Isolate* isolate, const std::string& canonicalPath) { auto* registryPtr = ModuleRegistryFor(isolate); if (registryPtr == nullptr) { return Local(); } auto it = registryPtr->find(canonicalPath); if (it == registryPtr->end()) { return Local(); } return it->second.Get(isolate); } // What `require()` of an ES module hands back, per Node's // populateCJSExportsFromESM: an explicit `module.exports` export wins outright; // a namespace with no default export, or one that already declares // __esModule, passes through untouched; everything else gets the facade so // transpiled consumers reading `_mod.__esModule ? _mod.default : _mod` find the // default. Export names are arbitrary strings, hence the own-property probes. static Local RequireExportsForNamespace(Isolate* isolate, Local context, Local ns, const std::string& canonicalPath) { TryCatch tc(isolate); if (NamespaceHasOwn(isolate, context, ns, "module.exports")) { Local moduleExports; if (!ns->Get(context, ArgConverter::ConvertToV8String(isolate, "module.exports")) .ToLocal(&moduleExports)) { throw NativeScriptException( tc, "Cannot read the 'module.exports' export of " + canonicalPath); } return moduleExports; } bool hasDefault = NamespaceHasOwn(isolate, context, ns, "default"); bool hasEsModuleMarker = NamespaceHasOwn(isolate, context, ns, "__esModule"); if (!hasDefault || hasEsModuleMarker) { return ns; } Local target = RegisteredModuleForPath(isolate, canonicalPath); if (target.IsEmpty()) { // The load that produced this namespace registered the module under this // very key, so a miss means the registry and the namespace disagree — // returning the bare namespace would drop __esModule and misroute every // transpiled consumer downstream. throw NativeScriptException( "require() cannot build the exports facade for " + canonicalPath + ": the module evaluated but is absent from the registry under its canonical key"); } Local facade; if (!GetOrCreateRequireFacade(isolate, context, target, canonicalPath).ToLocal(&facade)) { throw NativeScriptException("Cannot build the require() exports facade for " + canonicalPath); } return facade->GetModuleNamespace(); } Local ModuleInternal::LoadModule(Isolate* isolate, const string& modulePath, const string& moduleCacheKey, const ModuleEvaluationOptions& options) { string frameName("LoadModule " + modulePath); tns::instrumentation::Frame frame(frameName); CrashBreadcrumbs::ModuleScope moduleBreadcrumb(modulePath.c_str()); Local result; auto context = isolate->GetCurrentContext(); auto moduleObj = Object::New(isolate); auto exportsObj = Object::New(isolate); auto exportsPropName = ArgConverter::ConvertToV8String(isolate, "exports"); moduleObj->Set(context, exportsPropName, exportsObj); auto fullRequiredModulePath = ArgConverter::ConvertToV8String(isolate, modulePath); moduleObj->Set(context, ArgConverter::ConvertToV8String(isolate, "filename"), fullRequiredModulePath); auto poModuleObj = new Persistent(isolate, moduleObj); TempModule tempModule(this, modulePath, moduleCacheKey, poModuleObj); TryCatch tc(isolate); // Check if this is an ES module (.mjs) if (Util::EndsWith(modulePath, ".mjs")) { // require()'s route into the ES module system, which cannot wait: an // async graph is refused rather than pumped. Local moduleNamespace = LoadESModule(isolate, modulePath, options); // A load that produced no namespace produced no module either — an // isolate torn down mid-load, or a graph that never settled. Caching the // empty exports object would intern that failure for the process. if (moduleNamespace.IsEmpty()) { throw NativeScriptException("ES module load returned empty value " + modulePath); } if (!moduleNamespace->IsObject()) { throw NativeScriptException("Failed to load ES module " + modulePath); } // `module.exports` is what Node's populateCJSExportsFromESM produces for // this namespace, not the namespace itself. Local esmExports = RequireExportsForNamespace(isolate, context, moduleNamespace.As(), CanonicalizeRegistryKey(modulePath)); moduleObj->Set(context, ArgConverter::ConvertToV8String(isolate, "exports"), esmExports); tempModule.SaveToCache(); result = moduleObj; return result; } Local moduleFunc; if (Util::EndsWith(modulePath, ".js")) { auto script = LoadScript(isolate, modulePath, fullRequiredModulePath); Local moduleFuncValue; if (!script->Run(context).ToLocal(&moduleFuncValue) || tc.HasCaught()) { throw NativeScriptException(tc, "Error running script " + modulePath); } moduleFunc = moduleFuncValue.As(); } else if (Util::EndsWith(modulePath, ".so")) { // Registrations from libraries this loader did not dlopen (statically // linked addons whose constructors ran at app start) must not be // attributed to whatever `.so` happens to load next. NapiModules::ClaimPendingModule(); auto handle = dlopen(modulePath.c_str(), RTLD_LAZY); if (handle == nullptr) { auto error = dlerror(); string errMsg(error != nullptr ? error : "dlopen failed for " + modulePath); throw NativeScriptException(errMsg); } // A library whose constructors registered a Node-API module is a // Node-API addon: its exports come from the addon registry (Node's // dlopen consumes `modpending` the same way). A library carrying the // NAPI_MODULE / node-addon-api registration symbol instead is // initialized through it — this is also the path a *re*-dlopen of an // already-loaded addon takes, since constructors only run on first // load. NSMain remains the protocol for plain native modules. string napiModuleName = NapiModules::ClaimPendingModule(); void* napiInitSymbol = napiModuleName.empty() ? dlsym(handle, "napi_register_module_v1") : nullptr; if (!napiModuleName.empty() || napiInitSymbol != nullptr) { Local napiExports; bool initialized = napiModuleName.empty() ? NapiModules::InitAddonFromSymbol(context, napiInitSymbol, modulePath).ToLocal(&napiExports) : NapiModules::GetExports(context, napiModuleName).ToLocal(&napiExports); if (!initialized || tc.HasCaught()) { throw NativeScriptException(tc, "Error initializing Node-API module " + (napiModuleName.empty() ? modulePath : napiModuleName)); } moduleObj->Set(context, exportsPropName, napiExports); tempModule.SaveToCache(); result = moduleObj; return result; } auto func = dlsym(handle, "NSMain"); if (func == nullptr) { string errMsg("Cannot find 'NSMain' in " + modulePath); throw NativeScriptException(errMsg); } auto extFunc = External::New(isolate, func, v8::kExternalPointerTypeTagDefault); auto ft = FunctionTemplate::New(isolate, RequireNativeCallback, extFunc); auto maybeFunc = ft->GetFunction(context); if (maybeFunc.IsEmpty() || tc.HasCaught()) { throw NativeScriptException(tc, "Cannot create native module function callback"); } moduleFunc = maybeFunc.ToLocalChecked(); } else { string errMsg = "Unsupported file extension: " + PathExtension(modulePath); throw NativeScriptException(errMsg); } SET_PROFILER_FRAME(); auto fileName = ArgConverter::ConvertToV8String(isolate, modulePath); // dirname() semantics without its fixed-size copy: module paths can // exceed any stack buffer (PATH_MAX is 4096 and node_modules nests). const size_t lastSlash = modulePath.find_last_of('/'); string strDirName = lastSlash == string::npos ? "." : lastSlash == 0 ? "/" : modulePath.substr(0, lastSlash); auto dirName = ArgConverter::ConvertToV8String(isolate, strDirName); // A module's own require inherits the options it was loaded under, so a // pumping require's whole dependency tree keeps pumping. Local require; if (!GetRequireFunction(isolate, strDirName, options).ToLocal(&require)) { throw NativeScriptException(tc, "Cannot create the require function for " + modulePath); } Local requireArgs[5] { moduleObj, exportsObj, require, fileName, dirName }; moduleObj->Set(context, ArgConverter::ConvertToV8String(isolate, "require"), require); auto moduleIdProp = ArgConverter::ConvertToV8String(isolate, "id"); const auto readOnlyFlags = static_cast(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); Maybe success = moduleObj->DefineOwnProperty(isolate->GetCurrentContext(), moduleIdProp, fileName, readOnlyFlags); if (success.IsNothing()) { throw NativeScriptException(string("Couldn't execute method 'DefineOwnProperty' on 'moduleObj' in 'Module::LoadModule'.")); } auto thiz = Object::New(isolate); auto extendsName = ArgConverter::ConvertToV8String(isolate, "__extends"); Local extendsFunc; if (!context->Global()->Get(context, extendsName).ToLocal(&extendsFunc) || tc.HasCaught()) { throw NativeScriptException(tc, "Cannot read '__extends' while loading " + modulePath); } thiz->Set(context, extendsName, extendsFunc); moduleFunc->Call(context, thiz, sizeof(requireArgs) / sizeof(Local ), requireArgs); if (tc.HasCaught()) { throw NativeScriptException(tc, "Error calling module function "); } tempModule.SaveToCache(); result = moduleObj; return result; } Local