From e2758797ddc51a604c3f30f0c130e642356e79bd Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 1 Dec 2026 22:23:08 -0300 Subject: [PATCH 01/11] feat(inspector): ns:inspector, inspector domains in JavaScript registerDomain(name, options) serves a protocol domain from JS to every connected client. The runtime owns enable and disable: it keeps which clients enabled the domain, runs the enabled/disabled and sessionEnabled/sessionDisabled/sessionClosed hooks, and remembers clients that enabled a domain before it was registered. Commands may be async; a throw or rejection answers with an error, with a ProtocolError's code. Each reply reaches its own client only, and events a command emits go out before its reply. domain.emit reaches the clients that enabled the domain, or every client for an alwaysEnabled one. The session handed to hooks and commands sends to one client and wraps, unwraps and releases remote objects for it, through the V8 session of that client; addInspectedObject sets its $0. monotonicTime, wallTime and captureStackTrace give what Network events need. Domains V8 or the runtime implements are refused, and a name has one owner at a time. The module is inert in release builds and in workers. Vendors crdtp/json.h, which turns V8's CBOR protocol objects into JSON. --- NativeScript/inspector/InspectorModule.h | 15 + NativeScript/inspector/InspectorModule.mm | 347 ++++++++++++ NativeScript/inspector/InspectorSessions.h | 3 + NativeScript/inspector/InspectorSessions.mm | 5 + NativeScript/inspector/JsV8InspectorClient.h | 33 ++ NativeScript/inspector/JsV8InspectorClient.mm | 165 +++++- NativeScript/runtime/NsBuiltinModules.cpp | 2 + NativeScript/runtime/js/ns-inspector.js | 533 ++++++++++++++++++ TestRunner/app/tests/NsInspectorTests.js | 101 ++++ TestRunner/app/tests/index.js | 1 + TestRunner/app/tests/nsInspectorWorker.js | 8 + docs/ns-builtin-modules.md | 82 ++- download_v8.sh | 3 +- tools/js2c-inputs.xcfilelist | 1 + tools/v8/vendor_inspector_sources.py | 1 + types/index.d.ts | 1 + types/ns-inspector.d.ts | 97 ++++ v8ios.xcodeproj/project.pbxproj | 8 + 18 files changed, 1400 insertions(+), 6 deletions(-) create mode 100644 NativeScript/inspector/InspectorModule.h create mode 100644 NativeScript/inspector/InspectorModule.mm create mode 100644 NativeScript/runtime/js/ns-inspector.js create mode 100644 TestRunner/app/tests/NsInspectorTests.js create mode 100644 TestRunner/app/tests/nsInspectorWorker.js create mode 100644 types/ns-inspector.d.ts diff --git a/NativeScript/inspector/InspectorModule.h b/NativeScript/inspector/InspectorModule.h new file mode 100644 index 000000000..4a5a6023d --- /dev/null +++ b/NativeScript/inspector/InspectorModule.h @@ -0,0 +1,15 @@ +#ifndef InspectorModule_h +#define InspectorModule_h + +#include "include/v8.h" + +namespace v8_inspector { + +// The natives of the ns:inspector builtin module (runtime/js/ns-inspector.js). +// Built in every isolate; `available` is false where no frontend can attach: +// release builds and workers. +v8::MaybeLocal NsInspectorBinding(v8::Local context); + +} // namespace v8_inspector + +#endif /* InspectorModule_h */ diff --git a/NativeScript/inspector/InspectorModule.mm b/NativeScript/inspector/InspectorModule.mm new file mode 100644 index 000000000..401ca6ca9 --- /dev/null +++ b/NativeScript/inspector/InspectorModule.mm @@ -0,0 +1,347 @@ +#include "InspectorModule.h" + +#include + +#include +#include +#include +#include + +#include "Helpers.h" +#include "JsV8InspectorClient.h" +#include "include/inspector/Runtime.h" +#include "utils.h" +#include "third_party/inspector_protocol/crdtp/json.h" + +using namespace v8; + +namespace v8_inspector { + +namespace { + +StringView Make8BitStringView(const std::string& value) { + return StringView(reinterpret_cast(value.data()), value.size()); +} + +void ThrowError(Isolate* isolate, const std::string& message) { + isolate->ThrowException(Exception::Error(tns::ToV8String(isolate, message))); +} + +JsV8InspectorClient* ClientOrThrow(Isolate* isolate) { + JsV8InspectorClient* client = JsV8InspectorClient::ForIsolate(isolate); + if (client == nullptr) { + ThrowError(isolate, "The inspector is not available"); + } + return client; +} + +// The session of the frontend the first argument names, or null with an +// exception set. +V8InspectorSession* SessionOrThrow(const FunctionCallbackInfo& info, + JsV8InspectorClient* client) { + Isolate* isolate = info.GetIsolate(); + if (info.Length() < 1 || !info[0]->IsNumber()) { + ThrowError(isolate, "Invalid session"); + return nullptr; + } + auto connectionId = static_cast(info[0].As()->Value()); + V8InspectorSession* session = client->SessionFor(connectionId); + if (session == nullptr) { + ThrowError(isolate, "The session is closed"); + } + return session; +} + +// A protocol object as the JSON value a frontend would receive. V8 only +// serializes them to CBOR. +template +MaybeLocal ToValue(Local context, const T& object) { + std::vector cbor; + object.AppendSerialized(&cbor); + std::string json; + if (!v8_crdtp::json::ConvertCBORToJSON(v8_crdtp::SpanFrom(cbor), &json).ok()) { + return MaybeLocal(); + } + return JSON::Parse(context, tns::ToV8String(Isolate::GetCurrent(), json)); +} + +class FunctionInspectable final : public V8InspectorSession::Inspectable { + public: + FunctionInspectable(Isolate* isolate, Local getter) + : isolate_(isolate), getter_(isolate, getter) {} + + Local get(Local context) override { + EscapableHandleScope scope(isolate_); + TryCatch tc(isolate_); + Local value; + if (!getter_.Get(isolate_)->Call(context, Undefined(isolate_), 0, nullptr).ToLocal(&value)) { + return scope.Escape(Undefined(isolate_).As()); + } + return scope.Escape(value); + } + + private: + Isolate* isolate_; + Global getter_; +}; + +void AttachCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = ClientOrThrow(isolate); + if (client == nullptr) { + return; + } + if (info.Length() < 1 || !info[0]->IsObject()) { + ThrowError(isolate, "attach expects a router"); + return; + } + client->SetJsDomainRouter(info[0].As()); +} + +void RegisterCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = ClientOrThrow(isolate); + if (client == nullptr) { + return; + } + std::string name = tns::ToString(isolate, info[0]); + std::vector enabledBefore; + std::string error; + if (!client->RegisterJsDomain(name, enabledBefore, error)) { + ThrowError(isolate, error); + return; + } + Local context = isolate->GetCurrentContext(); + Local result = Array::New(isolate, static_cast(enabledBefore.size())); + for (size_t i = 0; i < enabledBefore.size(); i++) { + result + ->Set(context, static_cast(i), + Number::New(isolate, static_cast(enabledBefore[i]))) + .Check(); + } + info.GetReturnValue().Set(result); +} + +// Throws for a domain the runtime implements, with or without a client. +void CheckDomainCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + std::string name = tns::ToString(isolate, info[0]); + if (JsV8InspectorClient::IsRuntimeDomain(name)) { + ThrowError(isolate, "The " + name + " domain is implemented by the runtime"); + } +} + +void UnregisterCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = JsV8InspectorClient::ForIsolate(isolate); + if (client == nullptr) { + return; + } + std::vector enabled; + if (info.Length() > 1 && info[1]->IsArray()) { + Local context = isolate->GetCurrentContext(); + Local ids = info[1].As(); + for (uint32_t i = 0; i < ids->Length(); i++) { + Local id; + if (ids->Get(context, i).ToLocal(&id) && id->IsNumber()) { + enabled.push_back(static_cast(id.As()->Value())); + } + } + } + client->UnregisterJsDomain(tns::ToString(isolate, info[0]), enabled); +} + +void ConnectionsCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + Local context = isolate->GetCurrentContext(); + std::vector connections; + if (JsV8InspectorClient* client = JsV8InspectorClient::ForIsolate(isolate)) { + connections = client->Connections(); + } + Local result = Array::New(isolate, static_cast(connections.size())); + for (size_t i = 0; i < connections.size(); i++) { + result + ->Set(context, static_cast(i), + Number::New(isolate, static_cast(connections[i]))) + .Check(); + } + info.GetReturnValue().Set(result); +} + +void SendCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = JsV8InspectorClient::ForIsolate(isolate); + if (client == nullptr || info.Length() < 2 || !info[0]->IsNumber() || !info[1]->IsString()) { + return; + } + auto connectionId = static_cast(info[0].As()->Value()); + client->SendRawToConnection(connectionId, tns::ToString(isolate, info[1])); +} + +void WrapObjectCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = ClientOrThrow(isolate); + if (client == nullptr) { + return; + } + V8InspectorSession* session = SessionOrThrow(info, client); + if (session == nullptr) { + return; + } + Local context = isolate->GetCurrentContext(); + std::string group = info.Length() > 2 && info[2]->IsString() ? tns::ToString(isolate, info[2]) + : std::string(); + bool preview = info.Length() > 3 && info[3]->BooleanValue(isolate); + std::unique_ptr remote = + session->wrapObject(context, info[1], Make8BitStringView(group), preview); + if (remote == nullptr) { + ThrowError(isolate, "The value cannot be wrapped"); + return; + } + Local result; + if (!ToValue(context, *remote).ToLocal(&result)) { + if (!isolate->IsExecutionTerminating()) { + ThrowError(isolate, "The value cannot be wrapped"); + } + return; + } + info.GetReturnValue().Set(result); +} + +void UnwrapObjectCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = ClientOrThrow(isolate); + if (client == nullptr) { + return; + } + V8InspectorSession* session = SessionOrThrow(info, client); + if (session == nullptr) { + return; + } + if (info.Length() < 2 || !info[1]->IsString()) { + ThrowError(isolate, "Invalid remote object id"); + return; + } + std::string objectId = tns::ToString(isolate, info[1]); + std::unique_ptr error; + Local value; + Local context; + if (!session->unwrapObject(&error, Make8BitStringView(objectId), &value, &context, nullptr)) { + std::string message = error != nullptr ? ToStdString(error->string()) : std::string(); + ThrowError(isolate, message.empty() ? "Could not find object with given id" : message); + return; + } + info.GetReturnValue().Set(value); +} + +void ReleaseObjectGroupCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = ClientOrThrow(isolate); + if (client == nullptr) { + return; + } + V8InspectorSession* session = SessionOrThrow(info, client); + if (session == nullptr) { + return; + } + session->releaseObjectGroup(Make8BitStringView(tns::ToString(isolate, info[1]))); +} + +void AddInspectedObjectCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = ClientOrThrow(isolate); + if (client == nullptr) { + return; + } + V8InspectorSession* session = SessionOrThrow(info, client); + if (session == nullptr) { + return; + } + if (info.Length() < 2 || !info[1]->IsFunction()) { + isolate->ThrowException(Exception::TypeError( + tns::ToV8String(isolate, "addInspectedObject expects a function"))); + return; + } + session->addInspectedObject( + std::make_unique(isolate, info[1].As())); +} + +void CaptureStackTraceCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = JsV8InspectorClient::ForIsolate(isolate); + if (client == nullptr) { + return; + } + std::unique_ptr trace = client->Inspector()->captureStackTrace(true); + if (trace == nullptr || trace->isEmpty()) { + return; + } + Local result; + if (ToValue(isolate->GetCurrentContext(), *trace->buildInspectorObject(0)).ToLocal(&result)) { + info.GetReturnValue().Set(result); + } +} + +// Network.MonotonicTime: seconds on the clock the platform's TimeTicks, and +// with them trace events, use on Darwin. +void MonotonicTimeCallback(const FunctionCallbackInfo& info) { + static mach_timebase_info_data_t timebase = [] { + mach_timebase_info_data_t value; + mach_timebase_info(&value); + return value; + }(); + double nanoseconds = + static_cast(mach_absolute_time()) * timebase.numer / timebase.denom; + info.GetReturnValue().Set(nanoseconds / 1e9); +} + +// Network.TimeSinceEpoch: seconds, fractional. +void WallTimeCallback(const FunctionCallbackInfo& info) { + info.GetReturnValue().Set(std::chrono::duration( + std::chrono::system_clock::now().time_since_epoch()) + .count()); +} + +void LogErrorCallback(const FunctionCallbackInfo& info) { + Log(@"ns:inspector: %s", tns::ToString(info.GetIsolate(), info[0]).c_str()); +} + +} // namespace + +MaybeLocal NsInspectorBinding(Local context) { + Isolate* isolate = Isolate::GetCurrent(); + Local binding = Object::New(isolate); + bool available = JsV8InspectorClient::ForIsolate(isolate) != nullptr; + if (!binding + ->Set(context, tns::ToV8String(isolate, "available"), v8::Boolean::New(isolate, available)) + .FromMaybe(false)) { + return MaybeLocal(); + } + + const std::pair natives[] = { + {"attach", AttachCallback}, + {"checkDomain", CheckDomainCallback}, + {"register", RegisterCallback}, + {"unregister", UnregisterCallback}, + {"connections", ConnectionsCallback}, + {"send", SendCallback}, + {"wrapObject", WrapObjectCallback}, + {"unwrapObject", UnwrapObjectCallback}, + {"releaseObjectGroup", ReleaseObjectGroupCallback}, + {"addInspectedObject", AddInspectedObjectCallback}, + {"captureStackTrace", CaptureStackTraceCallback}, + {"monotonicTime", MonotonicTimeCallback}, + {"wallTime", WallTimeCallback}, + {"logError", LogErrorCallback}, + }; + for (const auto& native : natives) { + Local function; + if (!Function::New(context, native.second).ToLocal(&function) || + !binding->Set(context, tns::ToV8String(isolate, native.first), function).FromMaybe(false)) { + return MaybeLocal(); + } + } + return binding; +} + +} // namespace v8_inspector diff --git a/NativeScript/inspector/InspectorSessions.h b/NativeScript/inspector/InspectorSessions.h index 1088fc0d3..5545ffd65 100644 --- a/NativeScript/inspector/InspectorSessions.h +++ b/NativeScript/inspector/InspectorSessions.h @@ -55,6 +55,9 @@ class InspectorSessions { bool Has(uint64_t connectionId) const; + // The frontend's session, or null once it is gone or closing. + V8InspectorSession* Find(uint64_t connectionId) const; + private: class Channel; struct Session { diff --git a/NativeScript/inspector/InspectorSessions.mm b/NativeScript/inspector/InspectorSessions.mm index a2a45af6c..e51628161 100644 --- a/NativeScript/inspector/InspectorSessions.mm +++ b/NativeScript/inspector/InspectorSessions.mm @@ -225,6 +225,11 @@ void flushProtocolNotifications() override {} return it != sessions_.end() && !it->second->closing; } +V8InspectorSession* InspectorSessions::Find(uint64_t connectionId) const { + auto it = sessions_.find(connectionId); + return it != sessions_.end() && !it->second->closing ? it->second->session.get() : nullptr; +} + void InspectorSessions::Destroy(uint64_t connectionId) { auto node = sessions_.extract(connectionId); if (node.empty()) { diff --git a/NativeScript/inspector/JsV8InspectorClient.h b/NativeScript/inspector/JsV8InspectorClient.h index dd1c2dd0f..c42c76f2b 100644 --- a/NativeScript/inspector/JsV8InspectorClient.h +++ b/NativeScript/inspector/JsV8InspectorClient.h @@ -67,6 +67,28 @@ class JsV8InspectorClient : V8InspectorClient { void registerModules(); + // For ns:inspector (InspectorModule.mm). All need the isolate's Locker. + // The client debugging `isolate`, which only the main isolate has. + static JsV8InspectorClient* ForIsolate(v8::Isolate* isolate); + // Receives the commands of the domains JS registers, and the departures of + // frontends: dispatch(connectionId, id, domain, command, params) returns + // whether it handled the command; closed(connectionId). + void SetJsDomainRouter(v8::Local router); + // Whether V8 or the runtime implements the domain. Needs no client. + static bool IsRuntimeDomain(const std::string& name); + // Fills `enabledBefore` with the frontends that enabled the domain while + // nothing handled it. False, with `error` set, for a domain V8 or the + // runtime implements, or one already registered. + bool RegisterJsDomain(const std::string& name, std::vector& enabledBefore, + std::string& error); + // `enabled`: frontends that still have it enabled, for a later + // registration of the name. + void UnregisterJsDomain(const std::string& name, const std::vector& enabled); + std::vector Connections(); + // Null once the frontend is gone or leaving. + V8InspectorSession* SessionFor(uint64_t connectionId); + V8Inspector* Inspector() { return inspector_.get(); } + void consoleLog(v8::Isolate* isolate, ConsoleAPIType method, const std::vector>& args); @@ -133,6 +155,17 @@ class JsV8InspectorClient : V8InspectorClient { nlohmann::json id; }; std::map pendingJsReplies_; + + // ns:inspector state; needs the isolate's Locker. + v8::Global jsDomainRouter_; + std::set jsDomains_; + // Frontends that sent .enable for a domain nothing handled yet. + std::map> rememberedEnables_; + // Whether the JS domain router handled the command. + bool DispatchToJsDomain(uint64_t connectionId, v8::Local context, + v8::Local message, const std::string& domain, + const std::string& command); + void NotifyJsDomainsClosed(uint64_t connectionId); int64_t lastJsRequestId_ = 0; // The process-global trace controller serves one frontend at a time. diff --git a/NativeScript/inspector/JsV8InspectorClient.mm b/NativeScript/inspector/JsV8InspectorClient.mm index 82743339b..2b0c558ad 100644 --- a/NativeScript/inspector/JsV8InspectorClient.mm +++ b/NativeScript/inspector/JsV8InspectorClient.mm @@ -672,6 +672,10 @@ bool GetInt32(const json& value, long long& out) { for (auto& entry : this->jsDomainEnablers_) { entry.second.erase(item.connectionId); } + for (auto& entry : this->rememberedEnables_) { + entry.second.erase(item.connectionId); + } + this->NotifyJsDomainsClosed(item.connectionId); for (auto it = this->pendingJsReplies_.begin(); it != this->pendingJsReplies_.end();) { it = it->second.connectionId == item.connectionId ? this->pendingJsReplies_.erase(it) : std::next(it); @@ -904,16 +908,24 @@ bool GetInt32(const json& value, long long& out) { return; } + size_t dot = method.find('.'); + std::string domain = method.substr(0, dot); + std::string command = dot == std::string::npos ? std::string() : method.substr(dot + 1); + + // Domains registered through ns:inspector win over __registerDomainDispatcher. + bool jsDomain = this->jsDomains_.count(domain) != 0 && arg->IsObject(); + if (jsDomain && this->DispatchToJsDomain(connectionId, context, arg.As(), domain, + command)) { + return; + } + // Pass incoming message to a registerd domain handler if any - if (!arg.IsEmpty() && arg->IsObject()) { + if (!jsDomain && !arg.IsEmpty() && arg->IsObject()) { Local domainDebugger; Local argObject = arg.As(); Local domainMethodFunc = v8_inspector::GetDebuggerFunctionFromObject(context, argObject, domainDebugger); - size_t dot = method.find('.'); - std::string domain = method.substr(0, dot); - std::string command = dot == std::string::npos ? std::string() : method.substr(dot + 1); bool hasHandler = !domainMethodFunc.IsEmpty() && domainMethodFunc->IsFunction(); if (hasHandler && command == "disable") { @@ -986,6 +998,12 @@ bool GetInt32(const json& value, long long& out) { } } + // A domain JS registers later is told about this frontend then. + if (command == "enable" && !jsDomain && + !V8InspectorSession::canDispatchMethod(Make8BitStringView(method))) { + this->rememberedEnables_[domain].insert(connectionId); + } + // if no handler handled the message successfully, fall-through to the default V8 implementation sessions_->Dispatch(connectionId, method, message); @@ -1001,6 +1019,145 @@ bool GetInt32(const json& value, long long& out) { } } +JsV8InspectorClient* JsV8InspectorClient::ForIsolate(Isolate* isolate) { + JsV8InspectorClient* client = instance_; + return client != nullptr && client->isolateWrapper_.BelongsTo(isolate) ? client : nullptr; +} + +void JsV8InspectorClient::SetJsDomainRouter(Local router) { + this->jsDomainRouter_.Reset(isolate_, router); +} + +bool JsV8InspectorClient::IsRuntimeDomain(const std::string& name) { + // The runtime answers these before any JS domain is asked. + static const char* kNativeDomains[] = {"IO", "Target", "Tracing"}; + bool native = std::any_of(std::begin(kNativeDomains), std::end(kNativeDomains), + [&](const char* domain) { return name == domain; }); + return native || V8InspectorSession::canDispatchMethod(Make8BitStringView(name + ".enable")); +} + +bool JsV8InspectorClient::RegisterJsDomain(const std::string& name, + std::vector& enabledBefore, + std::string& error) { + if (IsRuntimeDomain(name)) { + error = "The " + name + " domain is implemented by the runtime"; + return false; + } + if (!this->jsDomains_.insert(name).second) { + error = "The " + name + " domain is already registered"; + return false; + } + + std::set enabled; + auto remembered = this->rememberedEnables_.find(name); + if (remembered != this->rememberedEnables_.end()) { + enabled = std::move(remembered->second); + this->rememberedEnables_.erase(remembered); + } + auto legacy = this->jsDomainEnablers_.find(name); + if (legacy != this->jsDomainEnablers_.end()) { + for (const auto& entry : legacy->second) { + if (entry.second) { + enabled.insert(entry.first); + } + } + } + for (uint64_t connectionId : enabled) { + if (sessions_->Has(connectionId)) { + enabledBefore.push_back(connectionId); + } + } + return true; +} + +void JsV8InspectorClient::UnregisterJsDomain(const std::string& name, + const std::vector& enabled) { + if (this->jsDomains_.erase(name) == 0) { + return; + } + for (uint64_t connectionId : enabled) { + if (sessions_->Has(connectionId)) { + this->rememberedEnables_[name].insert(connectionId); + } + } +} + +std::vector JsV8InspectorClient::Connections() { + std::vector connections; + std::lock_guard lock(this->frontendsMutex_); + for (const auto& entry : this->frontends_) { + if (sessions_->Has(entry.first)) { + connections.push_back(entry.first); + } + } + return connections; +} + +V8InspectorSession* JsV8InspectorClient::SessionFor(uint64_t connectionId) { + return sessions_->Find(connectionId); +} + +bool JsV8InspectorClient::DispatchToJsDomain(uint64_t connectionId, Local context, + Local message, const std::string& domain, + const std::string& command) { + if (this->jsDomainRouter_.IsEmpty()) { + return false; + } + Isolate* isolate = isolate_; + Local router = this->jsDomainRouter_.Get(isolate); + Local dispatch; + Local id; + Local params; + if (!router->Get(context, tns::ToV8String(isolate, "dispatch")).ToLocal(&dispatch) || + !dispatch->IsFunction() || + !message->Get(context, tns::ToV8String(isolate, "id")).ToLocal(&id) || + !message->Get(context, tns::ToV8String(isolate, "params")).ToLocal(¶ms)) { + return false; + } + + Local args[] = {Number::New(isolate, static_cast(connectionId)), id, + tns::ToV8String(isolate, domain), tns::ToV8String(isolate, command), + params}; + TryCatch tc(isolate); + Local handled; + bool called = dispatch.As()->Call(context, router, 5, args).ToLocal(&handled); + if (tc.HasCaught() && !tc.HasTerminated()) { + tns::LogError(isolate, tc); + } + // An async handler answers from a microtask. Not while paused: that would + // also run the app's own promise callbacks in the middle of paused JS. + if (!runningPauseLoop_) { + isolate->PerformMicrotaskCheckpoint(); + } + return !called || handled->BooleanValue(isolate); +} + +void JsV8InspectorClient::NotifyJsDomainsClosed(uint64_t connectionId) { + if (this->jsDomainRouter_.IsEmpty()) { + return; + } + Isolate* isolate = isolate_; + Isolate::Scope isolate_scope(isolate); + HandleScope handle_scope(isolate); + Local context = tns::Caches::Get(isolate)->GetContext(); + Context::Scope context_scope(context); + Local router = this->jsDomainRouter_.Get(isolate); + Local closed; + if (!router->Get(context, tns::ToV8String(isolate, "closed")).ToLocal(&closed) || + !closed->IsFunction()) { + return; + } + Local args[] = {Number::New(isolate, static_cast(connectionId))}; + TryCatch tc(isolate); + std::ignore = closed.As()->Call(context, router, 1, args); + if (tc.HasCaught() && !tc.HasTerminated()) { + tns::LogError(isolate, tc); + } + if (!runningPauseLoop_) { + isolate->PerformMicrotaskCheckpoint(); + } +} + void JsV8InspectorClient::HandleLoadNetworkResource(uint64_t connectionId, int msgId, const std::string& url, const std::string& sessionId) { diff --git a/NativeScript/runtime/NsBuiltinModules.cpp b/NativeScript/runtime/NsBuiltinModules.cpp index c55e859bf..b1f01f6f2 100644 --- a/NativeScript/runtime/NsBuiltinModules.cpp +++ b/NativeScript/runtime/NsBuiltinModules.cpp @@ -18,6 +18,7 @@ #include "URLSearchParamsImpl.h" #include "Worker.h" #include "WrapperLifetime.h" +#include "inspector/InspectorModule.h" using namespace v8; @@ -53,6 +54,7 @@ struct Registration { // distinct and the standard module never carries compatibility code. constexpr Registration kRegistry[] = { {"ns:interop", BuiltinId::kNsInterop, Interop::NsInteropBinding}, + {"ns:inspector", BuiltinId::kNsInspector, v8_inspector::NsInspectorBinding}, {"ns:interop/ios", BuiltinId::kNsInteropIos, Interop::NsInteropIosBinding}, {"ns:module", BuiltinId::kNsModule, NsModuleBinding}, {"ns:runtime", BuiltinId::kNsRuntime, NsRuntimeBinding}, diff --git a/NativeScript/runtime/js/ns-inspector.js b/NativeScript/runtime/js/ns-inspector.js new file mode 100644 index 000000000..1353e1539 --- /dev/null +++ b/NativeScript/runtime/js/ns-inspector.js @@ -0,0 +1,533 @@ +"use strict"; + +// The `ns:inspector` builtin module: JS domains for the inspector protocol. +// A domain registered here gets every command its name prefixes, from any +// connected frontend; the runtime keeps who enabled it, answers each frontend +// under its own ids, and tells the domain when a frontend leaves. See +// docs/ns-builtin-modules.md for the contract. +// +// The native side (inspector/InspectorModule.mm) routes commands here through +// the router passed to `attach`, and is the only way out to a frontend. It is +// inert in release builds and in workers, where `available` is false. + +const { + available, + attach, + checkDomain, + register, + unregister, + connections, + send, + wrapObject, + unwrapObject, + releaseObjectGroup, + addInspectedObject, + captureStackTrace, + monotonicTime, + wallTime, + logError, +} = binding; +const { + Error, + Map, + Set, + TypeError, + ArrayPrototypePush, + ArrayPrototypeSlice, + ArrayPrototypeSplice, + FunctionPrototypeApply, + FunctionPrototypeCall, + JSONStringify, + MapPrototypeDelete, + MapPrototypeGet, + MapPrototypeSet, + NumberIsInteger, + ObjectCreate, + ObjectDefineProperty, + ObjectFreeze, + ObjectPrototypeHasOwnProperty, + PromisePrototypeThen, + PromiseResolve, + RegExpPrototypeTest, + SetIteratorPrototypeNext, + SetPrototypeAdd, + SetPrototypeDelete, + SetPrototypeHas, + SetPrototypeValues, +} = primordials; + +const kDomainName = /^[A-Z][A-Za-z0-9]*$/; +const kHooks = ["enabled", "disabled", "sessionEnabled", "sessionDisabled", "sessionClosed"]; +const kServerError = -32000; + +class ProtocolError extends Error { + constructor(code, message) { + if (!NumberIsInteger(code)) { + throw new TypeError("ProtocolError code must be an integer"); + } + super(message); + this.code = code; + } +} +ObjectDefineProperty(ProtocolError.prototype, "name", { + value: "ProtocolError", + writable: true, + configurable: true, +}); + +function setValues(set) { + const values = []; + const iterator = SetPrototypeValues(set); + for (;;) { + const entry = SetIteratorPrototypeNext(iterator); + if (entry.done) { + return values; + } + ArrayPrototypePush(values, entry.value); + } +} + +function isThenable(value) { + return value !== null && (typeof value === "object" || typeof value === "function") && + typeof value.then === "function"; +} + +function report(error) { + try { + logError(error instanceof Error && typeof error.stack === "string" ? error.stack : `${error}`); + } catch { + // Reporting must not break the protocol bookkeeping around it. + } +} + +// Every hook is user code that may throw, or pause, during which the +// frontend may leave or another may change the domain: callers record their +// state before calling and check it again after. +function callHook(owner, name, ...args) { + const hook = owner[name]; + if (typeof hook !== "function") { + return undefined; + } + try { + return FunctionPrototypeApply(hook, owner, args); + } catch (error) { + report(error); + return undefined; + } +} + +// connectionId -> Session, for frontends that reached a JS domain. +const sessions = new Map(); +// name -> Domain +const domains = new Map(); + +class Session { + #connectionId; + #closed = false; + + constructor(connectionId) { + this.#connectionId = connectionId; + } + + get closed() { + return this.#closed; + } + + emit(method, params) { + if (typeof method !== "string") { + throw new TypeError("emit expects a method name"); + } + if (this.#closed) { + return; + } + send(this.#connectionId, JSONStringify({ method, params: params === undefined ? {} : params })); + } + + wrapObject(value, options) { + const objectGroup = options !== undefined && options !== null ? options.objectGroup : undefined; + const generatePreview = options !== undefined && options !== null && !!options.generatePreview; + this.#ensureOpen(); + return wrapObject(this.#connectionId, value, + typeof objectGroup === "string" ? objectGroup : "", generatePreview); + } + + unwrapObject(objectId) { + if (typeof objectId !== "string") { + throw new TypeError("unwrapObject expects an object id"); + } + this.#ensureOpen(); + try { + return unwrapObject(this.#connectionId, objectId); + } catch (error) { + throw new ProtocolError(kServerError, error instanceof Error ? error.message : `${error}`); + } + } + + releaseObjectGroup(objectGroup) { + if (typeof objectGroup !== "string") { + throw new TypeError("releaseObjectGroup expects a group name"); + } + if (!this.#closed) { + releaseObjectGroup(this.#connectionId, objectGroup); + } + } + + addInspectedObject(get) { + if (typeof get !== "function") { + throw new TypeError("addInspectedObject expects a function"); + } + this.#ensureOpen(); + addInspectedObject(this.#connectionId, get); + } + + // Called by the router only. + static close(session) { + session.#closed = true; + } + + static connectionId(session) { + return session.#connectionId; + } + + #ensureOpen() { + if (this.#closed) { + throw new Error("The session is closed"); + } + } +} + +function sessionFor(connectionId) { + let session = MapPrototypeGet(sessions, connectionId); + if (session === undefined) { + session = new Session(connectionId); + MapPrototypeSet(sessions, connectionId, session); + } + return session; +} + +function reply(session, id, result) { + if (session.closed) { + return; + } + send(Session.connectionId(session), + JSONStringify({ id, result: result === undefined || result === null ? {} : result })); +} + +function replyError(session, id, error) { + if (session.closed) { + return; + } + const isProtocolError = error instanceof ProtocolError; + if (!isProtocolError) { + report(error); + } + const message = error instanceof Error ? error.message : `${error}`; + send(Session.connectionId(session), JSONStringify({ + id, + error: { code: isProtocolError ? error.code : kServerError, message: message || "Internal error" }, + })); +} + +// Answers once `value` settles, when it is a promise. +function whenSettled(value, onResult, onError) { + if (!isThenable(value)) { + onResult(value); + return; + } + PromisePrototypeThen(PromiseResolve(value), onResult, onError); +} + +class Domain { + #name; + #options; + #alwaysEnabled; + #registered = true; + // Sessions with the domain enabled, and those that enabled it or sent it a + // command, which get sessionClosed. + #enabled = new Set(); + #enabledCount = 0; + #touched = new Set(); + + constructor(name, options, alwaysEnabled) { + this.#name = name; + this.#options = options; + this.#alwaysEnabled = alwaysEnabled; + } + + get name() { + return this.#name; + } + + get enabled() { + if (!this.#registered) { + return false; + } + return this.#alwaysEnabled ? connections().length > 0 : this.#enabledCount > 0; + } + + emit(event, params) { + if (typeof event !== "string") { + throw new TypeError("emit expects an event name"); + } + if (!this.#registered) { + return; + } + const message = JSONStringify({ + method: `${this.#name}.${event}`, + params: params === undefined ? {} : params, + }); + if (this.#alwaysEnabled) { + const ids = connections(); + for (let i = 0; i < ids.length; i++) { + send(ids[i], message); + } + return; + } + const enabled = setValues(this.#enabled); + for (let i = 0; i < enabled.length; i++) { + if (!enabled[i].closed) { + send(Session.connectionId(enabled[i]), message); + } + } + } + + unregister() { + if (!this.#registered) { + return; + } + this.#registered = false; + MapPrototypeDelete(domains, this.#name); + // A later registration of the name finds them enabled again. + const enabled = setValues(this.#enabled); + const stillEnabled = []; + for (let i = 0; i < enabled.length; i++) { + if (!enabled[i].closed) { + ArrayPrototypePush(stillEnabled, Session.connectionId(enabled[i])); + } + } + unregister(this.#name, stillEnabled); + } + + // The router's side. + + static dispatch(domain, session, id, command, params) { + return domain.#dispatch(session, id, command, params); + } + + static enableWithoutReply(domain, session) { + domain.#enable(session, undefined, () => {}); + } + + static close(domain, session) { + domain.#close(session); + } + + #dispatch(session, id, command, params) { + if (command === "enable") { + SetPrototypeAdd(this.#touched, session); + if (this.#alwaysEnabled) { + reply(session, id); + } else { + this.#enable(session, params, () => reply(session, id)); + } + return true; + } + if (command === "disable") { + if (!this.#alwaysEnabled) { + this.#disable(session); + } + reply(session, id); + return true; + } + + const commands = this.#options.commands; + if (commands === undefined || commands === null || + !ObjectPrototypeHasOwnProperty(commands, command) || typeof commands[command] !== "function") { + return false; + } + SetPrototypeAdd(this.#touched, session); + let result; + try { + result = FunctionPrototypeCall(commands[command], commands, + params === undefined ? {} : params, session); + } catch (error) { + replyError(session, id, error); + return true; + } + whenSettled(result, (value) => reply(session, id, value), (error) => replyError(session, id, error)); + return true; + } + + #enable(session, params, done) { + if (SetPrototypeHas(this.#enabled, session)) { + done(); + return; + } + const first = this.#enabledCount === 0; + SetPrototypeAdd(this.#enabled, session); + this.#enabledCount++; + SetPrototypeAdd(this.#touched, session); + if (first) { + callHook(this.#options, "enabled"); + } + // The client may have left, or disabled it again, while `enabled` ran. + if (session.closed || !SetPrototypeHas(this.#enabled, session)) { + done(); + return; + } + const result = callHook(this.#options, "sessionEnabled", session, params === undefined ? {} : params); + whenSettled(result, done, (error) => { + report(error); + done(); + }); + } + + #disable(session) { + if (!SetPrototypeDelete(this.#enabled, session)) { + return; + } + this.#enabledCount--; + callHook(this.#options, "sessionDisabled", session); + if (this.#enabledCount === 0) { + callHook(this.#options, "disabled"); + } + } + + #close(session) { + this.#disable(session); + if (SetPrototypeDelete(this.#touched, session)) { + callHook(this.#options, "sessionClosed", session); + } + } +} + +const router = ObjectFreeze({ + __proto__: null, + dispatch(connectionId, id, domainName, command, params) { + const domain = MapPrototypeGet(domains, domainName); + if (domain === undefined) { + return false; + } + return Domain.dispatch(domain, sessionFor(connectionId), id, command, params); + }, + closed(connectionId) { + const session = MapPrototypeGet(sessions, connectionId); + if (session === undefined) { + return; + } + Session.close(session); + MapPrototypeDelete(sessions, connectionId); + // A copy: a hook may register or unregister domains. + const names = ArrayPrototypeSlice(domainNames); + for (let i = 0; i < names.length; i++) { + const domain = MapPrototypeGet(domains, names[i]); + if (domain !== undefined) { + Domain.close(domain, session); + } + } + }, +}); + +// Registration order, for closing domains in a stable order. +const domainNames = []; + +function validateOptions(options) { + if (options === undefined) { + return ObjectCreate(null); + } + if (options === null || typeof options !== "object") { + throw new TypeError("registerDomain expects an options object"); + } + for (let i = 0; i < kHooks.length; i++) { + const hook = kHooks[i]; + if (options[hook] !== undefined && typeof options[hook] !== "function") { + throw new TypeError(`'${hook}' must be a function`); + } + } + const commands = options.commands; + if (commands !== undefined && (commands === null || typeof commands !== "object")) { + throw new TypeError("'commands' must be an object"); + } + if (options.alwaysEnabled !== undefined && typeof options.alwaysEnabled !== "boolean") { + throw new TypeError("'alwaysEnabled' must be a boolean"); + } + return options; +} + +// Release builds and workers: the same checks, and nothing to serve. +const inertNames = new Set(); + +class InertDomain { + #name; + #registered = true; + + constructor(name) { + this.#name = name; + } + + get name() { + return this.#name; + } + + get enabled() { + return false; + } + + emit(event) { + if (typeof event !== "string") { + throw new TypeError("emit expects an event name"); + } + } + + unregister() { + if (this.#registered) { + this.#registered = false; + SetPrototypeDelete(inertNames, this.#name); + } + } +} + +function registerDomain(name, options) { + if (typeof name !== "string" || !RegExpPrototypeTest(kDomainName, name)) { + throw new TypeError("registerDomain expects a domain name such as 'Network'"); + } + options = validateOptions(options); + if (!available) { + checkDomain(name); + if (SetPrototypeHas(inertNames, name)) { + throw new Error(`The ${name} domain is already registered`); + } + SetPrototypeAdd(inertNames, name); + return new InertDomain(name); + } + + // Throws for a domain the runtime implements, or one already registered. + const enabledBefore = register(name); + const domain = new Domain(name, options, options.alwaysEnabled === true); + MapPrototypeSet(domains, name, domain); + for (let i = 0; i < domainNames.length; i++) { + if (domainNames[i] === name) { + ArrayPrototypeSplice(domainNames, i, 1); + break; + } + } + ArrayPrototypePush(domainNames, name); + if (options.alwaysEnabled !== true) { + for (let i = 0; i < enabledBefore.length; i++) { + Domain.enableWithoutReply(domain, sessionFor(enabledBefore[i])); + } + } + return domain; +} + +if (available) { + attach(router); +} + +exports.registerDomain = registerDomain; +exports.ProtocolError = ProtocolError; +exports.monotonicTime = monotonicTime; +exports.wallTime = wallTime; +// Native, so that the trace starts at its caller. +exports.captureStackTrace = captureStackTrace; +ObjectFreeze(exports); diff --git a/TestRunner/app/tests/NsInspectorTests.js b/TestRunner/app/tests/NsInspectorTests.js new file mode 100644 index 000000000..310e6a1ca --- /dev/null +++ b/TestRunner/app/tests/NsInspectorTests.js @@ -0,0 +1,101 @@ +describe("ns:inspector", function () { + var nsInspector = require("ns:inspector"); + var registered = []; + + function register(name, options) { + var domain = nsInspector.registerDomain(name, options); + registered.push(domain); + return domain; + } + + afterEach(function () { + registered.forEach(function (domain) { + domain.unregister(); + }); + registered = []; + }); + + it("exposes frozen exports", function () { + expect(Object.isFrozen(nsInspector)).toBe(true); + }); + + // The export set is public API, declared in types/ns-inspector.d.ts and + // docs/ns-builtin-modules.md; all three must change together. + it("exposes exactly the declared surface", function () { + expect(Object.keys(nsInspector).sort()).toEqual( + ["ProtocolError", "captureStackTrace", "monotonicTime", "registerDomain", "wallTime"]); + }); + + it("is a singleton per realm", function () { + expect(require("ns:inspector")).toBe(nsInspector); + }); + + it("validates the domain name and options", function () { + expect(function () { nsInspector.registerDomain("lowercase"); }).toThrowError(TypeError); + expect(function () { nsInspector.registerDomain("Two words"); }).toThrowError(TypeError); + expect(function () { nsInspector.registerDomain("Valid", 5); }).toThrowError(TypeError); + expect(function () { nsInspector.registerDomain("Valid", { enabled: true }); }).toThrowError(TypeError); + expect(function () { nsInspector.registerDomain("Valid", { commands: 1 }); }).toThrowError(TypeError); + expect(function () { nsInspector.registerDomain("Valid", { alwaysEnabled: "yes" }); }).toThrowError(TypeError); + }); + + it("refuses the domains the runtime implements", function () { + ["Runtime", "Debugger", "Profiler", "HeapProfiler", "Target", "IO", "Tracing"].forEach(function (name) { + expect(function () { nsInspector.registerDomain(name); }).toThrowError(/implemented by the runtime/); + }); + }); + + it("allows one owner per domain until it unregisters", function () { + var domain = register("NsInspectorTestsOwner"); + expect(domain.name).toBe("NsInspectorTestsOwner"); + expect(function () { nsInspector.registerDomain("NsInspectorTestsOwner"); }).toThrowError(/already registered/); + domain.unregister(); + register("NsInspectorTestsOwner"); + }); + + it("is not enabled without a client, and emits nowhere", function () { + var domain = register("NsInspectorTestsQuiet", { commands: {} }); + expect(domain.enabled).toBe(false); + domain.emit("event", { a: 1 }); + expect(function () { domain.emit(5); }).toThrowError(TypeError); + }); + + it("builds protocol errors with a code", function () { + var error = new nsInspector.ProtocolError(-32602, "bad params"); + expect(error instanceof Error).toBe(true); + expect(error.name).toBe("ProtocolError"); + expect(error.code).toBe(-32602); + expect(error.message).toBe("bad params"); + expect(function () { return new nsInspector.ProtocolError("x", "y"); }).toThrowError(TypeError); + }); + + it("reads the clocks", function () { + var first = nsInspector.monotonicTime(); + var second = nsInspector.monotonicTime(); + expect(typeof first).toBe("number"); + expect(second >= first).toBe(true); + expect(Math.abs(nsInspector.wallTime() - Date.now() / 1000)).toBeLessThan(5); + }); + + it("captures the caller's stack when the inspector is available", function () { + var trace = nsInspector.captureStackTrace(); + if (trace !== undefined) { + expect(Array.isArray(trace.callFrames)).toBe(true); + expect(trace.callFrames.length).toBeGreaterThan(0); + } + }); + + it("is inert in a worker", function (done) { + var worker = new Worker("./nsInspectorWorker.js"); + worker.onmessage = function (event) { + expect(event.data).toEqual({ enabled: false, stack: "undefined", clock: "number" }); + worker.terminate(); + done(); + }; + worker.onerror = function (event) { + expect(String(event.message)).toBe(""); + worker.terminate(); + done(); + }; + }); +}); diff --git a/TestRunner/app/tests/index.js b/TestRunner/app/tests/index.js index 7be398e09..c8cb0b79e 100644 --- a/TestRunner/app/tests/index.js +++ b/TestRunner/app/tests/index.js @@ -135,6 +135,7 @@ require("./ProxyReceiverTests"); require("./InvalidReceiverTests"); require("./NsRuntimeTests"); require("./NsWorkerThreadsTests"); +require("./NsInspectorTests"); require("./NsUrlTests"); require("./NsInteropTests"); require("./GCFinalizerTests"); diff --git a/TestRunner/app/tests/nsInspectorWorker.js b/TestRunner/app/tests/nsInspectorWorker.js new file mode 100644 index 000000000..118e2dd9e --- /dev/null +++ b/TestRunner/app/tests/nsInspectorWorker.js @@ -0,0 +1,8 @@ +var nsInspector = require("ns:inspector"); +var domain = nsInspector.registerDomain("NsInspectorWorkerDomain", { commands: {} }); +domain.emit("event", {}); +postMessage({ + enabled: domain.enabled, + stack: typeof nsInspector.captureStackTrace(), + clock: typeof nsInspector.monotonicTime(), +}); diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 8aaf580ca..7aaa5dc1c 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -918,6 +918,86 @@ New code should import from the modules. also what first builds the three modules in a realm that has not required them. +### `ns:inspector` + +Inspector protocol domains implemented in JavaScript, served to every +connected client (DevTools windows, CDP scripts). **Experimental, iOS-only** +until the Android runtime ships it. + +| export | description | +|---|---| +| `registerDomain(name, options?)` | Handles every command `name.*` from every client and returns the domain. Throws a `TypeError` for a name that is not a capitalized identifier or for malformed options, and an `Error` for a domain the runtime implements (`Runtime`, `Debugger`, `Profiler`, `HeapProfiler`, `Console`, `Schema`, `Target`, `IO`, `Tracing`) or one already registered. | +| `ProtocolError` | `new ProtocolError(code, message)`: thrown or rejected by a command to answer with that protocol error code. | +| `monotonicTime()` | Seconds on the monotonic clock trace events use, sub-millisecond (`Network.MonotonicTime`). | +| `wallTime()` | Seconds since the epoch, fractional (`Network.TimeSinceEpoch`). | +| `captureStackTrace()` | The caller's stack as a `Runtime.StackTrace` (`Network.Initiator.stack`). | + +`options`: the hooks `enabled()`, `disabled()`, `sessionEnabled(session, +params)`, `sessionDisabled(session)`, `sessionClosed(session)`; `commands`, +an object of command handlers `(params, session) => result`; and +`alwaysEnabled`, for domains with no `enable` command. + +```js +import { registerDomain } from "ns:inspector"; + +const network = registerDomain("Network", { + sessionEnabled(session) { + // replay state to a client that enabled the domain + }, + commands: { + async getResponseBody({ requestId }, session) { + return { body: await bodyOf(requestId), base64Encoded: false }; + }, + }, +}); + +if (network.enabled) { + network.emit("requestWillBeSent", params); +} +``` + +Rules: + +- **The runtime owns `enable` and `disable`.** It answers them, keeps which + clients enabled the domain, and runs the hooks; handlers never receive them. + `enabled` runs for the first client and `disabled` after the last. + `domain.emit` reaches the clients that enabled the domain, or every client + for an `alwaysEnabled` one. +- **A client that enabled a domain before it was registered** (or while it + was unregistered) is enabled at registration: `enabled` and + `sessionEnabled` run then, with empty params. +- **Commands may be async.** The returned value, or what a returned promise + resolves to, answers the command; `undefined` answers `{}`. A throw or + rejection answers with an error whose code is the `ProtocolError`'s, or + -32000. A reply never reaches another client, and one for a client that + left is dropped. A command the handlers do not define goes to V8, which + does not know it. +- **Per client, messages go out in the order they are sent.** Events a + command emits precede its reply, and events `sessionEnabled` emits precede + the reply to `enable`, which waits for a promise `sessionEnabled` returns. +- **Disabling is not leaving.** `sessionClosed` runs once a client leaves, + for every client that enabled the domain or sent it a command, after + `sessionDisabled` if it had the domain enabled. Cleanup that must happen + belongs there. +- **Commands run while the app is paused.** A command that must work at a + breakpoint answers synchronously: promise callbacks, the handler's own + included, run only after the resume. +- **The `session` argument** stands for one client for as long as it is + connected: `closed`, `emit(method, params)`, and `wrapObject(value, + { objectGroup?, generatePreview? })`, `unwrapObject(objectId)`, + `releaseObjectGroup(objectGroup)` and `addInspectedObject(get)` for remote + objects. An object id belongs to the client it was made for, so wrapped + objects are never broadcast. `addInspectedObject` makes the getter's value + `$0` in that client's console. Once the client has left, `emit` does + nothing and the object methods throw. +- **Commands the runtime answers natively stay native**: + `Network.loadNetworkResource`, `IO.*`, `Tracing.*` and `Target.*` reach no + domain. +- A domain registered with `__registerDomainDispatcher` too is handled here. +- **In release builds and in workers** the module loads, `registerDomain` + returns an inert domain (`enabled` is false, `emit` does nothing), and + `captureStackTrace` returns `undefined`. + ### `node:` compatibility shims The same registry serves the `node:` scheme with **compatibility shims** so @@ -1316,7 +1396,7 @@ resolvers read the same table differently: - The **`ns:`/`node:` resolver** — the app-facing one, behind `require()`, `import` and `import()` — serves only rows *not* marked internal-only. An internal-only specifier fails exactly as a name absent from the table does. - Eleven rows are public today: `ns:interop`, `ns:interop/ios`, `ns:module`, + Twelve rows are public today: `ns:inspector`, `ns:interop`, `ns:interop/ios`, `ns:module`, `ns:runtime`, `ns:url`, `ns:util`, `ns:worker_threads`, `node:module`, `node:url`, `node:util`, `node:worker_threads`. `ns:interop/visionos` and `ns:interop/macos` are aliases, canonicalized to `ns:interop/ios` before any diff --git a/download_v8.sh b/download_v8.sh index 1418fba91..5bb5e2fed 100755 --- a/download_v8.sh +++ b/download_v8.sh @@ -67,7 +67,8 @@ fi # checkout looking up to date. installed() { [ -f "$STAMP" ] && [ "$(cat "$STAMP")" = "$RELEASE" ] \ - && [ -f "$NS_DIR/include/v8.h" ] && [ -d "$NS_DIR/inspector" ] + && [ -f "$NS_DIR/include/v8.h" ] \ + && [ -f "$NS_DIR/inspector/third_party/inspector_protocol/crdtp/json.h" ] } if [ "$FORCE" = "0" ] && installed; then diff --git a/tools/js2c-inputs.xcfilelist b/tools/js2c-inputs.xcfilelist index ca3913c1d..61957e156 100644 --- a/tools/js2c-inputs.xcfilelist +++ b/tools/js2c-inputs.xcfilelist @@ -17,6 +17,7 @@ $(SRCROOT)/NativeScript/runtime/js/node-module.js $(SRCROOT)/NativeScript/runtime/js/node-url.js $(SRCROOT)/NativeScript/runtime/js/node-util.js $(SRCROOT)/NativeScript/runtime/js/node-worker-threads.js +$(SRCROOT)/NativeScript/runtime/js/ns-inspector.js $(SRCROOT)/NativeScript/runtime/js/ns-interop.js $(SRCROOT)/NativeScript/runtime/js/ns-interop-ios.js $(SRCROOT)/NativeScript/runtime/js/ns-module.js diff --git a/tools/v8/vendor_inspector_sources.py b/tools/v8/vendor_inspector_sources.py index c831d7baa..ede6ca0e5 100644 --- a/tools/v8/vendor_inspector_sources.py +++ b/tools/v8/vendor_inspector_sources.py @@ -21,6 +21,7 @@ "src/inspector/v8-stack-trace-impl.h", "src/inspector/v8-console-message.h", "src/inspector/v8-inspector-session-impl.h", + "third_party/inspector_protocol/crdtp/json.h", ] INCLUDE_RE = re.compile(r'^\s*#\s*include\s*[<"]([^>"]+)[>"]', re.MULTILINE) diff --git a/types/index.d.ts b/types/index.d.ts index 0bef9864c..b0ddfd2a1 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -26,6 +26,7 @@ // in docs/ns-builtin-modules.md, not something to restate in types that would // then conflict. +/// /// /// /// diff --git a/types/ns-inspector.d.ts b/types/ns-inspector.d.ts new file mode 100644 index 000000000..fbaf0b046 --- /dev/null +++ b/types/ns-inspector.d.ts @@ -0,0 +1,97 @@ +declare module "ns:inspector" { + /** + * One connected inspector client (a DevTools window, a CDP script). The + * object stays the same for as long as the client is connected, so it can + * key a map. Once the client has left, `closed` is true, `emit` does + * nothing, and the object methods throw. + */ + export interface InspectorSession { + readonly closed: boolean; + /** Sends an event to this client only, e.g. `"Network.dataReceived"`. */ + emit(method: string, params?: object): void; + /** + * A `Runtime.RemoteObject` for `value`, valid for this client only: an + * object id names nothing, or something else, in another client. The + * value is held until the client releases `objectGroup`, releases the + * object, or leaves. + */ + wrapObject(value: unknown, options?: { objectGroup?: string; generatePreview?: boolean }): object; + /** The value behind one of this client's object ids. Throws a `ProtocolError` for an unknown id. */ + unwrapObject(objectId: string): unknown; + releaseObjectGroup(objectGroup: string): void; + /** + * Makes the getter's value `$0` in this client's console, and moves the + * previous ones to `$1`..`$4`. Called on every read; a getter that + * throws reads as `undefined`. + */ + addInspectedObject(get: () => unknown): void; + } + + /** + * The value or promise a command returns becomes its result; `undefined` + * becomes `{}`. A throw or rejection answers with an error: a + * `ProtocolError`'s code, -32000 otherwise. + */ + export type InspectorCommand = (params: any, session: InspectorSession) => unknown; + + export interface DomainOptions { + /** The first client enabled the domain. */ + enabled?(): void; + /** The last client disabled it, or left. */ + disabled?(): void; + /** + * This client enabled it. Events sent from here reach the client before + * the reply to its `enable`, which waits for a returned promise. + */ + sessionEnabled?(session: InspectorSession, params: any): unknown; + /** This client disabled it, or left. It may enable it again. */ + sessionDisabled?(session: InspectorSession): void; + /** + * This client left, having enabled the domain or sent it a command: drop + * everything kept for it. + */ + sessionClosed?(session: InspectorSession): void; + /** By command name, without the domain: `{ getResponseBody(params, session) {} }`. */ + commands?: Record; + /** + * For domains without `enable` (`Input`, `Emulation`): events reach every + * client, and `enable`/`disable` are only acknowledged. + */ + alwaysEnabled?: boolean; + } + + export interface InspectorDomain { + readonly name: string; + /** Whether any client has it enabled. Always false in release builds and workers. */ + readonly enabled: boolean; + /** Sends `.` to every client that enabled the domain. */ + emit(event: string, params?: object): void; + /** Stops handling the domain; a later registration of the name takes over. */ + unregister(): void; + } + + /** + * Handles the commands of `name` from every connected client. Throws for + * a domain the runtime implements (`Runtime`, `Debugger`, `Target`, ...) and + * for one already registered. In release builds and in workers the domain + * is inert: `enabled` is false and `emit` does nothing. + */ + export function registerDomain(name: string, options?: DomainOptions): InspectorDomain; + + /** An error a command can throw to answer with a chosen protocol error code. */ + export class ProtocolError extends Error { + constructor(code: number, message: string); + readonly code: number; + } + + /** `Network.MonotonicTime`: seconds on the clock trace events use, sub-millisecond. */ + export function monotonicTime(): number; + /** `Network.TimeSinceEpoch`: seconds since the epoch, fractional. */ + export function wallTime(): number; + /** + * A `Runtime.StackTrace` of the caller's stack, for `Network.Initiator`. + * Script ids belong to the isolate, so it can go to every client. + * `undefined` in release builds and workers. + */ + export function captureStackTrace(): object | undefined; +} diff --git a/v8ios.xcodeproj/project.pbxproj b/v8ios.xcodeproj/project.pbxproj index 13721fbf5..cee09bfbd 100644 --- a/v8ios.xcodeproj/project.pbxproj +++ b/v8ios.xcodeproj/project.pbxproj @@ -350,8 +350,10 @@ A1B2C3D40000000000000004 /* WorkerInspectorClient.mm in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000002 /* WorkerInspectorClient.mm */; }; A1B2C3D40000000000000007 /* InspectorSessions.h in Headers */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000005 /* InspectorSessions.h */; }; A1B2C3D4000000000000000B /* InspectorQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000009 /* InspectorQueue.h */; }; + A1B2C3D4000000000000000F /* InspectorModule.h in Headers */ = {isa = PBXBuildFile; fileRef = A1B2C3D4000000000000000D /* InspectorModule.h */; }; A1B2C3D40000000000000008 /* InspectorSessions.mm in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000006 /* InspectorSessions.mm */; }; A1B2C3D4000000000000000C /* InspectorQueue.mm in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4000000000000000A /* InspectorQueue.mm */; }; + A1B2C3D40000000000000010 /* InspectorModule.mm in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4000000000000000E /* InspectorModule.mm */; }; F6191AB129C0FCE8003F588F /* InspectorServer.h in Headers */ = {isa = PBXBuildFile; fileRef = F6191AA929C0FCE7003F588F /* InspectorServer.h */; }; F6191AB229C0FCE8003F588F /* InspectorServer.mm in Sources */ = {isa = PBXBuildFile; fileRef = F6191AAA29C0FCE7003F588F /* InspectorServer.mm */; settings = {COMPILER_FLAGS = "-fobjc-arc"; }; }; F6191AB629C0FF87003F588F /* utils.h in Headers */ = {isa = PBXBuildFile; fileRef = F6191AB429C0FF86003F588F /* utils.h */; }; @@ -912,8 +914,10 @@ A1B2C3D40000000000000002 /* WorkerInspectorClient.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WorkerInspectorClient.mm; sourceTree = ""; }; A1B2C3D40000000000000005 /* InspectorSessions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InspectorSessions.h; sourceTree = ""; }; A1B2C3D40000000000000009 /* InspectorQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InspectorQueue.h; sourceTree = ""; }; + A1B2C3D4000000000000000D /* InspectorModule.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InspectorModule.h; sourceTree = ""; }; A1B2C3D40000000000000006 /* InspectorSessions.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = InspectorSessions.mm; sourceTree = ""; }; A1B2C3D4000000000000000A /* InspectorQueue.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = InspectorQueue.mm; sourceTree = ""; }; + A1B2C3D4000000000000000E /* InspectorModule.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = InspectorModule.mm; sourceTree = ""; }; F6191AA929C0FCE7003F588F /* InspectorServer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InspectorServer.h; sourceTree = ""; }; F6191AAA29C0FCE7003F588F /* InspectorServer.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = InspectorServer.mm; sourceTree = ""; }; F6191AB429C0FF86003F588F /* utils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = utils.h; sourceTree = ""; }; @@ -1708,8 +1712,10 @@ A1B2C3D40000000000000002 /* WorkerInspectorClient.mm */, A1B2C3D40000000000000005 /* InspectorSessions.h */, A1B2C3D40000000000000009 /* InspectorQueue.h */, + A1B2C3D4000000000000000D /* InspectorModule.h */, A1B2C3D40000000000000006 /* InspectorSessions.mm */, A1B2C3D4000000000000000A /* InspectorQueue.mm */, + A1B2C3D4000000000000000E /* InspectorModule.mm */, F6191AA929C0FCE7003F588F /* InspectorServer.h */, F6191AAA29C0FCE7003F588F /* InspectorServer.mm */, 91B25A0829DAC83D00E3CE04 /* ns-v8-tracing-agent-impl.mm */, @@ -1764,6 +1770,7 @@ A1B2C3D40000000000000003 /* WorkerInspectorClient.h in Headers */, A1B2C3D40000000000000007 /* InspectorSessions.h in Headers */, A1B2C3D4000000000000000B /* InspectorQueue.h in Headers */, + A1B2C3D4000000000000000F /* InspectorModule.h in Headers */, 6573B9D0291FE29F00B0ED7C /* JSIV8ValueConverter.h in Headers */, C20AB5E726E1015300E2B41D /* OneByteStringResource.h in Headers */, C2DDEBAC229EAC8300345BFE /* ObjectManager.h in Headers */, @@ -2514,6 +2521,7 @@ A1B2C3D40000000000000004 /* WorkerInspectorClient.mm in Sources */, A1B2C3D40000000000000008 /* InspectorSessions.mm in Sources */, A1B2C3D4000000000000000C /* InspectorQueue.mm in Sources */, + A1B2C3D40000000000000010 /* InspectorModule.mm in Sources */, C2DDEB9C229EAC8300345BFE /* ClassBuilder.cpp in Sources */, C266569322AFFF7E00EE15CC /* Pointer.cpp in Sources */, F1CB51832D5C37100042555E /* URLPatternImpl.cpp in Sources */, From 152231cc064848e5e13557d9b4cb0b3f18ac951c Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 1 Dec 2026 23:59:26 -0300 Subject: [PATCH 02/11] fix(inspector): ns:inspector review findings - A client that enabled a domain and disabled it again before it was registered is no longer enabled at registration. - Enables recorded by __registerDomainDispatcher move to the first registerDomain of the name, instead of coming back at every registration. - A result JSON cannot serialize answers with an error instead of no reply. - A hook getter that throws no longer stops the other domains' cleanup when a client leaves, and validation reads each hook once. - releaseObjectGroup throws once the client has left, like the other object methods. - An unregistered domain still gets sessionDisabled and sessionClosed for its clients. - A repeated enable waits for a pending sessionEnabled before its reply. --- NativeScript/inspector/JsV8InspectorClient.mm | 11 ++- NativeScript/runtime/js/ns-inspector.js | 73 +++++++++++++++---- 2 files changed, 68 insertions(+), 16 deletions(-) diff --git a/NativeScript/inspector/JsV8InspectorClient.mm b/NativeScript/inspector/JsV8InspectorClient.mm index 2b0c558ad..024e41536 100644 --- a/NativeScript/inspector/JsV8InspectorClient.mm +++ b/NativeScript/inspector/JsV8InspectorClient.mm @@ -999,9 +999,13 @@ bool GetInt32(const json& value, long long& out) { } // A domain JS registers later is told about this frontend then. - if (command == "enable" && !jsDomain && + if (!jsDomain && (command == "enable" || command == "disable") && !V8InspectorSession::canDispatchMethod(Make8BitStringView(method))) { - this->rememberedEnables_[domain].insert(connectionId); + if (command == "enable") { + this->rememberedEnables_[domain].insert(connectionId); + } else { + this->rememberedEnables_[domain].erase(connectionId); + } } // if no handler handled the message successfully, fall-through to the default V8 implementation @@ -1054,6 +1058,8 @@ bool GetInt32(const json& value, long long& out) { enabled = std::move(remembered->second); this->rememberedEnables_.erase(remembered); } + // From here the JS domain keeps them; a later registration of the name + // gets them from UnregisterJsDomain. auto legacy = this->jsDomainEnablers_.find(name); if (legacy != this->jsDomainEnablers_.end()) { for (const auto& entry : legacy->second) { @@ -1061,6 +1067,7 @@ bool GetInt32(const json& value, long long& out) { enabled.insert(entry.first); } } + this->jsDomainEnablers_.erase(legacy); } for (uint64_t connectionId : enabled) { if (sessions_->Has(connectionId)) { diff --git a/NativeScript/runtime/js/ns-inspector.js b/NativeScript/runtime/js/ns-inspector.js index 1353e1539..7c74bda7f 100644 --- a/NativeScript/runtime/js/ns-inspector.js +++ b/NativeScript/runtime/js/ns-inspector.js @@ -104,11 +104,11 @@ function report(error) { // frontend may leave or another may change the domain: callers record their // state before calling and check it again after. function callHook(owner, name, ...args) { - const hook = owner[name]; - if (typeof hook !== "function") { - return undefined; - } try { + const hook = owner[name]; + if (typeof hook !== "function") { + return undefined; + } return FunctionPrototypeApply(hook, owner, args); } catch (error) { report(error); @@ -167,9 +167,8 @@ class Session { if (typeof objectGroup !== "string") { throw new TypeError("releaseObjectGroup expects a group name"); } - if (!this.#closed) { - releaseObjectGroup(this.#connectionId, objectGroup); - } + this.#ensureOpen(); + releaseObjectGroup(this.#connectionId, objectGroup); } addInspectedObject(get) { @@ -209,8 +208,14 @@ function reply(session, id, result) { if (session.closed) { return; } - send(Session.connectionId(session), - JSONStringify({ id, result: result === undefined || result === null ? {} : result })); + let message; + try { + message = JSONStringify({ id, result: result === undefined || result === null ? {} : result }); + } catch (error) { + replyError(session, id, error); + return; + } + send(Session.connectionId(session), message); } function replyError(session, id, error) { @@ -247,6 +252,9 @@ class Domain { #enabled = new Set(); #enabledCount = 0; #touched = new Set(); + // Sessions whose sessionEnabled has not settled, with the replies to + // repeated enables that wait for it. + #initializing = new Map(); constructor(name, options, alwaysEnabled) { this.#name = name; @@ -297,6 +305,10 @@ class Domain { } this.#registered = false; MapPrototypeDelete(domains, this.#name); + // Its clients still get sessionClosed when they leave. + if (setValues(this.#touched).length !== 0) { + ArrayPrototypePush(retired, this); + } // A later registration of the name finds them enabled again. const enabled = setValues(this.#enabled); const stillEnabled = []; @@ -322,6 +334,10 @@ class Domain { domain.#close(session); } + static isDone(domain) { + return setValues(domain.#touched).length === 0; + } + #dispatch(session, id, command, params) { if (command === "enable") { SetPrototypeAdd(this.#touched, session); @@ -360,7 +376,12 @@ class Domain { #enable(session, params, done) { if (SetPrototypeHas(this.#enabled, session)) { - done(); + const waiting = MapPrototypeGet(this.#initializing, session); + if (waiting !== undefined) { + ArrayPrototypePush(waiting, done); + } else { + done(); + } return; } const first = this.#enabledCount === 0; @@ -376,9 +397,21 @@ class Domain { return; } const result = callHook(this.#options, "sessionEnabled", session, params === undefined ? {} : params); - whenSettled(result, done, (error) => { - report(error); + if (!isThenable(result)) { done(); + return; + } + const waiting = [done]; + MapPrototypeSet(this.#initializing, session, waiting); + const settled = () => { + MapPrototypeDelete(this.#initializing, session); + for (let i = 0; i < waiting.length; i++) { + waiting[i](); + } + }; + whenSettled(result, settled, (error) => { + report(error); + settled(); }); } @@ -417,7 +450,7 @@ const router = ObjectFreeze({ } Session.close(session); MapPrototypeDelete(sessions, connectionId); - // A copy: a hook may register or unregister domains. + // Copies: a hook may register or unregister domains. const names = ArrayPrototypeSlice(domainNames); for (let i = 0; i < names.length; i++) { const domain = MapPrototypeGet(domains, names[i]); @@ -425,11 +458,22 @@ const router = ObjectFreeze({ Domain.close(domain, session); } } + const retiredNow = ArrayPrototypeSlice(retired); + for (let i = 0; i < retiredNow.length; i++) { + Domain.close(retiredNow[i], session); + } + for (let i = retired.length - 1; i >= 0; i--) { + if (Domain.isDone(retired[i])) { + ArrayPrototypeSplice(retired, i, 1); + } + } }, }); // Registration order, for closing domains in a stable order. const domainNames = []; +// Unregistered domains that some open session enabled or sent a command. +const retired = []; function validateOptions(options) { if (options === undefined) { @@ -440,7 +484,8 @@ function validateOptions(options) { } for (let i = 0; i < kHooks.length; i++) { const hook = kHooks[i]; - if (options[hook] !== undefined && typeof options[hook] !== "function") { + const value = options[hook]; + if (value !== undefined && typeof value !== "function") { throw new TypeError(`'${hook}' must be a function`); } } From 23dcd8ad5d94b44eaf5afecaa9f78614af94e824 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 00:06:15 -0300 Subject: [PATCH 03/11] fix(inspector): an older sessionEnabled no longer ends a newer one's wait --- NativeScript/runtime/js/ns-inspector.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/NativeScript/runtime/js/ns-inspector.js b/NativeScript/runtime/js/ns-inspector.js index 7c74bda7f..efcae6863 100644 --- a/NativeScript/runtime/js/ns-inspector.js +++ b/NativeScript/runtime/js/ns-inspector.js @@ -404,7 +404,10 @@ class Domain { const waiting = [done]; MapPrototypeSet(this.#initializing, session, waiting); const settled = () => { - MapPrototypeDelete(this.#initializing, session); + // Not a newer one: the client may have disabled and enabled it again. + if (MapPrototypeGet(this.#initializing, session) === waiting) { + MapPrototypeDelete(this.#initializing, session); + } for (let i = 0; i < waiting.length; i++) { waiting[i](); } From 931d8d3034e4ae686428a7bacf91158631cc4895 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 00:10:26 -0300 Subject: [PATCH 04/11] fix(inspector): a disable drops a pending sessionEnabled's wait --- NativeScript/runtime/js/ns-inspector.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/NativeScript/runtime/js/ns-inspector.js b/NativeScript/runtime/js/ns-inspector.js index efcae6863..bdcf95d14 100644 --- a/NativeScript/runtime/js/ns-inspector.js +++ b/NativeScript/runtime/js/ns-inspector.js @@ -423,6 +423,9 @@ class Domain { return; } this.#enabledCount--; + // A later enable starts over; replies already waiting still go out when + // the pending sessionEnabled settles. + MapPrototypeDelete(this.#initializing, session); callHook(this.#options, "sessionDisabled", session); if (this.#enabledCount === 0) { callHook(this.#options, "disabled"); From 8e0982bcb2f949afd79773d6dd0d0157b9dad2c9 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 00:14:52 -0300 Subject: [PATCH 05/11] fix(inspector): record a pending enable before its hooks run --- NativeScript/runtime/js/ns-inspector.js | 28 +++++++++++++------------ 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/NativeScript/runtime/js/ns-inspector.js b/NativeScript/runtime/js/ns-inspector.js index bdcf95d14..861f9bc7b 100644 --- a/NativeScript/runtime/js/ns-inspector.js +++ b/NativeScript/runtime/js/ns-inspector.js @@ -388,19 +388,8 @@ class Domain { SetPrototypeAdd(this.#enabled, session); this.#enabledCount++; SetPrototypeAdd(this.#touched, session); - if (first) { - callHook(this.#options, "enabled"); - } - // The client may have left, or disabled it again, while `enabled` ran. - if (session.closed || !SetPrototypeHas(this.#enabled, session)) { - done(); - return; - } - const result = callHook(this.#options, "sessionEnabled", session, params === undefined ? {} : params); - if (!isThenable(result)) { - done(); - return; - } + // Before any hook runs: a hook can pause, and the pause loop can hand + // this client's next enable to us meanwhile. const waiting = [done]; MapPrototypeSet(this.#initializing, session, waiting); const settled = () => { @@ -412,6 +401,19 @@ class Domain { waiting[i](); } }; + if (first) { + callHook(this.#options, "enabled"); + } + // The client may have left, or disabled it again, while `enabled` ran. + if (session.closed || !SetPrototypeHas(this.#enabled, session)) { + settled(); + return; + } + const result = callHook(this.#options, "sessionEnabled", session, params === undefined ? {} : params); + if (!isThenable(result)) { + settled(); + return; + } whenSettled(result, settled, (error) => { report(error); settled(); From b3740fb095175dc6b3d6ff9f605ac36a2074752f Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 00:38:56 -0300 Subject: [PATCH 06/11] fix(inspector): answer every JS domain command, close hooks after the session - Any thrown value, a rejection with one, or a result whose then getter throws answers the command with an error; before, some left it unanswered. - A sessionEnabled result whose then getter throws no longer leaves the client's later enables waiting. - Close hooks run after the client's V8 session is gone, so one that pauses does not hold the app for a client that has left. --- NativeScript/inspector/JsV8InspectorClient.mm | 4 +- NativeScript/runtime/js/ns-inspector.js | 40 +++++++++++++++++-- 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/NativeScript/inspector/JsV8InspectorClient.mm b/NativeScript/inspector/JsV8InspectorClient.mm index 024e41536..bc078e9cc 100644 --- a/NativeScript/inspector/JsV8InspectorClient.mm +++ b/NativeScript/inspector/JsV8InspectorClient.mm @@ -675,12 +675,14 @@ bool GetInt32(const json& value, long long& out) { for (auto& entry : this->rememberedEnables_) { entry.second.erase(item.connectionId); } - this->NotifyJsDomainsClosed(item.connectionId); for (auto it = this->pendingJsReplies_.begin(); it != this->pendingJsReplies_.end();) { it = it->second.connectionId == item.connectionId ? this->pendingJsReplies_.erase(it) : std::next(it); } sessions_->Disconnect(item.connectionId); + // After the session: a hook that pauses must not hold the app for a + // frontend that is gone. + this->NotifyJsDomainsClosed(item.connectionId); this->StopHolding(item.connectionId, false); break; case InspectorQueue::Item::Kind::kMessage: diff --git a/NativeScript/runtime/js/ns-inspector.js b/NativeScript/runtime/js/ns-inspector.js index 861f9bc7b..2431102c5 100644 --- a/NativeScript/runtime/js/ns-inspector.js +++ b/NativeScript/runtime/js/ns-inspector.js @@ -31,6 +31,7 @@ const { Error, Map, Set, + String, TypeError, ArrayPrototypePush, ArrayPrototypeSlice, @@ -87,11 +88,22 @@ function setValues(set) { } } +// Reads `then`, which may be a getter that throws. function isThenable(value) { return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function"; } +// The text of anything thrown, whatever it is. +function messageOf(error) { + try { + const message = error instanceof Error ? error.message : String(error); + return typeof message === "string" ? message : String(message); + } catch { + return ""; + } +} + function report(error) { try { logError(error instanceof Error && typeof error.stack === "string" ? error.stack : `${error}`); @@ -226,7 +238,7 @@ function replyError(session, id, error) { if (!isProtocolError) { report(error); } - const message = error instanceof Error ? error.message : `${error}`; + const message = messageOf(error); send(Session.connectionId(session), JSONStringify({ id, error: { code: isProtocolError ? error.code : kServerError, message: message || "Internal error" }, @@ -235,7 +247,14 @@ function replyError(session, id, error) { // Answers once `value` settles, when it is a promise. function whenSettled(value, onResult, onError) { - if (!isThenable(value)) { + let thenable; + try { + thenable = isThenable(value); + } catch (error) { + onError(error); + return; + } + if (!thenable) { onResult(value); return; } @@ -410,7 +429,13 @@ class Domain { return; } const result = callHook(this.#options, "sessionEnabled", session, params === undefined ? {} : params); - if (!isThenable(result)) { + let thenable = false; + try { + thenable = isThenable(result); + } catch (error) { + report(error); + } + if (!thenable) { settled(); return; } @@ -449,7 +474,14 @@ const router = ObjectFreeze({ if (domain === undefined) { return false; } - return Domain.dispatch(domain, sessionFor(connectionId), id, command, params); + const session = sessionFor(connectionId); + try { + return Domain.dispatch(domain, session, id, command, params); + } catch (error) { + // The command was ours; it must not go unanswered. + replyError(session, id, error); + return true; + } }, closed(connectionId) { const session = MapPrototypeGet(sessions, connectionId); From 4756fed527a236e54d72f22ece69cc926c36de41 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 00:42:59 -0300 Subject: [PATCH 07/11] fix(inspector): answer a command rejected with a revoked proxy --- NativeScript/runtime/js/ns-inspector.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/NativeScript/runtime/js/ns-inspector.js b/NativeScript/runtime/js/ns-inspector.js index 2431102c5..cfcf99e1b 100644 --- a/NativeScript/runtime/js/ns-inspector.js +++ b/NativeScript/runtime/js/ns-inspector.js @@ -234,7 +234,13 @@ function replyError(session, id, error) { if (session.closed) { return; } - const isProtocolError = error instanceof ProtocolError; + let isProtocolError = false; + try { + // Throws for a revoked proxy. + isProtocolError = error instanceof ProtocolError; + } catch { + // Not one of ours. + } if (!isProtocolError) { report(error); } From 3302d3f39ceb075f25c7dce280515b9cae4ed4b3 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 00:47:19 -0300 Subject: [PATCH 08/11] fix(inspector): fall back to -32000 for a ProtocolError code that is no longer an integer --- NativeScript/runtime/js/ns-inspector.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/NativeScript/runtime/js/ns-inspector.js b/NativeScript/runtime/js/ns-inspector.js index cfcf99e1b..f95bac002 100644 --- a/NativeScript/runtime/js/ns-inspector.js +++ b/NativeScript/runtime/js/ns-inspector.js @@ -244,10 +244,21 @@ function replyError(session, id, error) { if (!isProtocolError) { report(error); } + let code = kServerError; + if (isProtocolError) { + try { + // `code` is writable, so it may no longer be an integer. + if (NumberIsInteger(error.code)) { + code = error.code; + } + } catch { + // Keep the default. + } + } const message = messageOf(error); send(Session.connectionId(session), JSONStringify({ id, - error: { code: isProtocolError ? error.code : kServerError, message: message || "Internal error" }, + error: { code, message: message || "Internal error" }, })); } From 4f9742ef3effc9e1de0443699c961c48db386f9d Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 00:58:39 -0300 Subject: [PATCH 09/11] fix(inspector): more defensive JS domain replies and enables - A sessionEnabled promise whose constructor getter throws settles the enable, so later enables are answered. - A ProtocolError's code is read once. - A disable handled by a __registerDomainDispatcher domain also forgets the client's remembered enable, so a later registerDomain of the name does not enable it again. --- NativeScript/inspector/JsV8InspectorClient.mm | 2 ++ NativeScript/runtime/js/ns-inspector.js | 12 +++++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/NativeScript/inspector/JsV8InspectorClient.mm b/NativeScript/inspector/JsV8InspectorClient.mm index bc078e9cc..1951168d0 100644 --- a/NativeScript/inspector/JsV8InspectorClient.mm +++ b/NativeScript/inspector/JsV8InspectorClient.mm @@ -931,6 +931,8 @@ bool GetInt32(const json& value, long long& out) { bool hasHandler = !domainMethodFunc.IsEmpty() && domainMethodFunc->IsFunction(); if (hasHandler && command == "disable") { + // Neither may a later registerDomain of the name find it enabled. + this->rememberedEnables_[domain].erase(connectionId); auto& enablers = this->jsDomainEnablers_[domain]; enablers.erase(connectionId); if (!enablers.empty()) { diff --git a/NativeScript/runtime/js/ns-inspector.js b/NativeScript/runtime/js/ns-inspector.js index f95bac002..3d5e44550 100644 --- a/NativeScript/runtime/js/ns-inspector.js +++ b/NativeScript/runtime/js/ns-inspector.js @@ -248,8 +248,9 @@ function replyError(session, id, error) { if (isProtocolError) { try { // `code` is writable, so it may no longer be an integer. - if (NumberIsInteger(error.code)) { - code = error.code; + const candidate = error.code; + if (NumberIsInteger(candidate)) { + code = candidate; } } catch { // Keep the default. @@ -275,7 +276,12 @@ function whenSettled(value, onResult, onError) { onResult(value); return; } - PromisePrototypeThen(PromiseResolve(value), onResult, onError); + try { + // Reads `constructor`, which may be a getter that throws. + PromisePrototypeThen(PromiseResolve(value), onResult, onError); + } catch (error) { + onError(error); + } } class Domain { From d3c90cb36c3ebf124395c017fd90a4d9391b47be Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 01:39:53 -0300 Subject: [PATCH 10/11] fix(inspector): forget a remembered enable only once a legacy disable succeeds --- NativeScript/inspector/JsV8InspectorClient.mm | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/NativeScript/inspector/JsV8InspectorClient.mm b/NativeScript/inspector/JsV8InspectorClient.mm index 1951168d0..6af0ffeaa 100644 --- a/NativeScript/inspector/JsV8InspectorClient.mm +++ b/NativeScript/inspector/JsV8InspectorClient.mm @@ -931,11 +931,11 @@ bool GetInt32(const json& value, long long& out) { bool hasHandler = !domainMethodFunc.IsEmpty() && domainMethodFunc->IsFunction(); if (hasHandler && command == "disable") { - // Neither may a later registerDomain of the name find it enabled. - this->rememberedEnables_[domain].erase(connectionId); auto& enablers = this->jsDomainEnablers_[domain]; enablers.erase(connectionId); if (!enablers.empty()) { + // Neither may a later registerDomain of the name find it enabled. + this->rememberedEnables_[domain].erase(connectionId); json response = {{"id", json_message["id"]}, {"result", json::object()}}; this->SendRawToConnection(connectionId, response.dump()); return; @@ -981,6 +981,9 @@ bool GetInt32(const json& value, long long& out) { } if (success) { + if (hasHandler && command == "disable") { + this->rememberedEnables_[domain].erase(connectionId); + } auto returnString = GetReturnMessageFromDomainHandlerResult(result, json_message["id"]); From 29c1beb1a3c458e5e18f8596f71ec045b2b03b59 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 12:46:07 -0300 Subject: [PATCH 11/11] fix(inspector): keep the one-owner rule out of the ns:inspector contract - Commands a registered domain does not define go on to the domain's __registerDomainDispatcher handler instead of straight to V8, so registering a domain no longer silences a legacy dispatcher for it. - emit throws a TypeError for params that are not an object, instead of stringifying them. - Docs and types describe the already-registered throw as a current limit, stop promising empty params for remembered enables, and allow native handling before a command reaches its domain. --- NativeScript/inspector/JsV8InspectorClient.mm | 6 +++-- NativeScript/runtime/js/ns-inspector.js | 14 ++++++++++- TestRunner/app/tests/NsInspectorTests.js | 9 +++++--- docs/ns-builtin-modules.md | 23 ++++++++++++------- types/ns-inspector.d.ts | 6 ++--- 5 files changed, 41 insertions(+), 17 deletions(-) diff --git a/NativeScript/inspector/JsV8InspectorClient.mm b/NativeScript/inspector/JsV8InspectorClient.mm index 6af0ffeaa..97c4ed826 100644 --- a/NativeScript/inspector/JsV8InspectorClient.mm +++ b/NativeScript/inspector/JsV8InspectorClient.mm @@ -914,7 +914,9 @@ bool GetInt32(const json& value, long long& out) { std::string domain = method.substr(0, dot); std::string command = dot == std::string::npos ? std::string() : method.substr(dot + 1); - // Domains registered through ns:inspector win over __registerDomainDispatcher. + // Domains registered through ns:inspector win over __registerDomainDispatcher, + // which still gets the commands their handlers do not define. The router + // answers enable and disable itself, so those never reach it. bool jsDomain = this->jsDomains_.count(domain) != 0 && arg->IsObject(); if (jsDomain && this->DispatchToJsDomain(connectionId, context, arg.As(), domain, command)) { @@ -922,7 +924,7 @@ bool GetInt32(const json& value, long long& out) { } // Pass incoming message to a registerd domain handler if any - if (!jsDomain && !arg.IsEmpty() && arg->IsObject()) { + if (!arg.IsEmpty() && arg->IsObject()) { Local domainDebugger; Local argObject = arg.As(); Local domainMethodFunc = diff --git a/NativeScript/runtime/js/ns-inspector.js b/NativeScript/runtime/js/ns-inspector.js index 3d5e44550..8cc5aa106 100644 --- a/NativeScript/runtime/js/ns-inspector.js +++ b/NativeScript/runtime/js/ns-inspector.js @@ -33,6 +33,7 @@ const { Set, String, TypeError, + ArrayIsArray, ArrayPrototypePush, ArrayPrototypeSlice, ArrayPrototypeSplice, @@ -88,6 +89,14 @@ function setValues(set) { } } +// Refused rather than coerced: a function is reserved for params built per session. +function checkParams(params) { + if (params !== undefined && + (params === null || typeof params !== "object" || ArrayIsArray(params))) { + throw new TypeError("emit expects params to be an object"); + } +} + // Reads `then`, which may be a getter that throws. function isThenable(value) { return value !== null && (typeof value === "object" || typeof value === "function") && @@ -149,6 +158,7 @@ class Session { if (typeof method !== "string") { throw new TypeError("emit expects a method name"); } + checkParams(params); if (this.#closed) { return; } @@ -319,6 +329,7 @@ class Domain { if (typeof event !== "string") { throw new TypeError("emit expects an event name"); } + checkParams(params); if (!this.#registered) { return; } @@ -581,10 +592,11 @@ class InertDomain { return false; } - emit(event) { + emit(event, params) { if (typeof event !== "string") { throw new TypeError("emit expects an event name"); } + checkParams(params); } unregister() { diff --git a/TestRunner/app/tests/NsInspectorTests.js b/TestRunner/app/tests/NsInspectorTests.js index 310e6a1ca..8640afb08 100644 --- a/TestRunner/app/tests/NsInspectorTests.js +++ b/TestRunner/app/tests/NsInspectorTests.js @@ -45,19 +45,22 @@ describe("ns:inspector", function () { }); }); - it("allows one owner per domain until it unregisters", function () { + it("registers a domain again after it unregisters", function () { var domain = register("NsInspectorTestsOwner"); expect(domain.name).toBe("NsInspectorTestsOwner"); - expect(function () { nsInspector.registerDomain("NsInspectorTestsOwner"); }).toThrowError(/already registered/); domain.unregister(); - register("NsInspectorTestsOwner"); + expect(register("NsInspectorTestsOwner").name).toBe("NsInspectorTestsOwner"); }); it("is not enabled without a client, and emits nowhere", function () { var domain = register("NsInspectorTestsQuiet", { commands: {} }); expect(domain.enabled).toBe(false); domain.emit("event", { a: 1 }); + domain.emit("event"); expect(function () { domain.emit(5); }).toThrowError(TypeError); + [null, 1, "x", [], function () {}].forEach(function (params) { + expect(function () { domain.emit("event", params); }).toThrowError(TypeError); + }); }); it("builds protocol errors with a code", function () { diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 7aaa5dc1c..91862ffc2 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -926,7 +926,7 @@ until the Android runtime ships it. | export | description | |---|---| -| `registerDomain(name, options?)` | Handles every command `name.*` from every client and returns the domain. Throws a `TypeError` for a name that is not a capitalized identifier or for malformed options, and an `Error` for a domain the runtime implements (`Runtime`, `Debugger`, `Profiler`, `HeapProfiler`, `Console`, `Schema`, `Target`, `IO`, `Tracing`) or one already registered. | +| `registerDomain(name, options?)` | Handles every command `name.*` from every client and returns the domain. Throws a `TypeError` for a name that is not a capitalized identifier or for malformed options, and an `Error` for a domain the runtime implements (`Runtime`, `Debugger`, `Profiler`, `HeapProfiler`, `Console`, `Schema`, `Target`, `IO`, `Tracing`) or, for now, one already registered. | | `ProtocolError` | `new ProtocolError(code, message)`: thrown or rejected by a command to answer with that protocol error code. | | `monotonicTime()` | Seconds on the monotonic clock trace events use, sub-millisecond (`Network.MonotonicTime`). | | `wallTime()` | Seconds since the epoch, fractional (`Network.TimeSinceEpoch`). | @@ -965,13 +965,15 @@ Rules: for an `alwaysEnabled` one. - **A client that enabled a domain before it was registered** (or while it was unregistered) is enabled at registration: `enabled` and - `sessionEnabled` run then, with empty params. + `sessionEnabled` run then. `params` may be `undefined` there instead of + what the client's `enable` carried. - **Commands may be async.** The returned value, or what a returned promise resolves to, answers the command; `undefined` answers `{}`. A throw or rejection answers with an error whose code is the `ProtocolError`'s, or -32000. A reply never reaches another client, and one for a client that - left is dropped. A command the handlers do not define goes to V8, which - does not know it. + left is dropped. A command the handlers do not define goes on to the + domain's `__registerDomainDispatcher` handler if there is one, and + otherwise to V8, which does not know it. - **Per client, messages go out in the order they are sent.** Events a command emits precede its reply, and events `sessionEnabled` emits precede the reply to `enable`, which waits for a promise `sessionEnabled` returns. @@ -990,10 +992,15 @@ Rules: objects are never broadcast. `addInspectedObject` makes the getter's value `$0` in that client's console. Once the client has left, `emit` does nothing and the object methods throw. -- **Commands the runtime answers natively stay native**: - `Network.loadNetworkResource`, `IO.*`, `Tracing.*` and `Target.*` reach no - domain. -- A domain registered with `__registerDomainDispatcher` too is handled here. +- **Event params are an object.** `emit` throws a `TypeError` for any other + `params` but `undefined`, which sends `{}`. +- **The runtime sees some commands first.** It answers + `Network.loadNetworkResource`, `IO.*`, `Tracing.*` and `Target.*` itself, + and they reach no domain. It may also act on other commands natively before + passing them on to the domain. +- **A domain registered with `__registerDomainDispatcher` too** is handled + here; the dispatcher keeps the commands `commands` does not define, and + never receives `enable` or `disable`. - **In release builds and in workers** the module loads, `registerDomain` returns an inert domain (`enabled` is false, `emit` does nothing), and `captureStackTrace` returns `undefined`. diff --git a/types/ns-inspector.d.ts b/types/ns-inspector.d.ts index fbaf0b046..7a42ecb5b 100644 --- a/types/ns-inspector.d.ts +++ b/types/ns-inspector.d.ts @@ -72,9 +72,9 @@ declare module "ns:inspector" { /** * Handles the commands of `name` from every connected client. Throws for - * a domain the runtime implements (`Runtime`, `Debugger`, `Target`, ...) and - * for one already registered. In release builds and in workers the domain - * is inert: `enabled` is false and `emit` does nothing. + * a domain the runtime implements (`Runtime`, `Debugger`, `Target`, ...) and, + * for now, for one already registered. In release builds and in workers the + * domain is inert: `enabled` is false and `emit` does nothing. */ export function registerDomain(name: string, options?: DomainOptions): InspectorDomain;