Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
7f898b5
build(runtime): take the base64 codec from the shared runtime-common …
edusperoni Dec 4, 2026
fba7f6b
feat(runtime): run the HTTP module loader on runtime-common
edusperoni Dec 5, 2026
eca54ca
build: pin runtime-common foundation and implement its platform funct…
edusperoni Dec 5, 2026
cae3f7f
feat(runtime): pump through Loop::PumpUntil
edusperoni Dec 5, 2026
9643abd
Merge remote-tracking branch 'origin/main' into feat/runtime-common
edusperoni Dec 5, 2026
35fdde5
build: pin runtime-common step 4 and implement the app-file and state…
edusperoni Dec 5, 2026
ddf63e4
feat(runtime): compile app files and keep their code caches through r…
edusperoni Dec 5, 2026
cd962c0
feat(runtime): delete the old flattened code caches once
edusperoni Dec 5, 2026
101f8ca
build: pin runtime-common at 6826386
edusperoni Dec 5, 2026
98d645a
fix(runtime): keep a non-sandboxed Catalyst app's code cache under it…
edusperoni Dec 5, 2026
141d243
fix(runtime): keep a non-sandboxed Catalyst app's HTTP module cache u…
edusperoni Dec 5, 2026
9f511e0
style: clang-format the app caches directory change
edusperoni Dec 5, 2026
9b0cf7d
build: pin runtime-common at 39e2174 and implement platform::ParseUrl
edusperoni Dec 5, 2026
8c80061
feat(runtime): take module identity from the runtime-common core
edusperoni Dec 5, 2026
ce21736
build: pin runtime-common at 3bcf603
edusperoni Dec 5, 2026
8cddd98
feat(runtime): take loader state, registry and resolution from the ru…
edusperoni Dec 5, 2026
f4a28d4
build: pin runtime-common at da7852d
edusperoni Dec 5, 2026
5cbb603
test(runtime): pin module resolution under the runtime-common core
edusperoni Dec 6, 2026
055b991
build: pin runtime-common at 8585d65
edusperoni Dec 6, 2026
b9ae5ab
feat(runtime): take the graph walk, file jobs, import callbacks and J…
edusperoni Dec 6, 2026
dbc010c
test(runtime): cover JSON module strictness and loader teardown under…
edusperoni Dec 6, 2026
4969897
build: pin runtime-common at f73c0f5
edusperoni Dec 6, 2026
510a459
test(runtime): pin a static import of '' and import JSON with its typ…
edusperoni Dec 6, 2026
14fedd9
build: pin runtime-common at ab7f353
edusperoni Dec 6, 2026
238d4b2
feat(runtime): take import.meta, the require(esm) facade and the ns:m…
edusperoni Dec 6, 2026
40bb311
test(runtime): cover import of .js, CommonJS and .cjs files and impor…
edusperoni Dec 6, 2026
12cd4fe
test(runtime): read code cache headers of format 2
edusperoni Dec 6, 2026
d2e6e31
fix(runtime): run every registered task in Tasks::Drain
edusperoni Dec 6, 2026
be00086
feat(runtime): boot the main entry and evaluate module graphs through…
edusperoni Dec 6, 2026
b91557a
test(runtime): cover module identity, require() cycles and waiting fo…
edusperoni Dec 6, 2026
1010277
docs: describe the main-entry boot hold and worker entries under the …
edusperoni Dec 6, 2026
390a2e1
feat(runtime): make a main-entry rejection after the hand-off fatal
edusperoni Dec 6, 2026
61b64d9
fix(runtime): keep the uncaughtErrorPolicy "throw" exception alive un…
edusperoni Dec 6, 2026
f56e886
chore(runtime): repin runtime-common to 53ed375
edusperoni Dec 6, 2026
fe32b9a
docs: module deadlines cover walk and settle; a hand-off entry reject…
edusperoni Dec 6, 2026
3a3d124
feat(runtime): require() through the runtime-common CommonJS core
edusperoni Dec 6, 2026
39f2fd8
test(runtime): run the shared node_modules, module-error, index.json …
edusperoni Dec 6, 2026
cb142cf
test(runtime): cover require() module objects, require.resolve/main, …
edusperoni Dec 6, 2026
ed2e3dd
docs: require() resolution, require.resolve/main and worker entry nam…
edusperoni Dec 6, 2026
aedaff1
chore(runtime): repin runtime-common to 8c4e81d
edusperoni Dec 6, 2026
3f202d7
docs: ~x app-root names and non-JavaScript worker entries
edusperoni Dec 6, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@
path = TestRunner/app/shared
url = https://github.com/NativeScript/common-runtime-tests-app.git
branch = master
[submodule "NativeScript/runtime-common"]
path = NativeScript/runtime-common
url = https://github.com/NativeScript/runtime-common.git
85 changes: 4 additions & 81 deletions NativeScript/NativeScript.mm
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
#include "runtime/Console.h"
#include "runtime/Helpers.h"
#include "runtime/ModuleInternal.h"
#include "runtime/ModuleInternalCallbacks.h"
#include "runtime/NativeScriptException.h"
#include "runtime/Runtime.h"
#include "runtime/RuntimeConfig.h"
Expand Down Expand Up @@ -129,87 +128,10 @@ static void DestroyMainRuntime() {
- (void)runMainApplication {
runtime_->RunMainScript();

// Outside the Locker: for a UI app this calls UIApplicationMain, which never
// returns.
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true);
tns::Tasks::Drain();

// Async boot handoff. For UI apps Tasks::Drain() invokes UIApplicationMain
// and never returns — the app's main runloop services whatever is still in
// flight. When Drain returns, the entry has not reached UIApplicationMain,
// so pump a manual runloop until boot actually finishes, Node-like. A
// completion may itself register the UIApplicationMain task, so drain after
// each slice; if that drain calls UIApplicationMain it takes over and never
// returns.
//
// Two independent things can leave boot unfinished, and BOTH must hold the
// pump: an in-flight module-graph load, and an entry whose own evaluation
// promise is still pending — a top-level await parked on anything at all
// (a nested import() that does its own async work, a native init that will
// call UIApplicationMain later). Gating on graph work alone let the second
// case reach counter == 0 and fall off the end of main().
std::string entryRejectionReason;
bool entryPending = runtime_->PollMainEntryEvaluation(&entryRejectionReason) ==
tns::EntryEvaluationState::kPending;
bool entryRejected = false;

if (entryPending || tns::HasPendingAsyncModuleGraphWork()) {
const CFAbsoluteTime deadline =
CFAbsoluteTimeGetCurrent() + 2 * tns::kModuleEvaluateDeadlineSeconds;
bool terminated = false;
for (;;) {
// Termination outranks everything, including an entry that settled in the
// same slice: boot must report the terminating fatal rather than take the
// normal exit and carry on into an app on a stopping isolate. Nothing
// pending can complete after this point either. Both signals: V8 reports
// only a materialized termination, which needs JS to run, and an entry
// parked on a promise nothing settles never runs any.
if (runtime_->IsExecutionTerminating() || runtime_->IsTerminationRequested()) {
terminated = true;
break;
}
if (!(entryPending || tns::HasPendingAsyncModuleGraphWork())) {
break;
}
if (CFAbsoluteTimeGetCurrent() >= deadline) {
break;
}
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.01, true);
tns::Tasks::Drain();

if (entryPending) {
tns::EntryEvaluationState state = runtime_->PollMainEntryEvaluation(&entryRejectionReason);
// Once it settles, stop probing for good.
entryPending = state == tns::EntryEvaluationState::kPending;
if (state == tns::EntryEvaluationState::kRejected) {
entryRejected = true;
break;
}
}
}
tns::Tasks::Drain();

// A settled entry that never called UIApplicationMain is a script-style app
// finishing normally. The failures below are fatal in every build: each one
// evicts the entry first, so nothing can later import the half-evaluated
// module the failure left behind, and then throws rather than logging and
// returning into an app whose entry never ran.
std::string fatal;
if (terminated) {
fatal = "boot ended with execution terminating before the main entry settled";
} else if (entryRejected) {
fatal = "the main entry module's evaluation rejected during boot: " + entryRejectionReason;
} else if (entryPending) {
char within[64];
snprintf(within, sizeof(within), "%.0fs", 2 * tns::kModuleEvaluateDeadlineSeconds);
fatal = std::string("main entry never settled and UIApplicationMain was never reached "
"within ") +
within;
}
if (!fatal.empty()) {
runtime_->EvictMainEntry();
Log(@"Fatal: %s", fatal.c_str());
throw tns::NativeScriptException("Fatal: " + fatal);
}
}
}

- (bool)liveSync {
Expand Down Expand Up @@ -246,11 +168,12 @@ - (instancetype)initializeWithConfig:(Config*)config {
Runtime::Initialize();
StartStdioForwarding();
DestroyMainRuntime();
RefreshLoaderConfig();
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
runtime_ = new Runtime();
Isolate* isolate = runtime_->GetIsolate();
v8::Locker l(isolate);
runtime_->Init();
runtime_->Init(nativescript::common::platform::LoaderSnapshot());
std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();
printf("Runtime initialization took %llims (version %s, V8 version %s)\n", duration,
Expand Down
3 changes: 3 additions & 0 deletions NativeScript/inspector/JsV8InspectorClient.h
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,9 @@ class JsV8InspectorClient : V8InspectorClient {
tns::Runtime* runtime_;
v8::Isolate* isolate_;
tns::IsolateWrapper isolateWrapper_;
// The main isolate's loader configuration, for the threads that read file
// URLs without its Locker.
std::shared_ptr<const nativescript::common::LoaderConfig> loaderConfig_;
// The runtime's loop. Outlives the runtime, after which it drops posts.
std::shared_ptr<tns::EventLoop> eventLoop_;
// Work for the main isolate. Connect and disconnect go through the same
Expand Down
137 changes: 80 additions & 57 deletions NativeScript/inspector/JsV8InspectorClient.mm
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
#include "src/inspector/v8-runtime-agent-impl.h"
#include "src/inspector/v8-stack-trace-impl.h"

#include "ns/JsError.h"
#include "ns/loader/LoaderState.h"

#include "Caches.h"
#include "Helpers.h"
#include "HttpLoader.h"
Expand Down Expand Up @@ -69,7 +72,8 @@ bool ShouldRewriteSourceMapURLs() {
// Debugger.scriptFailedToParse events from a file url (or a url relative to
// the script's file url) to an absolute nsruntime:// url, so DevTools
// requests the map through the target instead of the frontend host.
std::string MaybeRewriteSourceMapURL(const std::string& message) {
std::string MaybeRewriteSourceMapURL(const std::string& message,
const nativescript::common::LoaderConfig& config) {
if (!ShouldRewriteSourceMapURLs()) {
return message;
}
Expand All @@ -92,35 +96,32 @@ bool ShouldRewriteSourceMapURLs() {
return message;
}

std::string path;
std::optional<std::string> path;
if (sourceMapURL.rfind("file://", 0) == 0) {
path = tns::FileModulePath(sourceMapURL);
path = tns::OriginToPath(sourceMapURL, config);
} else if (sourceMapURL[0] == '/') {
path = sourceMapURL;
path = tns::OriginToPath("file://" + sourceMapURL, config);
} else {
// Relative to the script url, e.g. "bundle.js.map".
std::string scriptUrl = params.value("url", "");
if (scriptUrl.rfind("file://", 0) != 0) {
return message;
}
@autoreleasepool {
NSString* scriptPath = [NSString stringWithUTF8String:tns::FileModulePath(scriptUrl).c_str()];
NSString* mapPath = [NSString stringWithUTF8String:sourceMapURL.c_str()];
if (scriptPath != nil && mapPath != nil) {
NSString* resolved = [[[scriptPath stringByDeletingLastPathComponent]
stringByAppendingPathComponent:mapPath] stringByStandardizingPath];
if (resolved != nil) {
path = [resolved UTF8String];
}
}
const std::optional<std::string> scriptPath =
tns::OriginToPath(params.value("url", ""), config);
if (scriptPath) {
path = tns::CanonicalFilePath(
scriptPath->substr(0, scriptPath->rfind('/') + 1) + sourceMapURL, config);
}
}

if (path.empty()) {
if (!path || path->empty()) {
return message;
}

params["sourceMapURL"] = kSourceMapScheme + path;
// Spelled as the script's own origin is (file:///app/... for an app file),
// which does not change between installs.
const std::string origin = tns::ReportedModuleUrl(*path, config);
if (origin.rfind("file://", 0) != 0) {
return message;
}
params["sourceMapURL"] = kSourceMapScheme + origin.substr(strlen("file://"));
return parsed.dump();
}

Expand Down Expand Up @@ -240,6 +241,7 @@ bool GetInt32(const json& value, long long& out) {
: runtime_(runtime),
isolate_(runtime_->GetIsolate()),
isolateWrapper_(isolate_),
loaderConfig_(nativescript::common::loader::CaptureLoaderConfig(isolate_)),
eventLoop_(runtime_->GetEventLoop()) {
instance_ = this;
}
Expand Down Expand Up @@ -433,7 +435,7 @@ bool GetInt32(const json& value, long long& out) {
}

// Its Network.setCacheDisabled lasts only as long as the connection.
tns::SetModuleHttpCacheDisabledByInspector(connectionId, false);
tns::SetModuleHttpCacheDisabledBy(connectionId, false);

// Free the process-global trace controller for other frontends.
{
Expand Down Expand Up @@ -520,15 +522,23 @@ bool GetInt32(const json& value, long long& out) {
// DispatchFrontendMessage answers it when there is none. Worker sessions
// have no JS domain handlers, so they are answered here. A sessionId that
// names no worker of this frontend changes nothing and is left to
// RouteToWorker's "Session not found".
// RouteToWorker's "Session not found". A clear that failed is answered here
// for every session, since the domain handler cannot tell.
if ((method == "Network.setCacheDisabled" || method == "Network.clearBrowserCache") &&
(sessionId.empty() || this->HasWorkerSession(connectionId, sessionId))) {
const std::optional<bool> cacheDisabled = SetCacheDisabledParam(parsed);
const bool valid = method == "Network.clearBrowserCache" || cacheDisabled.has_value();
if (method == "Network.clearBrowserCache") {
tns::ClearModuleHttpCache();
const tns::CacheOpResult cleared = tns::ClearModuleHttpCache();
if (!cleared.ok) {
if (msgId >= 0) {
json error = {{"id", msgId}, {"error", {{"code", -32000}, {"message", cleared.error}}}};
this->SendRawToConnection(connectionId, WithSessionId(error, sessionId).dump());
}
return;
}
} else if (valid) {
tns::SetModuleHttpCacheDisabledByInspector(connectionId, *cacheDisabled);
tns::SetModuleHttpCacheDisabledBy(connectionId, *cacheDisabled);
}
if (!sessionId.empty()) {
if (msgId >= 0) {
Expand Down Expand Up @@ -844,7 +854,7 @@ bool GetInt32(const json& value, long long& out) {
}

void JsV8InspectorClient::SendToConnection(uint64_t connectionId, const std::string& message) {
this->SendRawToConnection(connectionId, MaybeRewriteSourceMapURL(message));
this->SendRawToConnection(connectionId, MaybeRewriteSourceMapURL(message, *loaderConfig_));
}

void JsV8InspectorClient::SendRawToConnection(uint64_t connectionId, const std::string& message) {
Expand Down Expand Up @@ -1240,11 +1250,21 @@ bool GetInt32(const json& value, long long& out) {
void JsV8InspectorClient::HandleLoadNetworkResource(uint64_t connectionId, int msgId,
const std::string& url,
const std::string& sessionId) {
std::string path;
if (url.rfind(kSourceMapScheme, 0) == 0) {
path = url.substr(strlen(kSourceMapScheme));
} else if (url.rfind("file://", 0) == 0) {
path = tns::FileModulePath(url);
// DevTools percent-encodes the URLs it requests, while a legacy origin, and
// a source map URL rewritten from one, spell their path verbatim: try both
// readings.
std::vector<std::string> candidates;
const bool sourceMap = url.rfind(kSourceMapScheme, 0) == 0;
if (sourceMap || url.rfind("file://", 0) == 0) {
const std::string fileUrl = sourceMap ? "file://" + url.substr(strlen(kSourceMapScheme)) : url;
std::optional<std::string> verbatim = tns::OriginToPath(fileUrl, *loaderConfig_);
if (verbatim) {
candidates.push_back(*verbatim);
}
std::optional<std::string> decoded = tns::FileUrlToPath(fileUrl, *loaderConfig_);
if (decoded && (!verbatim || *decoded != *verbatim)) {
candidates.push_back(*decoded);
}
} else {
// Reply with a protocol error (not success:false) so DevTools falls back
// to loading the resource from the frontend host, which is the
Expand All @@ -1257,35 +1277,18 @@ bool GetInt32(const json& value, long long& out) {

std::string content;
bool loaded = false;

if (!path.empty()) {
for (const std::string& candidate : candidates) {
@autoreleasepool {
NSString* urlPath = [NSString stringWithUTF8String:path.c_str()];
if (urlPath != nil) {
// Script urls are built by stripping RuntimeConfig.BaseDir (see
// ModuleInternal::LoadClassicScript), so map the url path back to
// disk; fall back to the raw path for absolute urls, and to
// percent-decoded variants for urls the frontend encoded.
NSString* basePath = [NSString stringWithUTF8String:RuntimeConfig.BaseDir.c_str()];
NSMutableArray<NSString*>* candidates = [NSMutableArray new];
[candidates addObject:[basePath stringByAppendingPathComponent:urlPath]];
[candidates addObject:urlPath];
NSString* decoded = [urlPath stringByRemovingPercentEncoding];
if (decoded != nil && ![decoded isEqualToString:urlPath]) {
[candidates addObject:[basePath stringByAppendingPathComponent:decoded]];
[candidates addObject:decoded];
}

for (NSString* candidate in candidates) {
NSData* data = [NSData dataWithContentsOfFile:candidate];
if (data != nil) {
content.assign(static_cast<const char*>(data.bytes), data.length);
loaded = true;
break;
}
}
NSData* data =
[NSData dataWithContentsOfFile:[NSString stringWithUTF8String:candidate.c_str()]];
if (data != nil) {
content.assign(static_cast<const char*>(data.bytes), data.length);
loaded = true;
}
}
if (loaded) {
break;
}
}

json resource;
Expand Down Expand Up @@ -1508,6 +1511,18 @@ bool GetInt32(const json& value, long long& out) {
}
}

// Inspector modules are optional tooling: a top-level await that rejects
// after registerModules returned is logged, like a failure before it.
static void InspectorModulesRejected(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
if (isolate->IsExecutionTerminating()) {
return;
}
TryCatch tc(isolate);
std::string reason = info.Length() > 0 ? tns::ToString(isolate, info[0]) : std::string();
Log(@"Inspector modules failed to load: %s", reason.c_str());
}

void JsV8InspectorClient::registerModules() {
Isolate* isolate = isolate_;
Local<Context> context = isolate->GetEnteredOrMicrotaskContext();
Expand Down Expand Up @@ -1554,11 +1569,19 @@ bool GetInt32(const json& value, long long& out) {
}

try {
runtime_->RunModule(modulePath);
Local<Promise> pendingEntry;
Local<v8::Function> onRejected;
if (runtime_->RunModule(modulePath).ToLocal(&pendingEntry) &&
v8::Function::New(context, InspectorModulesRejected).ToLocal(&onRejected)) {
std::ignore = pendingEntry->Catch(context, onRejected);
}
} catch (tns::NativeScriptException& ex) {
// Inspector modules are optional tooling; a failure must not take the
// app down, but it must be visible.
Log(@"Inspector modules failed to load: %s", ex.getMessage().c_str());
} catch (nativescript::common::JsError& ex) {
Log(@"Inspector modules failed to load: %s", ex.what());
} catch (nativescript::common::Terminated&) {
}
// FIXME: This triggers some DCHECK failures, due to the entered v8::Context in
// Runtime::init().
Expand Down
1 change: 1 addition & 0 deletions NativeScript/runtime-common
Submodule runtime-common added at 8c4e81
Loading
Loading