Status: proposal, 2026-12-04, updated 2026-12-06. Steps 1–6 of §9 are built
and adopted by both runtimes' draft PRs: the build wiring, the foundation
headers, the loop interface, the app-file seam and code cache
(ns/AppFiles.h, ns/loader/), the HTTP policy core (ns/http/) and the
ESM core (ns/loader/). Step 7, the evaluation layer and main-entry boot, is
built in ns/loader/Evaluate.h and ns/loader/Boot.h. Step 8, the CommonJS
core, has its questions decided. F3 (a submodule repository), F7 (the
nativescript::common namespace), D1–D10, A1–A10 and C1–C5 are decided. iOS #622 has since merged (052675a1); its Android port is
NativeScript/android #2177.
Baseline: NativeScript/ios origin/main 73c99f9f, NativeScript/android
origin/main a80675dfb, open iOS PR #622, the in-progress Android port of
#622 (uncommitted, snapshot of 2026-12-04), and open Android PR #2104.
Assumption, as stated in the request: both runtimes build against the same V8. They already do (14.9.207.39 headers on both). The only V8 config difference is pointer compression and Wasm: on for Android 64-bit, off on iOS. None of the loader code depends on it.
Scope: ES module loading, CommonJS require, the V8 code cache and the HTTP
module loader. Other mirrored subsystems (URL, structured clone, messaging,
builtin JS and so on) sit on the same foundation. They are ranked in §9 but not
designed here.
NativeScript has two layers, and this repository holds the first:
- The app runtime: what loading a NativeScript app needs from the ground up. Builtins, module loading, the code cache, the event loop, web globals.
- Native calling: the FFI that exposes platform APIs to JS. It is heading
to an
ns:nativemodule that any engine can load.
NativeScript/runtimes covers only the second layer: native calling on several
engines, through Node-API and its nativescript::engine layer. Its module
loading does just enough to run code. This repository aims at a complete app
runtime.
The order:
- Unify the app runtime across iOS and Android on V8 (this document).
- Shape and build
ns:native. - Port both to a common API that is engine-agnostic, and possibly
platform-agnostic, with each engine and platform supplying its primitives.
Where an existing engine API is too narrow it grows.
nativescript::enginehas no module records, code cache or off-thread compile today. - Bring native calling to any engine, without the app-runtime parts other engines don't need.
Rules that follow from it:
- Performance before neutrality. V8 is the target now, and no path gets
slower to avoid a V8 type. Example: per-runtime state is reached from the
v8::Isolate*that V8 hands every callback, through an isolate data slot, not looked up by an engine-neutral id on each call. Neutral shapes are taken where they are free; where they cost, the V8 type stays, inside the V8 layer. - V8 calls are confined. Policy (resolution, import maps, the graph walk, cache validity, the HTTP gate and retry) has no V8 dependency and is host-tested. V8 calls live in their own files. There is no virtual engine interface; step 3 adds a second implementation of those files, and until then they are the list of what an engine API has to provide.
- Namespace:
nativescript::common, subdivided by component (nativescript::common::base64,::loader,::platform,::http). One sub-namespace stays clear of the flatnativescript::names in NativeScript/runtimes. No nested namespace is calledv8, because insidenativescript::commonit would hide::v8. Headers stay underns/: anativescript/include root matches theNativeScript/source folders of all three repositories on case-insensitive file systems.
-
The loader already exists twice as one design. Every unit has the same name and structure on both sides. Comments say "mirroring iOS" and "the iOS port of the Android EventLoop". The PRs come in pairs.
-
The code itself has drifted. After normalizing formatting and stripping comments, line overlap is 55% in
ModuleInternalCallbacks, 34% inHttpLoaderand 23% inModuleInternal. That is not because the logic is platform specific. Most differences are helper names, state access, error plumbing and real behaviour drift. -
Genuinely platform-specific code is small and easy to name:
- how to read an app file (POSIX on iOS; on Android with #2104, layered files that can come from the APK);
- how to pump the thread (CFRunLoop on iOS, ALooper on Android);
- how to fetch a URL (NSURLSession on iOS, OkHttp or HttpURLConnection on Android);
- how to start a background thread (QoS and autorelease pool on Apple);
- where caches go;
- how the app says "I went to the background";
- where config, logging and the debug flag come from.
-
Porting is about half of all runtime work. Between 2026-09-04 and 2026-12-04:
- 35 of 81 iOS runtime PRs and 27 of 66 Android runtime PRs were ports of each other;
- that is ~15.0k and ~15.2k changed lines, about 57% and 51% of runtime churn;
- the lag ran from same-day to 55 days.
-
#622 is the measuring stick. It adds 435 substantive lines on iOS.
- 305 of them (70%) reappear verbatim, whitespace aside, in the Android port.
- Of the rest, 25 iOS lines and 36 Android lines are platform calls.
- 26 Android lines are a new pump primitive.
- The remainder (102 iOS, 153 Android) are renames, plus #622 being threaded through code that had already diverged.
With the core proposed here, the port would be a ~35-line Java/JNI lifecycle hook. The interface would have grown by a few generic primitives (§6.1).
-
Unifying finds bugs. The comparison turned up a dozen behaviour bugs that exist on only one side (§8). Several of them are worth fixing before or regardless of unification.
Metric: lines of the iOS file that diff matches to the Android file. Both
sides first go through a comment-stripping pass that respects string literals,
then one clang-format style (Google, 100 columns), with blank lines dropped.
The numbers are rough, because diff alignment is not semantic, but they are
much closer than raw diff -w. That is because iOS uses 2-space indents and
80 columns, while Android uses 4-space indents and 100 columns. (A first pass
without string awareness under-counted the loader files.)
| Pair | Common lines | Why the rest differs |
|---|---|---|
NativeScriptPlatform |
100% | nothing; the .mm contains no ObjC |
Base64, ModuleBinding |
~99% | one include |
TextEncoding, StructuredSerialization, Messaging |
92–97% | helper names, state access, small drift |
URL, URLSearchParams, URLPattern, BuiltinLoader |
79–87% | helper names, state access, three URL behaviour drifts |
NsBuiltinModules |
~65% | platform registry rows, logging |
ModuleInternalCallbacks (ESM) |
~55% | the same algorithm unit by unit, with drifted resolution, identity, pump and teardown (report A) |
ModuleInternal (CJS + evaluation) |
~23% | ESM evaluation is near identical; CommonJS resolution diverged structurally, with a native resolver on iOS and Java Module.java on Android |
HttpLoader |
~34% | policy is mirrored; the transport is genuinely different (report C) |
Per unit, the ESM resolver/registry report counts about 85% of
ModuleInternalCallbacks as "the same algorithm". The line overlap is low
because names, state accessors and error types differ on almost every line.
Already identical in substance:
- HTTP URL spelling and canonical keys;
- response classification and its error texts;
- the allowlist matcher;
- the require(esm) facade, registry mutation and invalidation;
- dynamic-import waiters;
- the settle policies (
kSyncStrict/kSyncPumping/kAsync); - the entry-evaluation probes;
- the off-thread compile gate.
┌───────────────────────────────────────────────────────────────┐
│ builtin JS (ns-module.js, require-factory.js, …) — shared │
├───────────────────────────────────────────────────────────────┤
│ common::loader — the shared core │
│ esm/ registry, identity, import maps, resolver, graph │
│ walk, dynamic import, import.meta, ns:module binding │
│ cjs/ resolver (node_modules walk), wrapper, require cache │
│ eval/ EvaluateModuleGraph, settle policies, main-entry │
│ boot (a pumping require of the entry) │
│ cache/ code-cache format, naming, freshness, deferred │
│ creation queue (#622 shape) │
│ http/ gate, canonicalization, classification, retry and │
│ deadline, cache switch, Clear-Site-Data, lanes │
│ jobs/ stream-compile pool, compile gate │
├───────────────────────────────────────────────────────────────┤
│ common foundation — shared, bridge-free headers │
│ IsolateState<T>, V8Helpers, Check, TraceLog/Log, JsError, │
│ Deadline, EventLoop interface │
├───────────────────────────────────────────────────────────────┤
│ common::platform — implemented once per platform │
│ ios/ (ObjC++, CF, NSURLSession) android/ (JNI, ALooper, │
│ OkHttp, AppFiles) │
└───────────────────────────────────────────────────────────────┘
The core never includes Caches.h, Helpers.h, Runtime.h, ArgConverter.h,
RuntimeState.h or JEnv.h. Those headers pull in ObjC, libffi or JNI. This
rule is the real prerequisite, more than any renaming.
Calls go in both directions:
- Down: the core calls the platform for files, loop, transport, threads, config and logs (§4).
- Up: the platform calls the core for V8 host callbacks, entry loading, teardown, lifecycle notifications, HTTP-cache controls and Java-facing resolution (§5).
Every method below traces to a place where the two trees do the same abstract thing differently. Each one lists both current implementations.
Recommended: link-time free functions for process-wide services, and small abstract classes only where more than one implementation lives at runtime.
HttpLoader.halready works link-time: one header,.mmon iOS and.cppon Android. No vtables, and the linker catches a missing function.- The cost: a core PR that adds a platform function can't build until both platforms implement it. With a submodule and a core CI that builds both runtimes, a new primitive needs a protocol. Either the platforms land it first (unused), or it arrives as a defaulted virtual or weak default that the core can call before every platform has caught up. #622 would have added six such primitives (§6.1), so this comes up regularly.
- The transport and the event loop are exceptions:
- Android switches transport from OkHttp to the platform one on
LinkageError. - Tests want fakes for both.
- Host-side unit tests need a fake file system and a fake transport.
- Android switches transport from OkHttp to the platform one on
Built: ns/LoaderConfig.h (LoaderConfig, platform::LoaderSnapshot()),
ns/Platform.h (Log, TraceEnabled, Trace), ns/Trace.h (Tracef,
Logf, NS_TRACE) and ns/V8Flags.h. LoaderConfig holds only fields the
loader reads today: appRoot, reportedPathPrefix, isDebug,
codeCacheEnabled, codeCacheDir and v8Flags. HTTP settings stay in
http::HttpLoaderConfig. Step 6.1 adds the module-identity fields:
appRootAliases: pairs of another spelling ofappRoot(or of an ancestor) and the oneappRootuses. Examples are Android's/data/data/<pkg>for/data/user/0/<pkg>, and iOS's/private/varfor/var, whichstringByStandardizingPathused to fold;virtualFileRoots:file://path prefixes that name the app root;appRootOrigin;legacyOrigins(A10).
reportedPathPrefix goes once both runtimes adopt 6.1 (Q5).
These join it when their step lands:
globalModuleRootsandwalkNodeModuleswith the CJS core (step 8);Fatalwhen the first core caller needs it.
Today these values come from:
| Value | iOS | Android |
|---|---|---|
| app root | RuntimeConfig.ApplicationPath |
three spellings: APP_ROOT_FOLDER_PATH, GetApplicationPath() and Java; #2104 unifies them as AppFiles |
| debug flag | RuntimeConfig.IsDebug |
isDebuggable passed to Runtime::Init, plus a second JNI read into s_isDebuggable |
| allowlist | RemoteModuleAllowlistFromConfig(id) |
RemoteModuleAllowlistFromConfig(optional<vector<optional<string>>>) |
| config reads | Runtime::GetAppConfigValue → id |
Java AppConfig → StartupOptions |
Shared code never reads package.json and never sees id or jobject.
Built: ns/AppFiles.h.
namespace nativescript::common {
struct FileInfo {
bool isFile; uint64_t size;
// Changes whenever the bytes may have changed, and identifies the serving
// layer: mtime for a disk layer, APK version for an asset layer. The code
// cache keys freshness on it (B2). Empty: the file never gets a cache.
std::string freshnessToken;
};
namespace platform {
// Logical paths (absolute, as V8 and users see them). Any thread, no Locker,
// bounded time: pool threads call these inside the compile gate that teardown
// drains on the isolate thread.
std::optional<FileInfo> Stat(std::string_view logicalPath); // nullopt: no such file
bool ReadFile(std::string_view logicalPath, std::string& out); // all-or-nothing
}
} // namespace nativescript::common- iOS:
statandread, the wayHelpers.mmdoes it today. - Android:
AppFilesfrom #2104, which serves layers: directory, APK asset and plugin map.
Report B argued file IO could be plain POSIX in the core, which is true on
main. #2104 makes it false: Android sources may come from AAssetManager.
Keeping reads behind this seam is what lets #2104 land without touching the
core, and it gives iOS the same OTA/layering option later for free.
ReadFile must be callable from pool threads, because #622 reads files
off-thread. #2104's AppFiles already is: it is documented "safe to call from
any thread" (AppFiles.h:101), takes a mutex, and makes no JNI upcalls. So pool
threads need no JVM attach.
#2104 does not yet provide this seam:
- No
Stat. It hasIsFile,Open(aReaderwithsize()) andReadText, but no size without opening and no freshness token. It would need to add aStat. - Short reads are not failures. Its
ReadTextreturns true and truncates on a short read (AppFiles.cpp:642-644). The platform adapter has to turn that into a failure. - No directories. It answers files only. #2104 rewrote the Java resolver
to probe files only, while iOS probes directories. So the core CJS resolver
should probe files only, such as
dir/package.jsonanddir/index.js, andStatnever needs a directory answer.
The code-cache file store is not in this seam. It lives in a real writable
directory on both platforms, so the core does it with POSIX: mkstemp + rename,
per-call buffers, all-or-nothing reads. Those helpers are the same algorithm on
both sides today (Helpers.mm ↔ File.cpp). #2104 deletes File.cpp and moves
cache IO into its ScriptCache.cpp, so the core takes that role.
Built: the code cache, in nativescript::common::loader.
ns/loader/CodeCache.h, V8-free and host-tested:- Name:
<codeCacheDir>/<16 hex digits>.mcache(or.cachefor a classic script). The digits are the 64-bit FNV-1a hash of the key. The key is the source's path relative toappRoot, or its absolute path outside it. A relative key keeps names stable when the iOS bundle path changes on an app update. - File: a header (magic
NSCC, format version, kind, key, source size, freshness token, payload length, module format), then V8's cached data. The header must match exactly, so a hash collision reads as a miss. V8 validates its own version and flags. Format version 2 (6.6) added the module format, which records howimporttakes a.jsfile (Q13): an ES module file carrieskEsModuleand its payload; a CommonJS marker carrieskCommonJsand no payload. A classic script's file carrieskNone.FreshModuleFormatreads it from the header alone;LoadCodeCachenever returns a marker. Version 1 files read as stale, so each app recompiles once after the update. CodeCacheEntryFor(path, kind, stat)names the file and records theStatit was decided on. It returns nullopt when caching is off:codeCacheEnabledfalse, nocodeCacheDir, or no freshness token. It takes theLoaderConfigit applies (6.2), the isolate'sLoaderConfigFor.HasFreshCodeCachereads the header only (decide-before-read).LoadCodeCachereturns the whole payload or nothing, checking the header again.WriteCodeCachecreates the directory and renames into place.SourceUnchanged(path, stat)is the B5 re-check: a secondStatafter the read, comparing size and token.PostCodeCacheWritehands the bytes to one serial writer thread (StartThread,kUtility). The writer skips a source that changed.
- Name:
ns/loader/CodeCacheQueue.h:QueueCodeCachedefers creation per isolate (IsolateState), 0.5 s after the last queued cache and then 16 ms apart, throughLoop::PostInternalDelayed.NotifyAppBackgroundedcreates everything queued in one loop task.ns/loader/FileCompile.h:CompileFileEsModuleandCompileFileClassicScript. Each doesStat, thenReadFile, consumes a fresh cache, compiles, and queues creation when there was no cache or V8 rejected it. Only a debug build re-checksSourceUnchangedbefore it consumes the cache (B5). A missing file throwsJsError"Cannot find module", an unreadable one "Cannot read module". A compile error returns empty with the exception pending. The caller passes the script origin (A10) and, for a classic script, the wrapper (A7) as parameters. 6.6 addedCompileFileModule, which picks howimporttakes a file (Q13).
The pool-thread consumer of #622 (step 6) uses the same calls:
CodeCacheEntryFor and HasFreshCodeCache at dispatch, then ReadFile,
SourceUnchanged and LoadCodeCache on the pool, and QueueCodeCache when
it finalizes.
The in-progress #622 port calls stat() on the real path (diff line ~1036).
Under #2104, that would silently send every APK-served .mjs down the inline
path. That is the concrete reason the core must only ever ask Stat.
Built: ns/Loop.h (Loop, PumpMode, PumpResult, platform::LoopFor) and
ns/Deadline.h. The header is normative; in short:
-
each runtime's
EventLoopimplementsLoop; -
PumpUntil(deadline, settled, mode, idle)checks termination, thensettled, then the deadline, before every slice, so termination outranks a state that settled during the slice; -
termination is the loop's flag (set before
TerminateExecution), the isolate terminating, or the loop stopped; -
settledmust not throw or run JS; a caller whose condition can fail records it and throws afterkSettled. Android's TLA probe throws from inside the pump today, which lets a same-slice rejection outrank termination; -
kPlatformWorkis a minimum (Android's set). iOS's CFRunLoop slice also runs non-nestable tasks and bare posts, which the contract allows; -
two waits stay off
PumpUntil: the synchronous HTTP fallback (a blocking wait bounded bywaitBound) and the teardown drain of streamed compiles, which must keep running on a terminated isolate and usesRunNestableV8Tasksdirectly. -
Android has
PumpUntil(deadlineSeconds, settled, drainLooperWork),PumpNestableV8TasksUntil(deadlineSeconds, settled, idle)andIsOnHomeThread()(#2177).PumpModefolds the two pump functions into one. -
iOS has no
PumpUntil. It pumps ad hoc in at least three places:ModuleInternal.mm:1345-1452: TLA evaluation (NSDatedeadline);ModuleInternalCallbacks.mm:2902-2985: the graph walk, withCFRunLoopRunInMode(…, 0.01, true)and, for file jobs only, theFileJobSignalwait;NativeScript.mm:129-212: the boot backstop (CFAbsoluteTimedeadline).
iOS growing this one method is the largest single platform task in this proposal.
-
Deadlines become monotonic everywhere. iOS still uses the wall clock for the TLA and backstop deadlines, so a clock change can stretch or cut short a module wait.
-
The
Post*return type: iOS returnsbooland Android returnsvoid. Unify onbool. -
Engine types stay.
v8::Taskand thev8::Isolate*key are used as is, per "Performance before neutrality" above. Comparing two runtimes for identity across threads still uses an id, because V8 reuses isolate addresses; that is a comparison, not a per-call lookup. -
iOS boot hands off to
UIApplicationMain, which never returns. A JS call to it only queues a task thatTasks::Drain()runs once the boot call has returned, outside the Locker. The core's boot call takes a hand-off predicate instead of a per-slice hook (step 7): it stops pumping when the predicate says the task is queued, so the core holds nothing whenUIApplicationMaintakes over. -
The mode can change between slices. The Android #622 port's outer loop switches modes as pending HTTP fetches come and go (diff ~1437-1448). A fixed mode per
PumpUntilcall is enough.
Built: ns/http/ModuleTransport.h (the seam) and ns/http/ModuleFetch.h (the
loader's API). The cut is at one attempt. The core owns:
- the gate and allowlist, re-checked against the URL a redirect ended at;
- the header set,
User-Agent: NativeScript-HTTP-ESMincluded; - the timeout, retry and deadline policy;
- classification;
- the cache switch and its holders;
- Clear-Site-Data parsing and scope;
- the fetch threads for transports that block, capped per host class.
The transport only performs attempts and stores the cache.
namespace nativescript::common::http {
struct AttemptRequest {
std::string url; // gated, NormalizeHttpModuleUrl spelling, never canonicalized
FetchPath path; // kGraphWalk | kSynchronousFallback (separate connections)
std::chrono::milliseconds timeout; // idle bound, > 0, clamped to the deadline
std::chrono::milliseconds waitBound; // sync only: timeout + 5 s, honoured if cancellable
bool useCache; // sampled once per fetch, when it is issued
std::vector<RequestHeader> headers; // core-built, no-cache pair included when off
};
struct AttemptOutcome {
bool arrived; // status line, and for a 2xx the whole body
int status; std::string contentType, body;
std::string finalUrl; // after redirects, set whenever `arrived`
std::vector<std::string> clearSiteData; // raw; the core parses and applies
bool malformedUrl, waitExpired; // neither is retried
std::string errorDescription;
};
class ModuleTransport {
public:
virtual const char* Name() const = 0;
virtual AttemptOutcome FetchBlocking(const AttemptRequest&) = 0;
virtual bool SchedulesItself() const { return false; } // NSURLSession: true
// Only used when SchedulesItself(); otherwise the core runs FetchBlocking on its
// fetch threads (Android's lanes, moved).
virtual void FetchAsync(AttemptRequest, std::function<void(AttemptOutcome)> anyThreadOnce);
// The retry delay of a self-scheduling transport. Default: one core timer thread;
// iOS overrides it with dispatch_after so each task gets an autorelease pool.
virtual bool PostDelayed(std::chrono::milliseconds, std::function<void()>);
virtual CacheOpResult ClearAll() = 0;
virtual CacheOpResult ClearOrigin(const std::string& origin) = 0;
virtual void OnFetchThreadStart() {} // Android: JVM attach
virtual void OnFetchThreadExit() {} // Android: JVM detach
};
} // namespace nativescript::common::http
namespace nativescript::common::platform {
http::HttpLoaderConfig ReadHttpLoaderConfig(); // once per process, before any cache setter
http::ModuleTransport& HttpTransport();
}- iOS keeps its NSURLSession partitions, NSURLCache generations, launch options and delegate queues inside the transport.
- Android keeps OkHttp, HttpURLConnection, StrictMode and JNI frame handling inside it. Its transport cannot cancel a blocking attempt yet, so its synchronous fallback still has no total-wait bound (D7).
- Both already satisfy this contract (report C §2): completion exactly once, on any thread, possibly inline; never canonicalize; the sync path never shares the walk's connections.
- The retry delay of a self-scheduling transport runs through its
PostDelayed, holding no connection. On the fetch threads it still sleeps, holding the slot for 120 ms (D1, v1).
Built: ns/Thread.h. The core creates the pthread itself (detached, sized,
named) and calls two platform functions: ApplyThreadPriority first on the
new thread (iOS QoS, Android setpriority) and RunJob around each unit of
work (iOS @autoreleasepool). BackgroundCompileStackBytes(v8Flags) sizes a
compile thread from --stack-size on both platforms; iOS currently hardcodes
2 MB and infers --no-lazy from the debug flag.
Both sides run the stream-compile pool on dedicated pthreads. GCD and bionic
default stacks are below what V8's background parser needs. iOS sets
QoS + @autoreleasepool; Android sizes the stack from --stack-size.
The pool itself (grow on demand, gate, drain) moves to the core. #622 already reuses it for file modules. The #622 cache writer is the second user:
- iOS uses a serial UTILITY GCD queue;
- the Android port wrote a
std::thread+ condition-variable writer.
Both become one core serial worker on StartThread.
Built: ns/IsolateStateBag.h (the storage, V8-free) and ns/IsolateState.h
(For, ForExisting, platform::StateBag(isolate)). Each runtime owns one
bag per runtime, reached through an isolate data slot, and closes it at the
end of teardown.
The two contracts differ, and the core can't be written against both.
- iOS
Caches::StateForgoes null at the start of~Runtime(Runtime.mm:318, before the loader quiesce).- The loader therefore reaches for
ExistingStateForduring teardown. - Messaging keeps a process-wide
Isolate*map to get around it.
- The loader therefore reaches for
- Android
RuntimeState::Forstays live until the last teardown statement (Runtime.cpp:1372).
Decided (F1): Android semantics, plus ForExisting for the cross-thread
reads. iOS moves "stop accepting new work" to a separate flag, in its own PR;
iOS adopts IsolateState only after that lands.
| Hook | Why |
|---|---|
LoadNativeModule(path) |
Android .so addons and system_lib:// |
ReportFatalToDeveloper(title, msg, stack) |
iOS error modal |
LoaderConfig::moduleRunScope(name, body, data) (built in step 8, replaces TraceModuleLoad): calls body(data) inside the runtime's per-module scope. The loader brackets each CommonJS module's function call (named by its path) and each ES module evaluation it starts (named by the root's registry key; V8 evaluates the root's whole graph inside it, and a CommonJS module imported there gets a nested scope). Null by default, so a runtime without one pays one pointer test |
Android profiler frames (instrumentation::Frame) and crash breadcrumbs (CrashBreadcrumbs::ModuleScope) |
ExternalMemoryCharge(isolate, bytes) |
iOS charges through its gate id; Android uses v8::ExternalMemoryAccounter. Same V8, so probably the plain accounter for both; needs a check against #507 |
namespace nativescript::common::loader {
// Per isolate
void InstallHostCallbacks(v8::Isolate*); // resolve, import(), import.meta
// Boot (ns/loader/Boot.h). Each throws JsError or Terminated and never
// asserts; whether that is fatal is the runtime's call.
struct BootOptions {
std::function<bool()> handOff; // asked before each slice; null = strict
double deadlineSeconds = kModuleSettleSeconds; // 60
};
enum class BootOutcome { kSettled, kHandedOff };
struct BootResult { BootOutcome outcome; v8::Local<v8::Promise> pendingEntry; };
// The app's ES module main entry: load, evaluate, then pump kPlatformWork
// until it settled and this isolate's graph walks ended, or handOff().
BootResult RunMainEntry(v8::Local<v8::Context>, const std::string& pathOrUrl,
const BootOptions&);
// The same hold after a CommonJS main entry the runtime ran (until step 8).
BootOutcome HoldBoot(v8::Local<v8::Context>, const BootOptions&);
// Worker and tooling entries: a local one returns its pending promise at
// once; an http(s) one is waited for (60 s) and throws.
v8::MaybeLocal<v8::Promise> RunEsModuleEntry(v8::Local<v8::Context>,
const std::string& pathOrUrl);
bool IsEsModuleEntry(std::string_view pathOrUrl); // .mjs or http(s)
bool HasPendingGraphWork(v8::Isolate*); // this isolate's walks
// Evaluation (ns/loader/Evaluate.h, ns/loader/EvaluationPolicy.h)
v8::MaybeLocal<v8::Promise> EvaluateModuleGraph(
v8::Local<v8::Context>, v8::Local<v8::Module>, const std::string& key,
const ModuleEvaluationOptions&);
v8::Local<v8::Object> LoadEsModule(v8::Local<v8::Context>,
const std::string& pathOrUrl,
const ModuleEvaluationOptions&);
v8::Local<v8::Value> RequireEsModule(v8::Local<v8::Context>,
const std::string& path,
const ModuleEvaluationOptions&);
// Teardown (isolate alive, locked, before the loop shuts down)
void Quiesce(v8::Isolate*);
// Lifecycle: any thread. The platform calls it for each runtime it wants
// flushed; today both flush the main isolate only.
void NotifyAppBackgrounded(v8::Isolate*); // flush deferred code caches (#622)
// Workers
LoaderVocabulary CaptureVocabulary(v8::Isolate* parent);
void InstallVocabulary(v8::Isolate* worker, LoaderVocabulary);
// Java-facing resolution (replaces Module.java's resolver)
std::string ResolveMainEntry(); // Module.bootstrapApp
std::string ResolveEntry(const std::string& spec); // Module.resolveEntryPath
// HTTP cache controls (ns:module and the inspector)
void SetHttpCacheEnabled(bool);
void SetHttpCacheDisabledBy(uint64_t holderId, bool disabled); // inspector connection
CacheOpResult ClearHttpCache();
} // namespace nativescript::common::loaderStep 8 (built: 8.1–8.5 core). These replace the
ResolveMainEntry() / ResolveEntry(spec) sketch above, and the
HoldBoot line: RunMainEntry now runs a CommonJS entry too. See §9
step 8.
namespace nativescript::common::loader {
// require() resolution, V8-free (ns/loader/RequireResolver.h)
RequireResolution ResolveRequire(std::string_view specifier,
std::string_view fromDir,
const LoaderConfig&, PackageJsonCache&);
std::vector<std::string> RequireLookupPaths(std::string_view fromDir,
const LoaderConfig&);
std::string RequireErrorMessage(const RequireResolution&);
std::string_view RequireErrorCode(const RequireResolution&);
RequireResolution ResolveMainEntry(const LoaderConfig&, PackageJsonCache&);
RequireResolution ResolveEntry(std::string_view specifier,
std::string_view fromDir,
const LoaderConfig&, PackageJsonCache&);
class RequireResolveCache; // found resolutions by (fromDir, specifier)
// package.json, V8-free (ns/loader/PackageJson.h)
PackageInfo ParsePackageJson(std::string_view text);
class PackageJsonCache; // one Stat per use, read again when it changed
// Per isolate (ns/loader/CommonJs.h)
const RequireResolution* CachedRequireResolution(v8::Isolate*,
std::string_view specifier,
std::string_view fromDir);
RequireResolution ResolveRequireFor(v8::Isolate*, std::string_view specifier,
std::string_view fromDir);
JsError RequireError(v8::Isolate*, const RequireResolution&);
// require() itself (ns/loader/CommonJs.h)
void InstallCommonJs(v8::Local<v8::Context>); // the global require
v8::Local<v8::Function> RequireFunctionFor(v8::Local<v8::Context>,
std::string_view dir,
const ModuleEvaluationOptions&);
v8::Local<v8::Value> RequireFile(v8::Local<v8::Context>,
const std::string& path); // import of CJS
// ns/loader/ModuleIdentity.h: a file: URL's path, virtual roots mapped
// (ns:module's createRequire uses it; require directories are canonical
// paths, never mapped).
std::string FileUrlPathToPath(std::string_view path, const LoaderConfig&);
// ns/loader/RequireResolver.h: the format require() gives a resolved path
// (RunCommonJsEntry dispatches on it).
RequireResolution::Format RequireFormatOf(std::string_view path,
const LoaderConfig&);
// Entries (ns/loader/Boot.h): RunMainEntry takes a CommonJS entry too;
// HoldBoot is gone. A .mjs entry runs as an ES module; a JSON or addon
// entry throws "Cannot run <path> as an entry: it is not a JavaScript
// module".
v8::MaybeLocal<v8::Promise> RunCommonJsEntry(v8::Local<v8::Context>,
const std::string& path);
// CommonJS compile (ns/loader/FileCompile.h)
inline constexpr std::array<std::string_view, 5> kCommonJsParameters;
v8::MaybeLocal<v8::Function> CompileFileCommonJs(
v8::Isolate*, v8::Local<v8::Context>, const std::string& logicalPath,
const std::string& scriptOrigin);
RequiredSource CompileFileForRequire( // the same, or "an ES module" (Q13)
v8::Isolate*, v8::Local<v8::Context>, const std::string& logicalPath,
const std::string& scriptOrigin);
// Import-map scopes (ns/loader/ImportMap.h): now takes the config
std::string ImportMapScopePrefix(std::string_view scopeKey,
const LoaderConfig&);
} // namespace nativescript::common::loader
namespace nativescript::common::platform {
// ns/RuntimeAccess.h: a Node-API name or a native addon path; nullopt when
// the runtime does not load it.
std::optional<v8::MaybeLocal<v8::Value>> RequireNativeAddon(
v8::Local<v8::Context>, const std::string& request,
v8::Local<v8::Object> module);
} // namespace nativescript::common::platformLoaderConfig gains walkNodeModules, globalModuleRoots,
nativeLibraryScheme, nativeAddonExtensions, commonJsThisHasExtends
and the optional hook (§4.8)
// On the isolate's thread, under its Locker; `name` lives until the call
// returns; `body` throws no C++ exception and may leave a V8 exception
// pending. Null for none.
void (*moduleRunScope)(const char* name, void (*body)(void* data),
void* data) = nullptr;CodeCacheKind gains kCommonJsFunction.
ns/loader/Transitional.h is gone: platform::RequireFileForImport and
platform::InstallCreateRequireBinding are no longer up-calls.
Each platform keeps a thin binding layer:
- iOS:
NativeScript.mm, theRuntime.mmboot, and theUIApplicationDidEnterBackgroundobserver. - Android:
com_tns_Runtime.cpp,Module.javaas JNI wrappers, and theonTrimMemoryregistration.
Caveat on method. §4 was written after reading #622, so this is not a blind test. It is a measure of what #622 forced the interface to contain, and of how little of the port would have been platform work.
What the Android port is doing today, from the uncommitted diff (copy in
SHARED_LOADER_CORE.reports/):
- It edits 12 files.
ModuleInternalCallbacks.cppalone is ~1,100 changed lines (insertions plus deletions).- Its substantive added lines, after whitespace normalization and excluding lines under 25 characters, are:
| iOS #622 | Android port | |
|---|---|---|
| substantive added lines | 435 | 520 |
| verbatim in both | 305 | 305 |
| platform calls | 25 (GCD queue, NSNotificationCenter, CFAbsoluteTime, CFRunLoopRunInMode, fopen/fread, Caches::Get) |
36 (std::thread + condition-variable writer, steady_clock, JNI entry, gettid, setpriority, runtime->ReadFileText) |
| new pump primitive | 3 | 26 (PumpNestableV8TasksUntil, IsOnHomeThread) |
| renames and pre-existing divergence | 102 | 153 |
The last row is mostly helper and enum names (TryLoadScriptCache vs
LoadScriptCache, Classic vs kClassicScript, robin_hood vs std::
maps). It also includes #622 being re-threaded through code that had already
diverged, chiefly the dynamic-import() callback: Android's version handles
NUL specifiers and builtins and keeps the real rejection reason, while iOS's
builds generic messages.
A shared core removes that row entirely. Line-set counting is approximate.
| #622 piece | Lands in | Interface need |
|---|---|---|
File jobs (FileModuleJob, FileModuleCompile, fileJobs, fileCompiles) |
core esm/ |
ReadFile (any thread), StartThread |
Walk parking (SyncModuleLoadScope, parkWalksBefore, parkedWalks) |
core esm/ + eval/ |
none |
Async file import() (fileDynamicImports, SettleFileDynamicImport) |
core esm/ |
none |
| Off-thread cache consume (≥256 KiB) and streamed compile (≥32 KiB) | core jobs/ |
StartThread |
Idle wait on FileJobSignal, no microtasks |
core calls PumpUntil(kNestableOnly, idle) |
new pump mode. iOS used CFRunLoopRunInMode + CV; Android added PumpNestableV8TasksUntil |
| Deferred cache creation (0.5 s quiet, 16 ms slices) | core cache/ |
PostInternalDelayed (exists) |
| Off-thread cache write, mtime re-check | core cache/ |
StartThread (replaces GCD queue vs std::thread) |
| Flush when backgrounded | core NotifyAppBackgrounded() |
platform wiring: UIApplicationDidEnterBackground ↔ onTrimMemory(UI_HIDDEN) |
| Republish rejected caches, Debug gate on save | core cache/ |
codeCacheEnabled |
| Eager vs lazy compile | core, from v8Flags |
iOS stops using IsDebug as a proxy |
| Gate-identity stale check on completion | core | LoopFor, IsolateState (no Isolate* identity) |
Verdict: with the core in place, the Android-specific part of #622 would have been:
- the ~35 lines of Java + JNI that register
onTrimMemoryand callNotifyAppBackgrounded(); - once per platform, the
kNestableOnlypump mode (26 lines on Android).
Everything else is core code written once.
#622 is also what forced these parts of the interface into existence. None of them existed in a common form before it:
| Primitive | Before #622 |
|---|---|
PumpMode::kNestableOnly + idle hook |
neither side had it; Android added PumpNestableV8TasksUntil, iOS a CV sleep |
Loop::IsOnHomeThread |
iOS had IsOnRuntimeThread; Android added it for this |
NotifyAppBackgrounded |
new on both |
ReadFile callable from any thread |
both read on the JS thread only |
a serial background writer (StartThread) |
iOS GCD queue vs Android hand-built thread |
FileInfo.freshnessToken |
#622 reads mtime with raw stat |
Each is generic, with no platform concept leaking into the core. So a feature of #622's size costs a handful of small, reusable primitives instead of a 1,000-line port. The next feature that needs a quiet pump or a background writer gets them for free.
Behaviour #622 changes, which a shared landing makes explicit instead of re-porting:
- File
import()stops pumping synchronously. Android main still pumps (ModuleInternalCallbacks.cpp:3830). - The iOS Debug-build cache-writing bug and the "never republish" bug go away.
| #2104 piece | Lands in | Effect on the core |
|---|---|---|
AppFiles layers (directory, APK asset, plugin map) |
platform ReadFile/Stat |
#2104 must add Stat (§4.3) |
/data/data/<pkg> ≡ /data/user/0/<pkg>, applied inside the ESM resolver through AppFiles::ToLogical (ModuleInternalCallbacks.cpp:120, 1518 on the branch) |
core identity | Not platform-only: it changes registry keys. The core needs LoaderConfig.appRootAliases, or one file gets two keys when JS spells the other root |
| Lexical normalization (no symlink canonicalization) | core identity rule | matches the proposed choice (A1), with the alias mapping above |
Cache location code_cache/v8/<hash(logical path)> |
LoaderConfig.codeCacheDir + core naming |
core naming changes for iOS too. Hashed names fix the iOS flattening collision (a/b-c.js ≡ a-b/c.js, ModuleInternal.mm:2008) |
| Header: magic, version, source length + crc32, payload crc32 | core cache/ format |
conflicts with #622's stat-only freshness (decision B2) |
| Republish rejected caches on the CJS path too | core cache/ |
same as #622; converges |
Verdict: #2104 is mostly platform-side. It touches the core in two places: identity (the root alias) and cache freshness.
The freshness conflict is the larger one:
- #622 chooses inline, stream or consume on the isolate thread from
statsize and mtime, before any read, and only then creates the streaming task (ios622ModuleInternalCallbacks.mm:2433-2473). - #2104 validates with the source's crc32, which needs the bytes, and APK assets have no meaningful mtime.
There are two ways out:
- (Recommended)
Statreports a freshness token: mtime on disk, APK version for assets. #622's shape survives unchanged, and the cache header carries the token instead of a crc. - Always read before deciding. This reshapes #622's job: the read moves ahead of the decision, and large files are read on the isolate thread or in an extra pool hop. It needs a cost measurement before it can be chosen.
My estimates from the reports, not measured line by line:
| Pair | Where the change would land |
|---|---|
| #621 ↔ #2176 import() like static import, file-module query identity | all core |
| #620 ↔ #2173 HTTP cache controls | core (switch, inspector holders, Clear-Site-Data) + ClearAll/ClearOrigin per transport |
| #585 ↔ #2172 HTTP cache + persistent connections | mostly transport (legitimately two implementations); timeout, header and retry policy core |
| #587 ↔ #2170 off-thread HTTP compile | all core except thread setup |
| #586 ↔ #2168 resolve against importer URL | all core |
Grouped by subsystem. "Rec" is a recommendation, and every row is your call.
Already agreed, carried over as core invariants rather than re-asked (from the #383/#444 ↔ android#1965/#2021 work):
- The shared terminate rules: termination outranks settlement at every pump head, the termination path always throws, and a module is evicted only while its promise is still pending.
- The three settle policies, with static
createPumpingRequiredefaults and no boot-aware defaults. - No local (non-HTTP) entry waits in place for its top-level await: the main entry boots as a pumping require, and a worker or tool entry returns its pending promise to its own event loop (decided 2026-12-06; this replaced the 1 s local window).
- Failures throw the same way in every build.
- Loader vocabulary is per isolate and copied to workers.
- Import maps are validated in full before they are swapped in.
- The runtime exposes mechanism, never HMR policy.
| # | Question | iOS today | Android today | Rec |
|---|---|---|---|---|
| A1 | Path normalization for registry keys | Foundation stringByStandardizingPath (strips /private) |
ESM lexical; CJS Java getCanonicalPath (realpath); #2104 makes all lexical |
Decided 2026-12-05: lexical everywhere. Normalize the app root once at the boundary |
| A2 | file:// with #, %, spaces |
NSURL (# is a fragment) |
verbatim (# stays in the path) |
Decided 2026-12-05: not NSURL: URL work in the core goes through the vendored ada parser (standing rule). A1 and A2 are the start of the deferred "canonical identity" sweep, so the HTTP-authority caveat from #586 still applies |
| A3 | file:// to absolute device paths |
everything mapped under the app root | allowed | Decided 2026-12-05: allowed (Android, Node and browser semantics). An absolute file:// path loads that file |
| A4 | CJS bare-name precedence | tns_modules/<n> first, then tns-core-modules/<n> |
tns-core-modules/<n> first, then node_modules walk |
Decided 2026-12-06: Node order. node_modules from the requiring file's directory up to and including <appRoot>/node_modules (up to / for a file outside the app root), then the legacy roots as config (globalModuleRoots): <appRoot>/tns_modules, then <appRoot>/tns_modules/tns-core-modules |
| A5 | node_modules walk on iOS |
none (5 shared specs xit) |
yes | Decided 2026-12-06: turn on through walkNodeModules (core config only); the xits become the acceptance list |
| A6 | Package main pointing at nothing |
returns the missing path | falls back to index |
Android (Node) |
| A7 | CJS wrapper prologue | 61 chars ) { |
60 chars ){ |
Decided 2026-12-06: no text prologue. Compile with ScriptCompiler::CompileFunction and Node's parameters (exports, require, module, __filename, __dirname), so line-1 columns are exact, under a new code-cache kind and format version. Every classic cache is rejected once. If V8's code cache or the inspector's script reporting does not work for such a function, fall back to one text prologue for both. Neither side corrects error-stack columns for the prologue today; only Android's extend() class naming (MetadataNode) subtracts it |
| A8 | import.meta.dirname |
file modules only (#614) | always | Decided 2026-12-05: iOS (file modules only, as in Node) |
| A9 | Import-map targets naming builtins, blob: resolution kind |
yes | no | Decided 2026-12-05: iOS |
| A10 | Script origins and import.meta of app files |
file:///app/<rel> for both (BaseDir stripped) |
file://<absolute path> for both |
Decided 2026-12-05: see "App origins" below |
App-root forms and .. (A1, A3). A ~/, root-absolute or bare
specifier names a path below the app root, so its tail is normalized as an
app-root-relative path first, a .. at the root dropped as at a URL's root,
and only then prefixed with the app root: /../../etc/x.mjs,
~/../../etc/x.mjs and lib/../../../etc/x.mjs all name
<appRoot>/etc/x.mjs, as /etc/x.mjs does. A root-absolute path already
under the app root is kept as it is (Q7). Only a relative specifier, joined
with its importer's directory, and an absolute file:// URL (A3) reach
files outside the app root.
App origins (A10). A script origin (stack traces, DevTools, error
messages, crash reporters) and import.meta serve different readers, so the
core spells them separately:
- Origin of a file under the app root:
LoaderConfig.appRootOrigin+/+ the path relative to the app root. The core default isapp://, givingapp:///foo.mjs. A scheme cannot collide with a real path on any OS (a Linux runtime can have a real/app). It stays the same across installs and platforms, which keeps crash-reporter grouping stable (Sentry matches it as~/foo.mjs, React Native's convention). DevTools also loads the side resources of a non-file:script, such as a relative source map, through the target, with nosourceMapURLrewrite. - Origin of a file outside the app root:
file://<absolute path>. import.meta.url,.filename,.dirname: the real absolute path, sofileURLToPath(import.meta.url) === import.meta.filenameholds as in Node, and the values work with file APIs and with absolutefile://imports (A3).- Resolver aliases:
app:///<rel>always resolves to the app root, so code written for the new scheme works whatever a platform reports. One function in the core maps an origin back to a path, for both the resolver and the inspectors'loadNetworkResource.
Rollout. Each platform keeps today's behaviour by default and offers an
opt-in app config flag, appSchemeOrigins: true (named and wired in 6.6),
that removes its override:
- iOS:
appRootOrigin = "file:///app",import.meta= the origin, and the/app/resolver alias stays. - Android:
appRootOrigin = "file://" + appRoot,import.meta= the origin.
The flag switches to the whole model above: origins and import.meta
together. The LoaderConfig defaults are that model, so the core has no code
for the flag: a runtime that reads it set skips its appRootOrigin and
legacyOrigins override. The virtual roots stay either way (Q10). Once
plugins and tools that parse stack traces handle app:///, the default flips
(or the override is kept), decided then.
| # | Question | Rec |
|---|---|---|
| B1 | Cache on by default in release? iOS yes, Android opt-in (android.codeCache) |
Keep it per platform as LoaderConfig.codeCacheEnabled. Note that unification makes it trivial to flip Android's default later |
| B2 | Freshness: mtime stamp (main, #622) vs source length + crc32 header (#2104) | Decided 2026-12-05: a header with a version and source length on both, plus a per-source freshness token from Stat (mtime on disk, APK version for assets) instead of crc. #2104 adapts to it. No payload checksum: atomic rename plus the exact-size check guard the file, as both runtimes' main do today |
| B3 | Land the cache in #622's shape (deferred creation, off-thread write, republish on reject) | Yes, as both investigations concluded |
| B5 | Re-check freshness after reading the source (Android's cacheMatchesBody) |
Decided 2026-12-05: yes. V8 checks a cache only against the source's length, so a same-length change between the dispatch-time Stat and the read would consume a cache that describes other bytes. One extra Stat per cached load, on the pool thread. The inline compile (CompileFile*) re-checks only in debug builds, so a Release boot pays no extra Stat on the isolate thread |
| B4 | Naming: flattened (iOS) / beside the source (Android main) / hashed (#2104) | Decided 2026-12-05: hashed under codeCacheDir, keyed by the path relative to appRoot (the absolute path outside it), so names survive the iOS bundle path changing on update. #2104 adapts to it |
| # | Question | Today | Rec |
|---|---|---|---|
| C1 | Pumped graph wait when terminating | iOS: return false; Android: return *done (ModuleInternalCallbacks.cpp:2427-2433); one of its three callers re-checks termination itself (ModuleInternal.cpp:1466) |
Already settled. The shared terminate rules agreed on 2026-08-19 (#383/#444 ↔ android#2021) say termination outranks settlement at every pump head. Android has regressed; fix it now (§8) |
| C2 | LoadESModule after a terminated pump |
iOS throws "interrupted by isolate termination"; Android returns the namespace | Same rule: "the termination path always throws". Android regressed |
| C3 | Deadline clock | iOS wall clock; Android steady_clock |
steady_clock |
| C4 | File import() pumping |
#622: async; Android main: sync pump | #622 |
| C5 | Boot backstop: rejection on the first poll | Android fatal; iOS not | Decided 2026-12-05: Android. Step 7 replaced the backstop: boot is a pumping require of the main entry that throws on any rejection, and each runtime makes that fatal |
All ten as report C recommends, built in ns/http/:
| # | Decision |
|---|---|
| D1 | The retry delay runs off-thread on a core timer for self-scheduling transports. Fetch threads sleep through it for now. |
| D2 | Queue time counts against the deadline: each attempt's timeout is computed when it starts. |
| D3 | The cache switch is sampled once per fetch, when it is issued; a retry reuses it. |
| D4 | Clear-Site-Data clears the response's origin plus the fetching origin, each once, before the fetch is reported. |
| D5 | Failed cache clears are reported (CacheOpResult). JS throws and the inspector answers -32000. |
| D6 | Cache holders are a set keyed by an opaque id (SetModuleHttpCacheDisabledBy), idempotent per id. |
| D7 | The sync fallback's total wait is the attempt timeout + 5 s. Android cannot cancel an attempt yet, so its wait stays unbounded until its transport can. |
| D8 | User-Agent: NativeScript-HTTP-ESM on both. |
| D9 | Deadlines are optional<steady_clock::time_point> everywhere. |
| D10 | The gate is re-checked against the final URL after redirects. A transport that does not report it fails closed while an allowlist is in force. The redirect is still followed first, so the request reaches the target before the check. |
Also: a transport error is a response that did not arrive (Android's rule): a status-bearing answer never is, unless it is a 2xx whose body failed.
- Shared code throws JS errors in every build, per the standing "same errors
in Debug and Release" rule. It never uses
tns::AssertorNS_CHECKfor anything JS can reach. - One
JsErrorvalue type (message, stack, name,ThrowToV8). Each platform'sNativeScriptExceptionwraps it.
| # | Question | Options | Rec |
|---|---|---|---|
| F1 | Per-isolate state contract | iOS early-null vs Android live-until-last | Decided 2026-12-05: Android's (live until the last teardown statement, plus a separate stop-accepting-work flag) + ForExisting. The iOS teardown change lands as its own PR before the core relies on it |
| F2 | Seam style | link-time functions / virtual interfaces / mixed | Mixed, as in §4.1 |
| F3 | Packaging | A submodule NativeScript/runtime-common / B vendored copy + CI staleness check / C monorepo |
Decided 2026-12-04: A, this repository, private for now |
| F4 | Same-PR parity | must every core change build both runtimes before merge? | Yes for the core: its CI builds both runtimes at their main |
| F5 | iOS source registration | synchronized folder group (objectVersion 77) / static-lib target | Static library with its own strict flags and no header map. At the project's current objectVersion 55 the target still lists each source file; zero per-file churn needs the synchronized-folder format, which is a separate project-format bump |
| F6 | Order relative to #622 | extract the core first, then land #622 once / land #622 on both, then extract | Second: the Android port is already in progress and is 70% a verbatim re-port. Extract from the post-#622 state; that is the baseline both sides converge on anyway |
| F7 | C++ namespace | top-level ns:: / nativescript::common:: |
Decided 2026-12-05: nativescript::common, subdivided by component; see "Layering and direction" |
On packaging (F3):
- Submodule is how the shared tests already work, and the record is instructive. In the window the pointer moved in only 2 of 30 paired PRs, and it hid 55 days of skew instead of exposing it.
- Vendored copies recreate exactly today's drift mechanism, since people
patch the copy. ada and
robin_hood.halready show independent fixes to the same warning. - A monorepo is the only option that makes drift impossible, and the
largest migration: history, PR numbering,
scripts/changelog.mjs, npm publishing, and two CI runners.
My recommendation is a submodule plus a core CI that builds both runtimes
(macOS + NDK) on every core PR, and a required check in each runtime that its
pin is not behind core main by more than N commits. A monorepo is worth
revisiting once the core is most of the code.
Most existed on one side only. Rechecked on 2026-12-05 against both
runtimes' main and the draft adoption PRs (iOS #625, Android #2179); line
numbers refer to those. "Fixed by" names the §9 step that retires the code
when the fix does not come sooner: fixing it once in the core beats fixing it
twice in place.
Open
| Side | Bug | Where | Fixed by |
|---|---|---|---|
| Android | The sync HTTP fallback has no total-wait bound. The core passes waitBound, but the transport cannot cancel an attempt, so a trickling body can hold the JS thread |
HttpLoader.cpp transport |
in place: OkHttp callTimeout or a watchdog calling Call.cancel() / disconnect() (D7) |
| Android | Module.java resolution keeps mutable statics with no locking (possibleException, checkForExternalPath, folderAsModuleCache). After an IOException in the helper, file is null and file.getCanonicalPath() throws an NPE |
Module.java:23-27, 85 |
step 8: the CJS resolver moves to the core |
| iOS | Cache-name flattening collides (a/b-c.js vs a-b/c.js). With 1 s mtimes and V8 not hashing content, a same-length collision could load the wrong code (risk, not reproduced) |
ModuleInternal.mm GetCacheFileName |
step 4 once adopted: hashed names, and the header holds the key |
| iOS | Calling-dir check substr(0,4) == "/app" also rewrites /apple/..., through createRequire too |
ModuleInternal.mm:548 |
step 8 |
| iOS | require("./") from any module loads the app's main entry instead of the calling directory as a package |
ModuleInternal.mm:554 |
step 8 |
| both | "main": "." (or "./", "") in a package.json recurses without end: iOS reads the same package.json again, Android loops through loadAsDirectory. Node resolves it to ./index.js (by reading) |
iOS ModuleInternal.mm:1773-1778; Android Module.java:270-274 |
step 8: main naming a directory loads its index and never reads a nested package.json |
| Android | ~/x builds <appRoot>//x: APP_ROOT_FOLDER_PATH ends in / and the resolver appends "/" + tail. For .mjs the doubled string is the path and the registry key |
ModuleInternal.cpp:743, Runtime.cpp:238 |
step 8 |
| Android | A bare-name require-cache key ignores the requiring directory, so two packages with different nested node_modules/<n> get whichever loaded first |
ModuleInternal.cpp:720 |
step 8: keyed by directory and specifier |
| both | A CommonJS file reached through require() and through import can run twice. The require cache keys by the platform's normalizer: iOS Foundation stringByStandardizingPath, which resolves a symlink followed by .. and keeps /private for a path that does not exist; Android Java getCanonicalPath, a realpath. RequireFileForImport keys by the core's lexical canonical path, so a file whose two spellings differ misses and runs again. Only on the adoption branches: before 6.6, import never shared the require cache |
iOS ModuleInternal.mm:648, 681; Android ModuleInternal.cpp:385, 771, Module.java:85 |
step 8: one canonical require-cache key |
| core | The classic code cache's header and name do not record the wrapper prologue, and V8 checks a cache only against the source length, so a same-length prologue change would consume caches compiled for other positions (latent) | CodeCache.cpp header, FileCompile.cpp |
step 8: a new cache kind and format version with A7 |
| iOS | File import() evaluation failure rejects with a generic "Evaluation failed" Error and drops the V8 exception |
ModuleInternalCallbacks.mm:3829 |
step 6.5 once adopted (built: "Evaluation failed for module: — ") |
| iOS | tns::ReadText aborts the process (Assert → Fatal) when a file it was told exists can't be opened; reachable from ES-module compiles, JSON modules and require() of a .json file (LoadData, ModuleInternal.mm:902) |
Helpers.mm:110-114 |
step 4 once adopted for compiles (CompileFile* throw "Cannot read module"); step 6.5 once adopted for JSON modules (built: platform::ReadFile, Error "Cannot read module "); step 8 for require() |
Fixed
| Side | Bug | Fixed in |
|---|---|---|
| Android | LoadESModule returned the namespace after the graph-walk pump reported termination |
main: returns empty (ModuleInternal.cpp:1479, 1557) |
| Android | URL hash accessor registered twice |
android#2180 |
| iOS | ReadModule ignored read()'s result, so a short read compiled uninitialized bytes |
ios#626 |
| iOS | Wrote ES-module code caches in Debug builds; never republished a rejected cache | #622 |
| iOS | Graph-walk and HTTP fetch deadlines used wall-clock CFAbsoluteTime |
iOS #625 (steady_clock) |
| both | The remote-module gate and allowlist were not re-checked after a redirect | core #2, adopted by iOS #625 and Android #2179 |
| Android | The pumped graph wait returned *done on termination, and its callers returned empty without throwing |
android#2179 |
| Android | A terminated top-level-await pump let LoadESModule return the namespace |
android#2179 |
| Android | The entry Load discarded an empty LoadESModule result |
android#2179 |
| iOS | The top-level-await deadline was wall-clock (NSDate) |
ios#625 (Loop::PumpUntil) |
| iOS | The boot backstop deadline was wall-clock (CFAbsoluteTime) |
ios#625 (Loop::PumpUntil) |
| both | import() of a module whose evaluation was on the stack (a self-import, or a cycle back to a module being evaluated) hit V8's CHECK in Module::Evaluate |
core fix/evaluating-import (settles after the evaluation, §9 6.5), once adopted |
| both | import() once loader::Quiesce had run returned an empty promise with no exception pending, and V8 aborted the process in Isolate::UnwindAndFindHandler |
core 6.5 (decided 2026-12-05: a promise that never settles), once adopted. A runtime wrapper that checks its own teardown state first must return such a promise too |
Each step is suite-green on both platforms on its own. The shared
common-runtime-tests-app suite is the conformance test.
The core also gets host-side unit tests, built with macOS and Linux clang using the core's flags, for the pure parts:
- canonicalization;
- classification;
- import-map parsing and resolution;
- the CJS resolver against a fake
Stat/ReadFile; - retry and deadline policy against a fake transport;
- cache naming and freshness.
These are cheap and catch most port-style regressions without a device.
-
Fix the §8 bugs marked "in place", one small PR per side. The others go away with the step named in their row.
-
Plumbing, proven on leaves.
- Create the core repo and wire both builds: an Android CMake subproject and an iOS static-lib target.
- The core gets its own flags, written to the stricter side: C++20,
-fno-rtti, exceptions,-Wall -Werror -Wshorten-64-to-32, and V8 deprecation warnings on. - Use a unique include root (
#include "ns/…"). iOS header maps resolve by basename, so a sharedEventLoop.hnext to a platform one would be picked silently. - Prove it on one slice whose include closure is V8 and std only: the
base64 codec and the atob/btoa natives (
ns/Base64.h,ns/Base64Binding.h). Each runtime keeps itsBase64.cppfor the builtin wiring (BuiltinLoader,SetMethodNoSideEffect). - The other units that looked identical are not leaves.
NativeScriptPlatformconstructs and calls the platformEventLoop, so it moves with step 3.ModuleBindingcarries a per-platform binding list, so it needs that list injected first.
-
Foundation headers and platform basics, scoped by what the code moving in steps 4–8 uses:
ns/V8Helpers.h,ns/Trace.h,ns/JsError.h,ns/Deadline.h,ns/IsolateState.h,ns/LoaderConfig.h,ns/Thread.h,ns/V8Flags.h,ns/Utf8.handns/RuntimeAccess.h(IsRuntimeAlive,MainContext).ns/Check.hwaits for a first caller. The runtimes implement the platform functions; their own code keeps its helpers until it moves. The iOS teardown change (F1) goes in as its own PR.Before the core throws
JsError, every platform catch ladder learnscatch (JsError&)andcatch (Terminated&)ahead of its generic clauses: iOSRequireCallbackandRunMainScripthave nocatch (...), so an unknown type ends instd::terminate. -
Loop interface. Both
EventLoops implementLoop. iOS gainsPumpUntilwith the three modes, replacing its three ad hoc pumps, and its deadlines go monotonic; the 1 s local TLA window stays separate from the 60 s one. Android foldsPumpNestableV8TasksUntilinto it and moves its TLA probe's throw after the pump. -
Code cache + file seam, in #622's shape, with B2/B4 as decided (#2104 adapts to it). The ESM core calls
CompileFileEsModule, so it has to move before step 6. Built in the core (§4.3); the runtimes adopt it next:- Both: implement
platform::Statandplatform::ReadFile. SetcodeCacheDirto a directory of the cache's own. ReplaceLoadScriptCache/TryLoadScriptCache,QueueScriptCache,FreshScriptCachePathandReadBinary/WriteBinarywith the core's calls. CallCompileFile*with today's origin and wrapper. Have the background hook callNotifyAppBackgrounded(isolate). - iOS: the token is the source's mtime. The
UIApplicationDidEnterBackgroundobserver moves to the platform. Before usingIsolateState, it needs the F1 teardown change. - Android: the token is the mtime on disk; with #2104, the APK version
for asset layers.
codeCacheDiris new on Android, which writes caches beside the source today. The debug LiveSync lock thatRuntime::ReadFileTexttakes per runtime becomes one process-wide lock, debug only, taken inside Android'splatform::ReadFile. The core has no hook for it. - Old cache files (iOS's flattened names in
Caches, Android's.cache/.mcachebeside the sources) are never read again. Delete them once.
- Both: implement
-
HTTP policy core +
ModuleTransport. NSURLSession and OkHttp move behind the interface; the lanes move into the core. -
ESM core (
ModuleInternalCallbacks). The largest step, landed as six units in the order below. Each one is suite-green on both platforms on its own, and each runtime deletes its copy of the unit in the same adoption. Baseline: both runtimes'feat/runtime-commonbranches (steps 1–4 adopted). #622 is on both sides there: file jobs, walk parking and asynchronous fileimport(). Both pumps already run throughLoop::PumpUntil, and both return false on termination.Three calls cross from the callbacks into each runtime's
ModuleInternal:InstallCreateRequireBinding(context, binding), from thens:modulebinding (6.6);EvaluateModuleGraph(…, kSyncStrict), from the require(esm) facade (6.6);ModuleInternal::CompileFileEsModule(isolate, path, query), from the walk and the static resolver. It is the runtime's wrapper around the core'sCompileFileEsModule, and it adds the origin and, on iOS, the CommonJS wrap for a.jsfile. 6.4 and 6.5 retire it: the core passesModuleOrigin, and the wrap follows Q13.
The first two stay until steps 7–8. They are declared in
ns/loader/Transitional.h, which each runtime implements, so they are deleted on purpose. The third goes there too if Q13 is still open when 6.4 lands.As built: 6.4 retired the third into
platform::FileModuleSourceWrap, and 6.6 deleted it:importtakes a file as an ES module or as CommonJS, never wrapped. 6.6 never added the second: the core evaluates the facade itself, so the facade needs no up-call. Q13 addedplatform::RequireFileForImport. The two left (InstallCreateRequireBinding,RequireFileForImport) go with step 8's CommonJS core.LoadESModuleis not an up-call. The callbacks never call it. It isModuleInternal's driver of the walk (SyncModuleLoadScope,RunModuleGraphLoadPumped,LoadHttpModuleForUrl,ResolveModuleCallback), and it calls the core's API once 6.4 lands. It moves with step 7.Until a unit lands, the runtime code that is still local calls the core units that already moved. Each unit below lists that surface.
6.1 Module identity. V8-free, in
ns/loader/ModuleIdentity.h. Built (see "Built" below).-
Core API:
NormalizePath(A1);ModuleQuery;KeyPath;CanonicalizeModuleKey;ModuleOriginandReportedModuleUrl, the A10 origins;ImportMetaFor, theimport.metastrings;OriginToPath, the inverse ofModuleOrigin;FileUrlToPath, afile:orapp:URL the runtime did not write (A2, A3).
None of them read a global config. Each takes the
LoaderConfigit applies. -
Config:
LoaderConfiggainsappRootOrigin(defaultapp://),legacyOrigins,appRootAliasesandvirtualFileRoots(§4.2).reportedPathPrefixgoes once both runtimes have adopted this unit. -
Platform:
platform::ParseUrl, WHATWG parsing through each runtime's ada (Q12). -
Runtimes delete:
- from
ModuleUrl:ReportedModuleUrl,ModuleQueryandFileModulePath; - iOS
NormalizePathandFileURLToPath, which are Foundation code; - Android
NormalizeDotSegments; - the bodies of
CanonicalizeRegistryKey. iOS keeps a wrapper for itsfilePathByKeyshort-circuit until 6.2; - the string work in both
import.metacallbacks; - the path mapping in both inspectors'
loadNetworkResourceand source-map rewrite, along with iOS'sBaseDircandidates.
- from
-
Settles:
- A1: lexical everywhere, with the app root's spelling fixed through
appRootAliases; - A2: the
file://branch of canonicalization goes through ada; - A8 and A10: the strings.
Under each platform's override (
legacyOrigins), every origin andimport.metastring stays byte-identical to today, except Q5. - A1: lexical everywhere, with the app root's spelling fixed through
6.2 Loader state and the registry. Built (see "Built: 6.2" below).
-
Core API:
- a core
ModuleLoaderStateinIsolateState, holding the registry, the module → key index and iOS's key → path record; SetRegisteredModule(key, module, path)as the only write. It unindexes the previous occupant;RemoveModuleFromRegistry,FindKeyForModule,ModuleFilePathForKey,GetLoadedModuleUrlsandInvalidateModules;- the per-isolate config snapshot (see "Liveness and config snapshot" below);
- a
closingflag thatloader::Quiescesets first. This is F1's "stop accepting new work", owned by the core, which replaces iOS'sCaches::IsTearingDowntest inModuleLoaderStateFor.
- a core
-
Platform:
platform::LoaderSnapshot()replacesplatform::Loader(). -
Still local: the walk, file jobs and vocabulary keep the runtime's own loader state and reach the registry through the core API. Both
ModuleInternals callSetRegisteredModuleandRemoveModuleFromRegistry. -
Runtimes delete:
- the registry,
keysByModuleHash,filePathByKeyandrequireFacadesByTargetHashfields, with theIndex/Unindexhelpers,DropRequireFacadesForTargetandModuleRegistryFor; - Android's open-coded unindex sites (seven);
IndexModuleForIsolate,UnindexModuleForIsolate,SetRegisteredFileModuleand the bodies ofFindKeyForModule,GetLoadedModuleUrlsandInvalidateModules.
RemoveModuleFromRegistryshrinks to the file-job step around the core's. - the registry,
-
Settles:
- the write-path shape (iOS's);
- Q6.
It also covers iOS
ModuleInternal.mm:1561. That line looks as though it overwrites a key without unindexing it when the entry there is still evaluating, because such an entry is neither reused nor removed. This is from reading the code, not a reproduction.
6.3 Vocabulary, import maps and the resolver. Built (see "Built: 6.3" below). Policy is V8-free; the JSON parse is in a V8 file.
- Core API:
LoaderVocabulary;ParseImportMapthroughv8::JSON::Parse, validated in full before install;LookupImportMap(map, spec, referrerPath), which takes the map explicitly (Android's shape);CaptureLoaderVocabularyandInstallLoaderVocabulary, whichWorker.mmandWorkerWrappercall;ResolveSpecifier(spec, referrer, vocabulary, config, ImportMapLookup), returningModuleResolutionwithkBuiltin,kHttp,kFile,kBloborkUnresolved. It probes files only, throughplatform::Stat, and builds the sameattemptedtext, which the tests pin.
- Platform:
- none for builtins:
IsBuiltinModuleSpecifier(spec)is a core prefix check, since both runtimes' scheme tests are the same. Each runtime keeps itsNsBuiltinModulesrows; - the ada-backed helpers the resolver calls,
ParseModuleUrl(authority as written) andBlobStoreUrl. They move fromModuleUrlto platform functions besideNormalizeHttpModuleUrluntil Q12.ParseModuleUrlneeds component offsets thatUrlPartsdoes not expose.
- none for builtins:
- Runtimes delete:
- both resolvers and both import-map parsers, including iOS's
NSJSONSerialization; ImportMapScopePrefix.
- both resolvers and both import-map parsers, including iOS's
- Settles:
- A3: an absolute
file://path loads that file. The iOS expectation atDynamicImportTests.js:159flips; - A9: builtin targets,
kBlobandkSkip; - A10:
app:///always resolves to the app root; - A1: the relative join is lexical;
- Q7–Q10.
- A3: an absolute
6.4 Graph walk, file jobs and the stream-compile pool. These land together. The walk dispatches file jobs to the pool, and parking ties the jobs to
SyncModuleLoadScope.-
Core API:
StartModuleGraphLoadwith the typedModuleGraphRoot(iOS's);RunModuleGraphLoadPumped,SyncModuleLoadScope,HasPendingGraphWorkandLoadHttpModuleForUrl;loader::Quiesce, which kills walks and file jobs (marking jobssuperseded, as Android does) and then drains the pool underSuppressMicrotaskExecutionScopeandDisallowJavascriptExecutionScope(invariant 11);- the pool on
StartThread,BackgroundCompileStackBytesand the eager option fromV8FlagsDisableLazyCompile; - file jobs, through
CodeCacheEntryFor,HasFreshCodeCache,SourceUnchanged,LoadCodeCacheandQueueCodeCache; - the liveness token (see "Liveness and config snapshot").
-
Platform: none new. Q15 settles the external memory charge.
-
Transitional: if Q13 is still open,
CompileFileEsModule'sSourceWrapfor a.jsreached throughimportcomes from aTransitional.hup-call (it was; 6.6 settled Q13). -
Runtimes delete:
StreamCompilePool,StreamFeedandBodySourceStream;FileModuleJoband its functions;AsyncGraphLoadand both copies of the walk.
LoadESModulecalls the core. -
Settles:
- the monotonic start stamp;
- Android's drain scopes,
supersededon kill, and its home-thread check before waiting on file jobs; - Q13 and Q14, the two items carried over from step 4.
The pool keeps the
SourceUnchangedre-check unconditionally.
6.5 Static and dynamic import, JSON modules. Built (see "Built: 6.5" below). (Found in 6.4: both runtimes build a JSON module as
"export default " + text + ";", so a served body is compiled as JavaScript, not validated as JSON. 6.5's JSON module should parse it withv8::JSON::Parseinto a synthetic module.)- Core API:
ResolveModuleCallback,ImportModuleDynamicallyCallback,FinishHttpDynamicImportand the settling of a fileimport();- blob
import(); - the dynamic-import waiters and
BuildModuleFailureReason; - JSON modules.
- Platform: a blob-store lookup. Today it is per runtime, beside
URL.createObjectURL. - Runtimes delete: both callbacks and
DynamicImportReferrerKey. - Settles:
- A9: builtins are matched after the single resolution (iOS);
- invariant 19: Android's rejection reasons. This fixes the §8 iOS "Evaluation failed" bug and iOS's generic blob failure messages;
Then(...)throughFromMaybe;- the referrer is read with
OriginToPath; - JSON modules read through
platform::ReadFile. This is the step 4 carry-over and retires iOStns::ReadTextfor modules.
6.6
import.meta, the require(esm) facade andns:module.- Core API:
InstallHostCallbacks(isolate), which installs the resolve,import()andimport.metacallbacks;InitializeImportMetaObject, built onImportMetaFor;GetOrCreateRequireFacade;- the
ns:modulebinding, with Android's C++ exception barrier on every callback and its rejection of a function-valuedimportMap.
- Transitional: both up-calls named above.
- Runtimes delete: both
import.metacallbacks (iOS's is inRuntime.mm), the facade, andBuildNsModuleBinding. - Settles:
- A8;
- wiring the
appSchemeOriginsapp-config flag on both platforms; - Q11, Q16 and Q17.
Built (see "Built: 6.6" below), with Q13.
Liveness and config snapshot. Decided 2026-12-05: both are accepted as written here. The core needs them before it posts work that outlives a call, so the snapshot lands with 6.2 and the token with 6.4. 6.1 needs neither.
-
Liveness (6.4). Today both
IsRuntimeAliveimplementations read the isolate's data slot. That read is itself a use-after-free once the isolate is disposed, and Android never clears its slot. The core never callsIsRuntimeAlive. Background work instead holds two things, captured on the isolate thread when the work is dispatched:- a liveness token:
std::shared_ptrto a coreRuntimeLiveness { std::atomic<bool> alive; std::weak_ptr<Loop> loop; }, created when the loader is installed and set false first thing inloader::Quiesce; - the loop's
weak_ptr.
A completion posts only while
alive, through theweak_ptr, and re-checksalivewhen it runs on the isolate thread before it touches the isolate. No isolate address is ever dereferenced or compared.Step 4's code-cache code splits two ways:
- Tasks that
CodeCacheQueueposts to the isolate's own loop keep their[isolate]capture. They run only on that loop, and the loop is shut down before the isolate is disposed. NotifyAppBackgrounded(isolate)is called from any thread and looks the loop up by isolate. It moves to the token: the platform holds the main runtime's token and passes that instead.
The existing
load->deadflag andStreamCompileGateidentity are two ad hoc copies of this pattern, and the token replaces both. A gate-id registry would also work, but it costs a lookup under a mutex on every check and still needs the id captured at dispatch.IsRuntimeAliveleavesns/RuntimeAccess.h.MainContextstays, for the isolate thread. - a liveness token:
-
Config snapshot (6.2).
platform::Loader()becomesstd::shared_ptr<const LoaderConfig> platform::LoaderSnapshot(). iOS'sRefreshLoaderConfigpublishes a new snapshot withstd::atomic_storeinstead of rewriting the static in place. (The free functions compile clean under C++20 on Apple clang 17 and NDK 27 and 29; libc++ has nostd::atomic<std::shared_ptr>.) The core copies the snapshot into the isolate's loader state when the loader is installed. A worker takes its parent's snapshot, as it does the vocabulary. Every core reader uses the per-isolate copy:CodeCacheEntryFor,FileCompile's debug check, and the identity functions' callers. A worker of the previous run then keeps that run's values, and no thread reads a struct that is being rewritten.
Decisions. Every question below was decided on 2026-12-05. Q1–Q5, Q12 and Q18 shape 6.1 and are built. The others are applied by the unit named in each.
-
Q1. Legacy round trip. Legacy origins spell the path verbatim, so a file whose name contains
#or a%XXsequence does not survive A2's ada parse. The options were to accept that, to percent-encode legacy origins too (which changes today's stack text), or to read the runtime's own strings back verbatim.Decided (c): strings the runtime minted (the
import()referrer, inspector URLs) are read back verbatim in legacy mode, and everything else goes through ada.OriginToPathis that inverse. Node never parses its CommonJS frame paths as URLs either, and a legacy origin is a path written infile://syntax, not a URL.A runtime-minted origin can also come back through JS, as
invalidateModules(import.meta.url)does. So underlegacyOriginsthe registry reads afile:URL back verbatim first (OriginToPath, with the query kept as written) and uses that key when it names a registered module. Any other string still goes through ada.RegistryKeyFor,RemoveModuleFromRegistryandInvalidateModulesall go through this (RegistryTable::CanonicalKey). Opt-in mode needs none of it: Q2 encodes its origins, and ada round-trips them. -
Q2. Encoding in opt-in mode. Decided: opt-in origins and
import.meta.urlare percent-encoded as Node'spathToFileURLdoes, andimport.meta.filenameis the decoded path. A10'sfileURLToPath(import.meta.url) === import.meta.filenameholds only this way.ModuleOrigindoes it. -
Q3. Hosts and encoded separators in a
file://URL. Today Android drops the host, and iOS's resolver reads it as a path segment under the app root.Decided (b), strict.
FileUrlToPathrejects:- a host other than empty or
localhost; %2Fand%5C, in either case. Node's ESM resolver rejects both withERR_INVALID_MODULE_SPECIFIER;%00. This is stricter than Node, which does not reject NUL by name but can never load such a path.
The runtime's own
node:urlfileURLToPathalready rejects hosts and%2F.OriginToPathreads strings the runtime minted, so it still decodes%5C: a file whose name contains\keeps its inspector URL andimport()referrer, but, as in Node, it cannot be imported through its own opt-inimport.meta.url. - a host other than empty or
-
Q4.
ModuleQuerywhen the parser rejects the specifier. Decided: iOS's fallback, which keeps the text from?to#, so two queries stay two modules. That is #621's stated intent, and the #2176 port dropped it. Android changes. -
Q5. iOS files in the bundle but outside the app root. Under the iOS override, their origin changes from
file:///<path relative to the bundle>tofile://<abs>, which is what A10 says for files outside the app root. No ES module can live there today (A3), so only classic scripts outsideapp/see it, and iOS's stack-textBaseDirstripping hides it there. Decided: accept it, and dropreportedPathPrefix. -
Q6. File names containing
?. iOS's key → path record reads them correctly. Android cuts the key at the first?. Decided: the record (6.2). -
Q7. A root-absolute specifier already under the app root. iOS prefixes the app root again. Android uses it as is. Decided: Android (6.3).
-
Q8. A specifier that is empty after the query is stripped. Android returns unresolved early; iOS falls through. Decided: Android (6.3).
-
Q9. The import-map scope prefix. iOS trims the trailing
/whenever the key has none. Android trims it only for a key written with no path (#2169). Decided: Android (6.3). -
Q10. Virtual roots under the opt-in. Decided:
file:///app/(both platforms) andfile:///android_asset/app/(Android) stayvirtualFileRootsin both modes (6.3). No such device path exists on either OS, and the shared tests usefile:///app/…throughout. Retiring them is its own deprecation. -
Q11.
import.meta.filename. Neither runtime sets it today. Decided: set it only under the opt-in, as A10 lists (6.6). In legacy mode, iOS'sdirnameis not a real path, so afilenamethere would not be one either. Done in 6.6. -
Q12. Ada in the core. Decided: keep ada behind
platform::ParseUrlfor step 6, and move it into the core with the URL follow-on. Both runtimes link their own ada today (iOS hides its symbols, #589). The move also retires theNormalizeHttpModuleUrlandHttpUrlOriginplatform functions. -
Q13. A
.jsfile reached throughimport(carried over from step 4). iOS wraps it in the CommonJS wrapper; Android compiles it as is. Still settled in 6.4, with the require(esm) interop rules.CompileFileEsModulekeepsSourceWrapuntil then.Decided 2026-12-06: Node's detection (
shouldRetryAsESM,containsModuleSyntax). A.jsfile is an ES module when it has module syntax, and otherwise CommonJS: a synthetic module whosedefaultismodule.exports, loaded by the runtime'srequire(). Any other extension (.cjsincluded) is CommonJS, never detected, as Node reads.cjs. Named exports:defaultand'module.exports'only; a CommonJS lexer (merve, as in Node) is a later unit. Built in 6.6, with the format recorded in the code cache file so the hot path parses once; see "Built: 6.6". -
Q14. When the off-thread consume did not run (carried over from step 4). Android loads the cache synchronously; iOS compiles without it. Decided: Android, since a consume is cheaper than a compile, once a measurement on a large
.mjsconfirms it. Settled in 6.4.Measured 2026-12-05. The branch is reached only for a job in consume mode (a fresh cache and at least 256 KiB), when V8 declined to start the consume task or
LoadCodeCachefailed on the pool. A smaller file with a fresh cache never becomes a job. The setup:- the 14.9 Mac Catalyst static libraries,
--jitless(as on a device) on an M-series Mac; - a fresh isolate per sample, the median of 15;
- prettier's self-contained plugin bundles;
- the cache made after evaluation, as
CodeCacheQueuemakes it; - no cache rejected in any sample.
Each cell is compile, then instantiate plus evaluate, in ms. "Sync" includes reading the cache file. "Pool" is the finalize after a consume that ran on another thread.
File, flags Lazy, no cache Eager, no cache Sync consume Pool babel 311 KiB, Debug 2.36 + 0.74 5.88 + 0.64 0.28 + 0.52 0.00 + 0.56 typescript 880 KiB, Debug 6.78 + 2.02 12.90 + 1.46 1.34 + 1.34 0.00 + 1.43 flow 1.06 MiB, Debug 2.32 + 3.61 4.62 + 0.65 0.27 + 0.56 0.00 + 0.57 babel, Release --no-lazy5.91 + 0.66 5.93 + 0.64 0.71 + 0.55 0.00 + 0.54 typescript, Release --no-lazy12.68 + 1.47 12.67 + 1.46 1.90 + 1.36 0.03 + 1.40 flow, Release --no-lazy4.64 + 0.67 4.72 + 0.66 0.92 + 0.56 0.00 + 0.63 Counting evaluation too, the sync consume is 3.3 to 7 times cheaper than iOS's compile at every size, so Android's branch stands. Absolute times won't carry over to a device; the ratios should.
- the 14.9 Mac Catalyst static libraries,
-
Q15. External memory charge. iOS uses its gate-id charge; Android uses
v8::ExternalMemoryAccounter. Decided: the plain accounter on both, after a check against #507's backoff (§4.8), in 6.4. -
Q16.
createRequire's JS signature. The headers disagree:(baseDir, pumping)vs(path). Decided: reconcile in 6.6.Done in 6.6. The native binding is the same on both platforms,
createRequire(baseDir, pumping, deadlineSeconds, throwOnTimeout, pumpRunLoop), and so are bothns-module.jshalves, which validate the arguments first. The(path)header was stale. The one difference is in native code JS cannot reach throughns-module.js: iOS throws on a bad deadline, Android ignores it. -
Q17. Android-only
ns:moduledebug calls. These arehttpFetchDiagnostics,streamedCompileStatsandforcePlatformHttpTransport. Decided: the first two become core and debug-only, and the third stays a platform row (6.6). Done in 6.6: Android addsforcePlatformHttpTransportto the binding after the core fills it. -
Q18. Virtual roots in key canonicalization. Both runtimes key
file:///app/x.mjsas/app/x.mjstoday. That matches no module, soinvalidateModuleswith an app file's legacyimport.meta.urlmisses. The resolver, meanwhile, maps the same URL to the app root, which gives one file two spellings (invariant 16).Decided (a): canonicalization maps virtual roots onto the app root too. It is JS-visible: such an invalidation starts to hit.
Built: 6.1.
-
Normalization and keys:
-
NormalizePathis Android'sNormalizeDotSegments, except that a relative path keeps its leading... Keys are always absolute. -
CanonicalFilePathnormalizes a path, then rewrites it from one of theappRootAliases(pairs of alias and spelling) onto the spellingappRootuses. -
CanonicalizeModuleKeyroutes keys by kind:- http(s): through
NormalizeHttpModuleUrlandCanonicalizeNormalizedHttpUrlKey; blob:and custom schemes: kept verbatim;file:andapp:, in any case and with or without//(the resolver's own scheme test):FileUrlToPathplusModuleQuery;- a plain path: normalized and aliased, followed by the
ModuleQueryof the text from its first?, so the query is encoded and its fragment dropped as the resolver keys it. The query's slashes and dot segments are not path syntax.
An absolute spelling of a file (a
file:orapp:URL, or a path already under the app root) canonicalizes to the key the resolver gives it;tests/ResolverTest.cppchecks every such spelling it resolves. A path spelling with a#and no?keeps the#, since a key cannot tell a fragment from a file name.The
file:branch maps virtual roots onto the app root (Q18). - http(s): through
-
-
Origins (
ModuleOrigin):- A file under
appRootgetsappRootOrigin+ its path relative to the root. - Any other file gets
file://+ its absolute path. - Under
legacyOrigins, both are verbatim andimport.metais the origin. - Otherwise, both are percent-encoded (Q2), and
import.meta.url,.filenameand.dirnameare the real path.
The override values:
- iOS:
appRootOrigin = "file://" + (appRoot without BaseDir), which isfile:///appfor the usual layout, withlegacyOrigins = true; - Android:
appRootOrigin = "file://" + appRoot, withlegacyOrigins = true.
- A file under
-
Reading back:
OriginToPathis the inverse ofModuleOrigin. It is verbatim in legacy mode and ada in opt-in mode (Q1), and it always acceptsapp:///.FileUrlToPathserves URLs from outside the runtime. It parses with ada, refuses what Q3 rejects, and percent-decodes. Then:app:names the app root;- an
appRootOriginprefix and thevirtualFileRootsmap onto the app root; - anything else is the absolute path (A3).
-
Decided behaviour. The code follows the decisions for Q1–Q4 and Q18, and the host tests pin each one. Nothing reaches JS before the runtimes adopt it.
-
Legacy spellings. A scratch harness linked the core against each runtime's own
ModuleUrl.cppand ada. It comparedReportedModuleUrl, the path read back from each origin, andModuleQueryover the same inputs. iOS showed no difference. Android showed one, Q4, which is decided in iOS's favour. Theimport.metastrings were checked against both callbacks by reading. -
Host tests:
tests/ModuleIdentityTest.cpp, againsttests/FakeUrl.cpp, a hand-written parser. With-DNS_ADA_DIR=<a runtime's ada folder>they run against the real ada instead (tests/AdaUrl.cpp). That file is also the reference implementation ofplatform::ParseUrl. Built: 6.2. -
Config snapshot (
ns/loader/LoaderState.h):platform::LoaderSnapshot()replacesplatform::Loader().InstallLoader(isolate, config)gives an isolate the snapshot it keeps for its life:platform::LoaderSnapshot()for a main runtime,CaptureLoaderConfig(parent), taken on the parent's thread, for a worker. It aborts on a null config and on a second call for the same isolate:LoaderConfigFor's callers hold the snapshot by reference.LoaderConfigFor(isolate)is the per-isolate read. It aborts whenInstallLoadernever ran, rather than guessing at a config that may belong to another run.CodeCacheEntryFortakes the config it applies, andFileCompilepassesLoaderConfigFor.
-
Closing:
loader::Quiesce(isolate)sets the flag and, for now, does nothing else; 6.4 adds the kills and the drain behind it.IsClosing(isolate)is the gate for work that would outlive the call. Under F1, the registry stays readable and writable through teardown; only new work checks the flag. -
Registry (
ns/loader/ModuleRegistry.h):SetRegisteredModule(isolate, key, module, filePath)is the only write. The previous occupant leaves the index under that key, and loses its facades once no other key holds it. The path record follows the occupant: an emptyfilePathclears it.- Reads:
FindRegisteredModule,IsModuleRegistered,RegisteredModuleCount,FindKeyForModule,ModuleFilePathForKeyandGetLoadedModuleUrls. RegistryKeyFor(isolate, keyOrUrl)isCanonicalizeModuleKeyunder the isolate's config, except that a registered file module's key is kept as it is (Q6), and a legacy origin that reads back verbatim as a registered key names it (Q1).RemoveModuleFromRegistry(isolate, keyOrUrl)returns the key it removed.InvalidateModules(isolate, urls, beforeRemove): each key once,beforeRemove(key)just before it goes.FindRequireFacadeandAddRequireFacade: the facade table moves now, because it has to empty as the registry does. Building a facade stays local until 6.6.- 6.3 moved the vocabulary into the loader state, and these functions lost their vocabulary parameter.
-
Still local, reached through the API above:
- Superseding a file job on removal. The runtime's
RemoveModuleFromRegistrywrapper marks the job for the key the core returns, until 6.4. Since 6.4, the core's removal andInvalidateModulesdo it. - Rejecting HTTP waiters and clearing
modulesInFlighton invalidation. The runtime passes this asbeforeRemove, together with the file-job step, until 6.5.
- Superseding a file job on removal. The runtime's
-
Host tests:
tests/ModuleRegistryTest.cppruns the V8-free table (src/loader/RegistryTable.h) with fake handles whose identity hashes collide. It pins the write path, facade release, the path record,ModuleFilePathForKey's fallback andGetLoadedModuleUrls' filter, and that onlyFindandFindFacade, which return a module, make av8::Local: the writes andFindKeycompareGlobal == Localand read a hash in aHandleScopeof their own, so a large invalidation does not grow the caller's scope. Both use iOS'sFileModulePathfor a key with no record. Android's also drops a host fromfile://host/…. No registered key can differ: afile:key stays verbatim only whenFileUrlToPathrefuses it, and such a specifier resolves to nothing, so nothing registers under it. The V8 instantiation (src/loader/ModuleRegistry.cpp,LoaderState.cpp) is only syntax-checked, against iOS's and Android's V8 headers, until a runtime adopts it. Built: 6.3. -
Vocabulary (
ns/loader/ImportMap.h,ns/loader/LoaderState.h):LoaderVocabulary(import map, canonicalization config and whether one was supplied, volatile patterns) lives in the coreModuleLoaderState.CaptureLoaderVocabulary(parent)andInstallLoaderVocabulary(worker, copy)replace the runtimes' worker inheritance.InstallImportMap,SetVolatilePatterns,SetCanonicalizationConfig,CanonicalizationConfigFor,IsVolatileModuleUrlandVocabularyForare the per-isolate accessors.InstallImportMapfails with "the isolate is shutting down" once the state is gone.
-
Import maps:
ParseImportMap(isolate, json, out, error)is Android's parser overv8::JSON::Parse, with its error texts, in the isolate's current context, which must be entered. It reads own keys only and installs nothing. It reads an index-like key ("404") as the string it is in the JSON. Android's parser kept it a number and rejected it as "every key must be a string"; iOS accepted it.AddImportMapEntry,ImportMapScopePrefix(Q9),FinishImportMapandLookupImportMapare V8-free. A map built by hand needsFinishImportMapbefore its first lookup, or its prefix keys never match.- A section keeps its exact keys in a hash map with transparent lookup and its '/'-terminated keys in a vector, longest first. A lookup allocates only on a hit, and scans only the prefix keys.
- Scopes are sorted most specific first, and every matching scope is
tried before "imports". As in the import-map spec, a scope matches a
referrer equal to its key, or below a key that ends in
/: the scope/data/app/pkgdoes not apply to/data/app/pkgs/x.mjs. Q9's path-less http(s) key still matches as a prefix.
-
Resolver (
ns/loader/Resolver.h):ResolveSpecifier(spec, {key, path}, vocabulary, config, lookup)is V8-free.ResolveModuleSpecifier(isolate, spec, referrerKey, lookup)reads the referrer's recorded file from the registry.- The order: builtins; the import map (unless
kSkip), whose target may be a builtin (A9);blob:askBlob(A9); an http(s) importer's browser rules; http(s) URLs;file:andapp:URLs throughFileUrlToPath(A3, A10, Q3, Q10); then paths: relative (lexical join, A1),~/, root-absolute (Q7, then without/app), and bare names underappRoot, the last three with..clamped atappRoot(see "App-root forms" under A). A specifier that is empty before its query or fragment resolves to nothing (Q8). - Q7's "already under
appRoot" is a path-segment test: withappRoot/data/app,/data/appx/y.mjsis not under it and is looked up as/data/app/data/appx/y.mjs. Android's raw string prefix used it as is. - A
file:///app/xspecifier names<appRoot>/xonly. iOS also tried<appRoot>/app/x, a leftover of reading everyfile://URL as app-relative, which A3 retires. Decided 2026-12-05: it stays dropped. - An http(s) importer can now reach an
app:URL as well as afile:one, because A10 saysapp:///always resolves. - Probes: as written,
.mjs,.js,/index.mjs,/index.js. A candidate that already ends in.mjsor.jsis not probed a second time with that extension. - Platform:
ParseModuleUrl(authority as written) andBlobStoreUrl.tests/AdaUrl.cppis their reference implementation.
-
Allocations per resolve, under libc++ (both runtimes' standard library; its short-string buffer holds 22 bytes) with tracing off, against a realistic app root.
tests/ResolverTest.cpppins each count under libc++, the rows that parse a URL against ada only; the platform'sStatis not counted. Debug with ASan and Release agree:- a relative, bare,
~/or root-absolute file hit: 2, the candidate, which becomespath, andkey; - each probe past the first: 1 more in total, since every extension and index probe shares one buffer;
- a miss: 2, the probe buffer and the last candidate, kept as
attempted; - a
~/hit on its second candidate (<appRoot>/app/…): 4. The second candidate is built only once the first has missed; - an import-map hit: the target string as well, when it is longer than the short-string buffer;
- a specifier longer than the buffer: 1 more, for
ModuleResolution::specifier; a query longer than it, 1 more forquery.ModuleQueryreturns the text as written when the parser would copy it unchanged, and parses only when a byte needs encoding or stripping; - a name that starts with
horb: nothing more. The http(s) andblob:tests read the whole scheme, as the parser does, before anything is copied or parsed; - a path with dot segments:
NormalizePath's segment list, which grows as it fills, and its output (11 in all for./lib/../lib/./../lib/util.mjs); - an http(s) URL: 3, with the host tests' stand-in
NormalizeHttpModuleUrl; a relative specifier from an http(s) importer: 3, most of them in the URL parser; - a
file:URL: 7, afile:///app/…URL: 5, anapp:///…URL: 3, most of them inFileUrlToPath's parse and decode; - a builtin: none.
- a relative, bare,
-
Host tests:
tests/ImportMapTest.cpppins entry validation and its errors, scope prefixes and lookup precedence.tests/ResolverTest.cpppins every branch above against fake files, including theattemptedand blocked texts.ParseImportMapis only syntax-checked, like the other V8 files. -
Deviations from the plan:
IsBuiltinModuleSpecifieris in the core, not the platform. The import map's JSON errors now come from V8 on iOS too (the plan'sv8::JSON::Parse), so iOS's detail text changes, and a lone surrogate in a key or target is rejected as "must be a string", as on Android.ParseModuleUrl's authority-as-written branch is ported from iOS but no host test reaches it. Built: 6.4. -
Liveness (
ns/RuntimeLiveness.h, a token per runtime):loader::LivenessFor(isolate)creates it the first time a walk needs it and the platform has a loop for the isolate (null until then). It holds aweak_ptr<Loop>and the isolate pointer. The pointer is used by a task the token ran, on the isolate's thread, and by a pool job inside a section (StartConsumingCodeCacheOnBackgroundfinds the isolate's heap through it), where the isolate cannot be disposed.NotifyAppBackgrounded(token)reads it off the thread only to hand it to its task.- The token keeps the loop it was created with.
LivenessForaborts, with a message, when the isolate's loop is no longer that loop: work posted through the token would go to a loop nobody runs. Post(task)posts a nestable V8 task while the token is open, and the task re-checks the token before it runs. It returns false when the token is closed or the loop is gone or stopped; for the last,Loop::PostV8Taskreports the drop. The weak loop is locked and released inside a section, so no other thread ever drops the last loop reference.Enter/Leavebracket background use of isolate-owned state.CloseAndDrain(service)closes the token and waits out the sections, runningservicefirst and between 2 ms waits.- The token merges the plan's two pieces: the
aliveflag and the stream gate's in-flight count. A plain flag cannot stop a thread that checked it a moment before teardown, and that thread could then become the loop's last owner; the count can. It replacesload->dead,StreamCompileGateand its identity check, and everyLookupEventLoop(isolate)on these paths. platform::IsRuntimeAliveis no longer declared.MainContextstays.NotifyAppBackgrounded(const std::shared_ptr<RuntimeLiveness>&)is the token overload (a shared_ptr, sincePostneedsshared_from_this). The isolate overload stays for callers that keep the runtime alive across the call: iOS pins the isolate gate, and Android calls it on the runtime's own thread. Both runtimes call that overload at3bcf603, so neither has to change.
-
Compile pool (
src/loader/CompilePool.h): one per process, at mostclamp(cpus - 1, 1, 4)threads. Threads start lazily throughStartThread("ns-esm-compile",kUserInitiated, a stack ofBackgroundCompileStackBytes(config.v8Flags)), and each job runs throughplatform::RunJob, which on iOS gives it an autorelease pool. Jobs carry an owner, the token.Discard(owner)calls that owner's queued jobs withrun == false, so a teardown never waits behind another isolate's compile. iOS's pool used a hard-coded 2 MiB stack. Known and left as is: the queue is FIFO across isolates, so one isolate's burst of file jobs delays another's. -
Graph walk (
ns/loader/GraphLoad.h):ModuleGraphRootis iOS's, plusFromResolution. AFilePathroot's path is canonicalized (CanonicalFilePath) when the walk starts, and is also its key. It is then read, cached and reported under the resolver's spelling, as iOS's dispatch and itsCompileFileEsModulewrapper did.StartModuleGraphLoad,SyncModuleLoadScope(parking),RunModuleGraphLoadPumped,HasPendingGraphWork(process-wide, as both runtimes have it) andLoadHttpModuleForUrl.HasPendingGraphWorkcounts walks from their start until they complete or Quiesce kills them; fetch threads that still hold a finished walk no longer count.GraphLoadCompletionruns at most once: never for a walk started after Quiesce, and not when the runtime is torn down first. It carries the exception a JSON root failed with (6.5).FinalizeFinishedFileModule(isolate, context, key)is the resolver's step for a finished job until 6.5 moves the resolver in.- Edges resolve through
ResolveModuleSpecifier. Thresholds and routing are unchanged: 32 KiB to stream or to make a file job, 256 KiB with a fresh cache, and file jobs for.mjsonly. - Walks and jobs own no V8 state. A walk's context lives in
GraphLoaderState::walkContexts, keyed by its start sequence, so a walk's last reference may drop on a transport or pool thread. Both runtimes kept aGlobal<Context>in the walk and relied on reset ordering. - The start stamp is
steady_clock(iOS used wall-clock time). - Eager streaming follows
V8FlagsDisableLazyCompile(config.v8Flags). On iOS that reproducesIsDebug ? lazy : eager, because iOS adds--no-lazyoutside Debug. - A file job's script origin is
ModuleOrigin(path, query). Both runtimes usedReportedModuleUrl(path + query), and the two agree unless the file name contains '?'. - An http(s) edge in an isolate without a loop is not fetched by the walk. The resolver fetches it synchronously and logs the miss. On Android, such a walk instead never completed.
RunModuleGraphLoadPumpedpumps at least once, so termination outranks a walk that completed inline (iOS). Android skipped the pump, and returned true, when the walk completed inline. A walk started on a closing loader returns false at once. It pumps the token's loop, the one the walk's completions go to.- Off the loop's home thread (multithreaded JavaScript)
RunModuleGraphLoadPumpednever pumps, since its caller holds the Locker the loop needs: it returns whether the walk completed inside the call, and false when termination was requested (ns/loader/GraphLoad.h). - A file job that lands while
platform::MainContextis empty still continues its waiters, each in its own walk context. Only the finalize waits: the result stays with the job, for the resolver or the next walk that reaches the key.
-
The walk's public functions open their own handle scopes and escape what they return. Only the isolate's thread reads
LoaderConfigForor the vocabulary. The pool and transport paths work on copies taken at dispatch: theCodeCacheEntry, the path and the pool's stack size. -
Settles:
- Android's drain scopes;
supersededon kill and on the core's removals (RemoveModuleFromRegistryandInvalidateModules);CanWaitForFileJobs(a loop that is on its home thread);- Q14: a synchronous
LoadCodeCacheconsume at finalize, after the measurement above; - Q15: the plain
v8::ExternalMemoryAccounter, increased under a handle and decreased inUnaccount. On the check against #507's backoff, see below.
-
Q15 and the #507 backoff, checked by reasoning and Android's shipped use of the accounter, not measured. The backoff comes from charges that a finalizer drops after V8 has recomputed its limits within the GC pause, so dead bytes still count toward the next limit. An external string's resource is different: V8 releases it while it processes its external-string table inside the collection, through
Unaccount, not a finalizer. Module sources also live as long as their module, and only an invalidated module's source dies at all. Neither part of the backoff applies. -
Q13 stays open. 6.4 did not force a choice. A
.jsfile never becomes a file job, and the inline compile takes its wrap from theplatform::FileModuleSourceWrap(path)up-call (ns/loader/Transitional.h). iOS returns its CommonJS wrapper there, and Android returns none. (Settled in 6.6:CompileFileModuledetects a.jsfile's format, any other extension is CommonJS, and the up-call is deleted.) -
JSON modules reached by an http(s) edge or
LoadHttpModuleForUrlcompile through theplatform::CompileJsonModuleup-call until 6.5. The runtimes' versions instantiate withResolveModuleCallback, which is 6.5's. -
Threads and teardown, per handoff. Nothing a background thread holds owns V8 state. V8 tasks and
StreamedSources live inGraphLoaderState, which only the isolate's thread creates, finalizes and destroys.Handoff Holds Cancelled by Fetch completion, transport thread to isolate thread walk, ticket, token, the fetched body ( ModuleFetchResult)refused once the token closes; dropped by the re-check if already queued Large HTTP body, transport thread to pool a token section; the ticket's raw stream and task pointers Discardif queued; Quiesce waits if running; the job skips its work once the token is closedPool completion back to the isolate thread job or ticket, posted from inside the section refused, or dropped by the re-check File job, isolate thread to pool a token section; job->compilerawas for the large HTTP body Parked walk, released when the outermost SyncModuleLoadScopeclosesthe walk's continuation posted through the token; the task takes the Locker File job's notify, pool to a synchronous wait shared_ptr<FileJobSignal>(a counter and a condition variable)nothing: shared ownership keeps it alive on both sides NotifyAppBackgrounded(token), any thread to isolate threadthe isolate pointer, read only by the task refused, or dropped by the re-check onCompleteof a walk, run on the isolate threadwhatever the caller captured destroyed unrun, on any thread, when the walk dies with the runtime; never run for a walk started after Quiesce So an
onCompleteowns no V8 state. All four runtime callers comply: theimport()ones keep their resolvers in loader state by id or key and capture strings, and the pumped wait captures ashared_ptr<bool>.loader::Quiesceruns on the isolate's thread, under its Locker, before the loop shuts down:- It marks the walks killed, resets their contexts and root
exceptions, supersedes the jobs still in
fileJobsand drops their waiters, and clears the parked walks. A job superseded earlier is no longer infileJobsand keeps its waiters until its completion is dropped; they are walks, which hold no V8 state. - It closes the token and drains under
SuppressMicrotaskExecutionScopeandDisallowJavascriptExecutionScope. The drain's service discards this token's queued pool jobs and runsRunNestableV8Tasks, where a background compile's GC request waits. When the loop is gone or stopped, no V8 task runs: the service then logs once, runsLowMemoryNotificationat most every 100 ms (any full GC on the isolate's thread releases a waiting background compile), and aborts with a message after 10 s. - It destroys the streamed compiles and file-job compiles that will never be finalized.
Step 1 precedes step 2, so a task the token refuses never holds the last reference to anything with a V8 handle.
- It marks the walks killed, resets their contexts and root
exceptions, supersedes the jobs still in
-
Host tests:
tests/CompilePoolTest.cppruns the token's sections and drain, the pool's run-once and discard rules, the teardown pattern (a drain does not wait for another owner's running job), andFileJobSignal. It also runs a concurrent close-and-drain stress (5,000 rounds under a sanitizer, 20,000 without; anEnterthat checks the flag before taking the mutex showed 100 to 300 violations in 2,000 rounds), a post that lands after the drain's firstDiscard, and a job taken off the queue but not yet run whenDiscardruns. It runs clean under ASan/UBSan (all three lanes) and under TSan. -
V8-linked tests (opt-in, never in CI): configured with
NS_V8_LIB_DIRandNS_V8_INCLUDE_DIR, the build links the whole core against a V8 build and runstests/v8.CMakeLists.txtdocuments a configure against iOS's Mac Catalyst libraries.LoaderHostTestruns synchronous and asynchronous file and HTTP graphs, streamed compiles, parking, supersession, the resolver racing the pool, termination during a pump and while parked, a walk without a main context, a replaced loop and a closed state bag (in a child process), a load off the home thread, and concurrent teardown of runtimes mid-walk on several threads.LoaderHostTestShutdownFirststops the loop beforeloader::Quiesce, under a 9 MB heap.ModuleImportTestis 6.5's. -
Adoption (on top of 6.2 and 6.3), current at the 6.5 tip. When 6.5 is adopted in the same change, read its list too: some items here fall away (marked "until 6.5").
- Platform functions to implement:
platform::FileModuleSourceWrap(iOS: today'sModuleSourceWrap; Android:{}). 6.6 deletes it; see its adoption list.platform::CompileJsonModule(today'sCompileJsonTextAsEsModule), until 6.5, which removes it.
- Interfaces that change:
Loop::PostV8Taskreturnsbool: false when the loop has stopped and dropped the task. Both runtimes'EventLoop::PostV8Taskand theNativeScriptPlatformforwarding change with it.GraphLoadCompletionisvoid(bool ok, const std::string& errorMessage, v8::Local<v8::Value> exception, v8::Local<v8::Context> context).exceptionis set only for a JSON root that did not parse. Any runtime caller ofStartModuleGraphLoadadds the parameter.
- Delete:
StreamCompilePool,StreamCompileGate,StreamFeed,FeedSourceStreamandBodySourceStream;StreamTicket,StreamedModuleCompile,FileModuleCompile,FileModuleJob,FileJobSignalandAsyncGraphLoad;OwnedAsciiSource;- both walks,
ModuleGraphRoot,ResolutionForRoot,SyncModuleLoadScopeandRunModuleGraphLoadPumped; LoadHttpModuleForUrlandHasPendingAsyncModuleGraphWork;QuiesceModuleLoadsForIsolateandNoteAppliedV8Flags;- the runtime's
fileJobsstep in theRemoveModuleFromRegistrywrapper and inbeforeRemove; - the
platform::IsRuntimeAlivedefinitions; - the matching
ModuleLoaderStatefields.
- Call sites:
- Call
loader::Quiesce(isolate)whereQuiesceModuleLoadsForIsolatewas called. - Boot backstops call
loader::HasPendingGraphWork(): Android'sRuntime.cppand iOS'srunMainApplication. - The resolvers' "finalize a finished job" block becomes
FinalizeFinishedFileModule, until 6.5 replaces the resolvers. - Android's
streamedCompileStatsreadsGetStreamedCompileStats(). - Android's
import()file path passesModuleGraphRoot::FromResolution(resolution)instead of the key string, and its HTTP path passesModuleGraphRoot::HttpUrl(url), until 6.5 replacesimport().
- Call
- Ordering, which the core now checks:
- The loader's token keeps the loop it finds on first use, and
LivenessForaborts the process when the isolate's loop has been replaced since. Both runtimes replace a stopped loop inRefreshEventLoopright afterIsolate::New; nothing may call a loader function that walks or posts before that, and neither runtime does today. - Every teardown path calls
loader::Quiescebefore the loop shuts down and before the state bag closes: the main runtime, workers, and failed or aborted initializations. A debug build aborts when the bag closes for an isolate whose loader was installed and never quiesced. loader::Quiesceafter the loop stopped is a backstop, not a supported order: it logs once, collects garbage on the calling thread for the background compiles waiting on a GC, and aborts the process after 10 s.
- The loader's token keeps the loop it finds on first use, and
- Optional: hold the token from
LivenessForand call the token overloadNotifyAppBackgrounded(const std::shared_ptr<RuntimeLiveness>&), retiring iOS's gate pin there. Neither runtime calls it yet. - Behavior that may move expectations:
- iOS's eager-compile choice now comes from the flag string (the
same in practice), and iOS's pool threads follow
--stack-sizeinstead of 2 MiB. HasPendingGraphWorkturns false as soon as the walks complete or are killed, so the boot backstops may stop pumping sooner.RunModuleGraphLoadPumpedcalled off the loop's home thread (multithreaded JavaScript) never pumps: it returns whether the walk completed inside the call.
- iOS's eager-compile choice now comes from the flag string (the
same in practice), and iOS's pool threads follow
- Platform functions to implement:
Built: 6.5.
-
Core API (
ns/loader/ModuleImport.h):ResolveModuleCallbackandImportModuleDynamicallyCallback, which each runtime installs or passes toInstantiateModule. Both resolve once, throughResolveModuleSpecifier, and load what the resolution names. Behind them, insrc/loader/ModuleImport.cpp: the http(s) and blob: waiters, the top-level-await continuations, the settling of a fileimport()(Android'sSettleDynamicImport) andFinishHttpImport. The waiters, the file imports' resolvers (by id, so a walk'sonCompleteholds no V8 state) and the JSON values live inImportState, in the coreModuleLoaderState. -
Platform: a new
platform::BuiltinModule(context, specifier)(ns/RuntimeAccess.h) returns the builtin's module, already evaluated, or empty with an exception pending ("No such built-in module: X" for an unknown name). Both runtimes have it asNsBuiltinModules::GetModuleplusNotFoundMessage.platform::CompileJsonModuleis gone fromns/loader/Transitional.h. -
Departures from the plan:
BuiltinModuleis a new up-call. The plan had none, but the builtin registry is per runtime until the builtins move (follow-on 3).- No blob-store platform lookup. Both runtimes' store is JS beside
URL.createObjectURL, and both read it asURL.InternalAccessor.getData(url).blob.text(), so the core reads the same accessor. InvalidateModules(isolate, context, urls)takes the context and dropsbeforeRemove. It rejects theimport()s still waiting on a key it removes with "Module invalidated during dev reload: ", which is what both runtimes'beforeRemovedid.Quiescedrops all import state. Animport()still pending then stays pending, as before. A newimport()after it returns a promise that never settles and runs nothing (decided below; it aborted the process before, §8).
-
Settles:
- A9: a builtin is matched after the single resolution, for
import()too (Android matched the raw specifier before it). AnykBlobresolution takes the blob path, as on iOS; Android took it only for theblob:nativescript/prefix, and rejected any otherblob:URL with "Cannot find module '' (tried )". Such a URL now loads when the store has it, and otherwise rejects with "Blob not found: ". - Invariant 19: Android's reasons, listed below.
- The
Then(...)results are ignored, asFromMaybedoes; noToLocalChecked. The continuations keep their state in the function's data array, not in a heap block a never-settling promise would leak. - The
import()referrer key comes fromOriginToPath(Android'sReferrerKeyFromOrigin), and falls back toRegistryKeyFor. - A
.jsonfile is read throughplatform::ReadFile; a failed read throws Error "Cannot read module ".
- A9: a builtin is matched after the single resolution, for
-
Rejection reasons.
<stage>: <url or key> — <V8 message>is Android'sBuildModuleFailureReason; the message comes fromTryCatch::Message(), so it starts with "Uncaught ". A module that throws while it evaluates rejects V8's evaluation promise, so its exception reaches JS as it is; the "Evaluation failed …" stages are left for anEvaluatethat returns empty, which only termination does.Path Failure Reason any NUL in the specifier Error Cannot resolve module specifier "<spec, \u0000 escaped>": a module specifier must not contain U+0000any unresolved, or blocked by a rule Error from UnresolvedModuleMessage;import('')gives "Cannot find module '' (tried )"builtin unknown name BuiltinModule's exceptionfile load (read, compile, JSON parse) the exception itself file link Error "Failed to instantiate module: — " file evaluation, or its top-level await the exception itself (V8 rejects the evaluation promise) http(s) fetch or compile in the walk Error with the walk's message, as in 6.4; a JSON root that does not parse rejects with its SyntaxError http(s) load after the walk the exception itself, or "HTTP fetch/compile failed: " http(s) link Error "Instantiation failed (http-loader): — " ("(http-cache hit)" on a registered module) http(s) evaluation, or its top-level await the exception itself blob: lookup Error "URL constructor not available", "URL.InternalAccessor not available", "URL.InternalAccessor.getData not available", "Blob not found: ", "Invalid blob data", "Blob object not found", "Blob.text() not available", "Blob.text() threw[: ]", "Blob.text() did not return a thenable", "Blob text is not a string" blob: compile Error "Failed to compile blob module: (line L:C)" blob: link Error "Failed to instantiate blob module: — " blob: evaluation, or its top-level await the exception itself http(s), blob: waiting on an evaluation that ended unevaluated Error "Module did not finish evaluation: " any, import()import attributes, with enforceImportAttributesTypeError Module "<url>" needs an import attribute of "type: json",Module "<url>" is not of type "json", orImport attribute "<key>" with value "<v>" is not supported in <url>(Node's texts)any, static the same the importer's link fails: "Failed to instantiate module: — TypeError: …" under a file import()Rows that change, from grepping both test trees at
bae0c78e(iOS) and1ee254f22(Android) for every reason above and the texts they replace: one iOS row.import('')from a module rejected with "Module resolution failed for dynamic import: " and now gets Android's "Cannot find module '' (tried )" (the["esm", "", …]row ofDynamicImportTests.js). No test checks a JSON failure text or a blob failure other than "Blob not found", and every.jsonfixture and JSON test-server response in both trees is strict JSON. -
JSON modules (
src/loader/JsonModule.cpp): a synthetic module whose only export,default, isJSON.parseof the text, BOM dropped. The value is parsed when the module is created, and kept inImportState::pendingJsonuntil the evaluation steps set the export. Text that is not JSON throws SyntaxError ": <V8's JSON.parse message>", e.g. "app:///x.json: Expected double-quoted property name in JSON at position 8 (line 1 column 9)". Every path that loads JSON goes through it: a file (ReadFile), and an http(s) response served as JSON, in the walk and inLoadHttpModuleForUrl.Differences JS can see, compared with both runtimes' `"export default "
- text + ";"`:
Text Before Now JS that is not JSON: trailing commas, comments, unquoted keys, single quotes, hex, .5,Infinity,undefined,\x41,1+1, a raw tab in a string, a vertical tab or NBSP between tokensloaded SyntaxError Code after the value, {"a":1};globalThis.x=1loaded, and ran the code SyntaxError; nothing runs {"__proto__": {…}}set the object's prototype an own __proto__property__proto__twiceSyntaxError (compile) loaded, last one wins Empty or whitespace only SyntaxError (compile) SyntaxError "Unexpected end of JSON input" Other invalid text (leading zero, two values, a line break in a string) SyntaxError "Failed to compile JSON module" SyntaxError with V8's JSON message Nesting deep enough to exhaust the compiler (3000 levels and up) RangeError, reported as "Failed to compile JSON module" loads BOM, U+2028 in a string, -0, a lone surrogate escape,null, a trailing newlinesame same Timing. The parse happens where the compile did, when the module is loaded and before it is linked, so an invalid file fails the same step it failed before. The old module was also instantiated and evaluated right after its compile; the synthetic module is linked and evaluated with its importer's graph. Its evaluation only sets the export, so the order is invisible except through code after the value, which no longer runs. Settling, measured in a V8 harness against the old module registered under the same key:
- a file
import(): 2 microtask turns, before and now; - a registered http(s) module: 1 turn, before and now;
- the first
import()whose root is an http(s) JSON module: one turn later than before, inside the same checkpoint. The old module was already evaluated, so its waiters resolved at once; now the import waits on the evaluation's promise, as it does for any module (by reading the code; the harness cannot count across the fetch).
Which paths hand the SyntaxError object to JS:
Where the bad JSON is What JS gets import()of the filethe SyntaxError a static import, under a file import()Error "Failed to instantiate module: — SyntaxError: : …" import()of the http(s) URLthe SyntaxError (decided below; the walk hands its JSON root's exception to onComplete)a static import, under an http(s) import()Error "Instantiation failed (http-loader): — Uncaught SyntaxError: : …" -
Import attributes. A module is JSON when its path ends in
.jsonor its response is served as JSON, as in both runtimes today, never because of an attribute. Static imports andimport()then check thetypeattribute against it (ResolveModuleCallbackper edge, so registry hits are checked too):- a JSON module imported without
type: "json"; type: "json"on a module that is not JSON (JavaScript, a builtin, a blob);- a
typeother than"json","javascript"included, as in Node and browsers; - any key other than
type, reported before the type, as Node does. WithLoaderConfig::enforceImportAttributes(default false) the import rejects with Node's TypeError before anything is linked or evaluated, soimport('./m.mjs', { with: { type: 'json' } })never runsm.mjs. File, builtin and blob imports are refused before the load starts, and an http(s) import with an unsupported key or type before its fetch. An http(s) module's type is known only after the fetch, so each waiter is checked against its own attributes once the module has loaded; when every waiter is refused, nothing links or evaluates. With enforcement off, the import goes on, and a debug build (LoaderConfig.isDebug) logs each mismatch once per module URL, naming the specifier and the importer:NativeScript: Module "app:///x.json" needs an import attribute of "type: json" ("./x.json" imported from app:///main.mjs). Import attributes will be enforced in a future release.V8 refuses a non-string value itself.assert { … }in a static import is a SyntaxError ("Unexpected identifier 'assert'"), and V8 ignores anassertkey inimport()'s options, so that import has no attributes.
- a JSON module imported without
-
Decided 2026-12-05:
- JSON errors: the walk passes its failing JSON root's exception
through
onComplete, soimport()of an http(s) JSON URL rejects with the SyntaxError itself, as a local file does. Failures deeper in the graph keep Android's wrapped messages. import()afterloader::Quiescereturns a promise that never settles, as the imports in flight at teardown do. It runs no JS.- Import attributes: warn now, enforce later, as above. The default
flips to enforcement once tooling and plugins write the attributes,
like the
appSchemeOriginsrollout.assert { … }stays a SyntaxError, as V8 decides. - Keys other than
type: warned in debug builds once per module, and rejected underenforceImportAttributeswith Node'sImport attribute "<key>" with value "<value>" is not supported in <url>, as fortype. - An http(s) JavaScript root that does not compile keeps its wrapped
rejection, Error "HTTP import compile failed: — …": V8's
SyntaxError does not name the module, and iOS's
HttpEsmLoaderTestschecks the message for the name. Only JSON roots reject with the exception itself. type: "javascript"is unsupported, as in Node and browsers: a warning by default, a rejection under enforcement.- A module whose static import breaks the attribute rule keeps the
wrapped outer rejection, "Failed to instantiate module: —
TypeError: …", as other failures deeper in the graph do. A direct
import()rejects with the TypeError itself. - After
loader::Quiesce,ResolveModuleCallbackthrows Error "The module loader is shutting down", so an instantiate a runtime runs then fails cleanly instead of returning empty with no exception pending.
- JSON errors: the walk passes its failing JSON root's exception
through
-
import ''in a static import throws Error "Cannot find module '' (tried )", the messageimport('')rejects with. Both runtimes failed the link with no exception pending. Under a fileimport()the reason is "Failed to instantiate module: — Error: Cannot find module '' (tried )". -
import()of a module being evaluated. V8 CHECKs (Module::Evaluateon akEvaluatingmodule) when animport()names a module whose evaluation is on the stack: a module that imports itself, or B, statically imported by A, callingimport('./A.mjs'). Both runtimes crashed this way inside theimport()call (iOSd888aad5, Android83a72561fanda12106397), and so did the core through 6.5.- Such an import is parked and settles from a microtask after the evaluation returns, as in Node: with the namespace once the evaluation has finished, following its top-level await, or with its error. Awaiting it inside that evaluation never settles (A awaits B, which awaits A), as in Node.
- When a microtask checkpoint nested in the evaluation runs it, the
module is still evaluating, and the retry goes to a 4 ms delayed
loop task, never to another microtask, so the checkpoint cannot
spin. Inside a
kPlatformWorkpump within that evaluation it polls at that interval until the evaluation returns. - Decided 2026-12-06: an http(s)
import()of a module a static import is evaluating waits the same way. Both runtimes resolved it with the namespace at once ("avoiding re-entrant Evaluate"), and so did the core: reading an export could hit its temporal dead zone, and a module that went on to throw, or was still in its top-level await, was handed over as evaluated. - JS-visible, both runtimes: a crash becomes a settlement after the
evaluation, for a file
import(); an immediate namespace becomes one after the evaluation, for an http(s)import(). - Known difference from Node, decided 2026-12-06 to stay: an
import(), made during an evaluation, of a module not yet loaded whose static graph reaches the module being evaluated.reach-a.mjsisimport './reach-b.mjs'; export const a = 'A';,reach-b.mjsisglobalThis.reach = import('./reach-c.mjs');, andreach-c.mjsisimport { a } from './reach-a.mjs'; export const seen = a;. Node givesseen === 'A'. When the walk forreach-c.mjscompletes synchronously (a small file), the core evaluates it inside theimport()call and it rejects with ReferenceError "Cannot access 'a' before initialization"; when it completes through a background job (an.mjsfile of 32 KiB or more, 256 KiB with a fresh code cache), it evaluates after A and gives'A'. Both runtimes evaluate inside the call too, so this is no regression. Matching Node would defer the evaluation of everyimport()made during an evaluation, which changes the timing of all of them. - Open:
- A blob
import()of a blob module that something other than animport()is evaluating queues a waiter that nothing settles. LinkAndEvaluateForWaitersreturns, leaving its waiters pending, when the module is being evaluated by someone else. That needs an http(s) walk to complete inside a pump nested in that module's evaluation.
- A blob
-
Verification:
ModuleImport.cpphas no V8-free part. It is syntax-checked against iOS's and NDK 27's V8 headers, andtests/v8/ModuleImportTest.cpp(the opt-in V8-linked lane) asserts the rows above under the default, iOS and Android configurations: JSON (file and http(s), static and dynamic, BOM,__proto__, the injection text), file, http(s) and blobimport()with link, evaluation and top-level-await failures, coalesced imports, builtins, NUL and empty specifiers, invalidation of an import in flight,import()of a module being evaluated (itself, back through a cycle, throwing, with top-level await, under a nested checkpoint, awaited, and an http(s) module a file's static import is evaluating),import()and a runtime's own instantiate after Quiesce, and every attribute case in both modes (JSON without the attribute,type: "json"on JavaScript and builtins, unsupported types including"javascript", unknown keys, static and dynamic, file and http(s)), with the warnings logged once each and none in a release build. -
Adoption (on top of 6.4), current at the 6.5 tip:
- Implement
platform::BuiltinModule:NsBuiltinModules::GetModule, throwingNotFoundMessagewhen it returns empty with no exception pending. - Config:
LoaderConfig::enforceImportAttributesis new and defaults to false. A platform may map an app config flag to it; nothing has to set it. The attribute warnings followLoaderConfig::isDebug. - Install the core's
ImportModuleDynamicallyCallback, and pass the core'sResolveModuleCallbackwherever a runtime instantiates.- A runtime that keeps a wrapper around
import()must not return an emptyMaybeLocalwhen its loader state is closing or gone, as both runtimes' callbacks do today whenModuleLoaderStateForis null: call the core's callback, which then returns a promise that never settles. An empty result with no exception pending aborts V8 (§8). - After
loader::Quiesce,ResolveModuleCallbackthrows Error "The module loader is shutting down", so an instantiate a runtime runs then fails with that exception pending. Run it under aTryCatch, as for any other link failure.
- A runtime that keeps a wrapper around
- The dev
invalidateModulesbinding calls the core'sInvalidateModules(isolate, context, urls). - Delete:
- both callbacks and everything only they use: the waiters,
FinishHttpDynamicImport,SettleDynamicImport/SettleFileDynamicImport,BuildModuleFailureReason,AdoptThenable, the blob path,LoadResolvedFileModule; DynamicImportReferrerKeyandReferrerKeyFromOrigin;- the JSON code (
CompileJsonTextAsEsModule) and theplatform::CompileJsonModuledefinitions; - the runtimes'
InvalidateModuleswrappers andRejectAndClearInvalidatedModuleState; - the matching
ModuleLoaderStatefields.
- both callbacks and everything only they use: the waiters,
- Adopted with 6.4 in one change, these 6.4 items fall away:
platform::CompileJsonModule, the resolvers'FinalizeFinishedFileModuleblock (unless something else in the runtime finalizes file jobs), and Android'sModuleGraphRootarguments inimport(). - Expectations that move:
- the iOS
import('')row above; - any JSON file or response that is not strict JSON (none in either test tree);
import()of an http(s) JSON URL that does not parse rejects with the SyntaxError instead of an Error wrapping its text; a search of both test trees for "failed to compile" found no test of that text;- debug builds log a warning once per module for each attribute
mismatch: a JSON module imported without
with { type: "json" },type: "json"on a module that is not JSON, any othertype("javascript"included), and any key other thantype. Both runtimes' HTTP loader tests importdata.jsonwithout the attribute: they log it and, with the default, still pass. No import in either test tree passes attributes (withorassert, static or inimport()'s options), checked at iOSd888aad5with the shared tests at2cb9c23and Androida12106397.
- the iOS
- Implement
Built: 6.6.
-
Core API:
ns/loader/ModuleImport.h:InitializeImportMetaObject, onImportMetaFor, andInstallHostCallbacks(isolate), which installs it withImportModuleDynamicallyCallback.ResolveModuleCallbackis not an isolate callback and is still passed to everyInstantiateModule.ns/loader/RequireEsm.h:GetOrCreateRequireFacade(context, target, label), Node's facade source (re-exports and__esModule = true), returned instantiated and evaluated, one per target. It throwsJsErrororTerminated; the runtime'srequire()catches them.ns/loader/NsModuleBinding.h:BuildNsModuleBinding(context, binding, diagnostics).configureLoader,invalidateModules,getLoadedModuleUrls,setHttpCacheEnabled,clearHttpCache, thencreateRequirefrom the platform. Withdiagnostics:canonicalizeHttpUrlKey,remoteUrlMatchesAllowlist,httpFetchDiagnosticsandstreamedCompileStats. Every member runs inside Android's barrier:JsError,Terminated, anystd::exception("C++ exception: ") and anything else become a JS exception.diagnosticsis a parameter, notLoaderConfig::isDebug, which must never change what JS observes.ns/loader/FileCompile.h:CompileFileModule(isolate, context, path, origin), the file moduleimportloads, by extension:.mjsan ES module,.jsdetected (Q13 below), anything else CommonJS. The walk and both import callbacks call it.CompileFileEsModulelost itsSourceWrapparameter.- The code cache's module format (§4.3).
-
Platform (
ns/loader/Transitional.h, all deleted by step 8):InstallCreateRequireBinding(context, binding), as before.RequireFileForImport(context, path), new:module.exportsof a CommonJS file through the runtime'srequire()and its cache. Empty with an exception pending on failure; never throws C++.FileModuleSourceWrapis deleted.
-
Departures from the plan:
- No
EvaluateModuleGraph(…, kSyncStrict)up-call. The facade only re-exports an evaluated target, so the core evaluates it: a rejected evaluation is marked handled and its value thrown; a pending one (a target that has not finished evaluating, which the header rules out) throws "The require() facade for did not evaluate synchronously". Afterloader::Quiesceit throws "The module loader is shutting down". RequireFileForImportis a new up-call, for Q13.- A synthetic module other than JSON that throws while it evaluates
(the CommonJS leaf) rejects
import()with the thrown value, as an ES module does, not with "Evaluation failed …".
- No
-
Settles:
- A8: one
import.metacallback, onImportMetaFor, which both runtimes already called. - Q11:
filenameunder the opt-in only, fromImportMetaFor. - Q13: below.
- Q16 and Q17: in their entries above.
appSchemeOrigins: see "Rollout" in §7 A. The core has nothing to wire; each runtime skips its override when the flag is set (adoption below).
- A8: one
-
Q13, as built.
CompileFileModuleon a.jsfile:- It
Stats the file. A format remembered for thatStat(size and freshness token) skips detection: first the isolate's memo (ModuleLoaderState::detectedFormats), then the code cache header (FreshModuleFormat). - Otherwise it reads the file and compiles it with
ScriptCompiler::CompileFunctionand the CommonJS parameters (exports,require,module,__filename,__dirname). Success means CommonJS. A failure is ES module syntax when V8's message is one of Node's three ESM-only messages ("Cannot use import statement outside a module", "Unexpected token 'export'", "Cannot use 'import.meta' outside a module"). When it is one of Node's maybe-ESM messages (the five "Identifier '' has already been declared", the top-levelawaitmessage, "missing ) after argument list", "SyntaxError: Unexpected"), it compiles as a module, as Node'sShouldRetryAsESMdoes, and success means ES module; that module is the one returned. Anything else is CommonJS, so the syntax error surfaces whenrequire()compiles it. - An ES module compiles with its code cache as
.mjsdoes, and queues a cache when there was none. A CommonJS file becomes a synthetic module with two exports,defaultand'module.exports'(as in Node 24), bothRequireFileForImport's value when it evaluates; the source is not read again. The cache writer gets a CommonJS marker for it.
Any other extension (
.cjs,.ts, none) goes straight to the CommonJS module after theStat: no detection, no read, no marker.So with the code cache on, a
.jsfile parses once on every boot but its first: an ES module consumes its cache; a CommonJS file reads a 36-byte header and is compiled only byrequire(), which has its own classic cache. With the code cache off, each isolate detects once per file.Named exports from CommonJS: decided 2026-12-06,
defaultand'module.exports'only. A lexer is a later unit: merve (nodejs/merve, the lexer Node uses since PR 61456; MIT or Apache-2.0, C++20). Its costs: the names stored with the marker (the marker path never reads the source), a CommonJS-resolve up-call for re-exports, a check of-fno-rttiand-Werrorbuilds, and its binary size.Detection cost, measured 2026-12-06 with raw V8 calls (not
CompileFileModule), as for Q14: the 14.9 Mac Catalyst static libraries on an M-series Mac, a fresh isolate per sample, the median of 15, prettier's plugin bundles (the ESM build's only module syntax is a trailingexport{}, so its CommonJS compile fails at the end). In ms:File, flags ES module compile Failed CommonJS compile + module compile CommonJS detection compile require()'s own compilebabel 311 KiB, --jitless2.35 2.01 + 2.25 1.90 1.87 typescript 880 KiB, --jitless6.34 5.16 + 6.05 4.25 4.10 flow 1.06 MiB, --jitless2.18 2.04 + 2.06 1.95 1.91 babel, --jitless --no-lazy5.68 2.45 + 5.55 5.88 5.68 typescript, --jitless --no-lazy12.09 5.87 + 11.66 12.31 11.74 flow, --jitless --no-lazy4.44 2.42 + 4.34 4.58 4.38 Reading the header on the remembered path costs 0.014 to 0.036 ms. A cold detection about doubles a
.jsfile's compile: a failed CommonJS compile before an ES module's, a second compile beforerequire()'s. Under--no-lazythe CommonJS detection is a full eager compile. Only the first boot with the cache on, and every isolate with it off, pays. - It
-
A webpack
bundle.jswith no module syntax, reached byimport(arequire()of it, the usual entry, is unchanged):- iOS: it was compiled as a strict ES module, unwrapped, beside and
apart from
require(), so it could run a second time. It is now CommonJS:require()runs it once, as its unwrapped sloppy classic script (top-levelvars become globals,thisis the global object), anddefaultis{}, asrequire('./bundle.js')returns. - Android: it was a strict ES module, where
moduleandexportsare undefined. It is now the CommonJS filerequire()loads, with the same cache.
- iOS: it was compiled as a strict ES module, unwrapped, beside and
apart from
-
JS-visible changes, iOS:
- A
.jsfile reached byimportwith module syntax, top-levelawaitor a redeclared CommonJS name was a SyntaxError (it was wrapped in the CommonJS function), and loads as an ES module. - A
.jsfile without module syntax compiled as an ES module wrapping a function that never ran: nothing ran,import()gave an empty namespace and a default import failed to link. It now runs throughrequire()and its cache, exportsdefaultand'module.exports', and a throw rejectsimport()with the thrown value. bundle.js, above.- Any other extension (
.cjs,.ts, none) reached byimportwas an ES module wrapping a CommonJS function that never ran, like a.jsfile. It now runs throughrequire(), as a.jsfile without module syntax does; ES module syntax in it is a SyntaxError from the CommonJS compile. configureLoaderwith a functionimportMap, or one whosetoJSONreturns undefined, throws TypeError "configureLoader: importMap must be an object or a JSON string" instead of a parse error.- Debug builds gain
httpFetchDiagnosticsandstreamedCompileStatsoncens-module.jsforwards them. AremoteUrlMatchesAllowlistentry holding a lone surrogate is dropped, as the app config's array drops one (ToExactUtf8); iOS read it throughNSString. createRequire("file://…#…")keeps the#in the path, as Android does; iOS cut the path at the#. A URL object's fragment is still dropped.- A C++ exception in a binding member is a JS exception, not a crash.
- The facade after
loader::Quiescethrows "The module loader is shutting down", and a facade that cannot be built throws the core's texts ("Cannot compile/link/evaluate the require() facade for "). - Once the isolate's loader state is gone,
import.metais left empty instead of getting the app root's strings. - Every cache file is stale once (format version 2).
- A
-
JS-visible changes, Android:
- A
.jsfile without module syntax was a strict ES module:moduleandexportswere undefined, a default import failed to link, and it ran apart fromrequire(). It now runs throughrequire(), as on iOS. - A
.jsfile that parses neither way reports the CommonJS compile's SyntaxError, as Node does. - Any other extension (
.cjs,.ts, none) reached byimportwas an unwrapped ES module, so ES module syntax in a.cjsfile worked. It is now CommonJS throughrequire(): such syntax is a SyntaxError, andmodule,exportsandrequirework. - The facade texts and the Quiesce error, as on iOS.
import.metais filled afterloader::Quiesce(Android's callback left it empty once the loader was closing), until the state bag closes.- Every cache file is stale once, which also drops
.mcachefiles compiled from CommonJS.jsfiles as ES modules.
- A
-
Verification:
tests/CodeCacheTest.cpp(host): the format field, markers, and corrupt headers (a marker with a payload, an ES module file with no format, an unknown format).tests/v8/ModuleImportTest.cpp, under the default, iOS and Android configurations:import.metastrings, with a query and over http; every detection row (ESM-only messages, top-levelawaitin three positions, redeclared names,return,awaitas an identifier,import()in CommonJS, syntax errors, a file that parses neither way, throws, cycles throughrequire(), the memo perStat, other extensions); the facade (live bindings, dropped with its target, after Quiesce); every binding member, error and barrier, with and without diagnostics; and a code cache mode that checks the marker and the ES module cache, then reads the marker from a new isolate.- Lanes: host ASan+UBSan (fake and ada), V8-linked ASan, and TSan on
CodeCacheTest,ModuleImportTestandLoaderHostTest; syntax-checked against iOS's and NDK 27's headers.
-
Adoption, iOS (on top of 6.5):
- Add
CommonJsModule.cpp,NsModuleBinding.cppandRequireEsm.cppto the RuntimeCommon target in the Xcode project. Runtime.mm: replace the twoSet…Callbackcalls withloader::InstallHostCallbacks(isolate)and delete the staticInitializeImportMetaObject.ModuleInternalCallbacks.mm: deleteGetOrCreateRequireFacadeandBuildNsModuleBinding.NsBuiltinModules.cppcallsloader::BuildNsModuleBinding(context, binding, RuntimeConfig.IsDebug).ModuleInternal.mm's require(esm) path calls the core's facade and turnsJsErrorandTerminatedinto its own exceptions.- Implement
platform::InstallCreateRequireBindingwithModuleInternal::InstallCreateRequireBinding. - Implement
platform::RequireFileForImportwithLoadImpland the require cache, convertingNativeScriptExceptionto a pending exception. A module still loading gives its exports so far;bundle.jsgives{}. The path is canonical and names an existing file, so skipResolvePath. It can end in anything but.mjsand.json:LoadImplthrows "Unsupported file extension: " for anything but.js,.mjsand.json(an extensionless path included), so load such a file as a CommonJS script (LoadModule's classic path, with the CommonJS wrapper) under its path in the require cache.require('./x.cjs')itself still throws until step 8. - Delete
platform::FileModuleSourceWrap(ModuleInternal.mm's definition).LoadClassicScripttakes its wrap from a private helper, today'sModuleSourceWrapbody: no wrap forbundle.jsor an ES module path, the CommonJS wrapper otherwise. ModuleInternal::CompileFileEsModule, used byLoadESModule, callsCompileFileModule(or serves.mjsonly) and passes no wrap: a.jsor.cjsentry would otherwise skip detection, and a.jsone overwrite its marker.js/ns-module.jsforwardshttpFetchDiagnosticsandstreamedCompileStats, and itsfileUrlToPathkeeps a#in the path, as Android's does (decided 2026-12-06).RefreshLoaderConfigskips itsappRootOriginandlegacyOriginsoverride when the app config setsappSchemeOrigins: true.
- Add
-
Adoption, Android (on top of 6.5):
- The core's sources come in through
add_subdirectory; nothing to list. Runtime.cpp:loader::InstallHostCallbacks(isolate)replaces the twoSet…Callbackcalls. DeleteInitializeImportMetaObject,GetOrCreateRequireFacadeandBuildNsModuleBindingfromModuleInternalCallbacks.cpp.NsBuiltinModules.cppcallsloader::BuildNsModuleBinding(context, binding, <debuggable>), then addsforcePlatformHttpTransportinside its own barrier.ModuleInternal.cpp's require(esm) path calls the core's facade and turnsJsErrorandTerminatedinto its own exceptions.- Implement
platform::RequireFileForImport(therequire()cache, a pending exception on failure) andplatform::InstallCreateRequireBinding. As on iOS, the path is canonical and can end in anything but.mjsand.json: neitherModule.java's resolution (it appends.jsor.mjsto an unknown extension) norLoadImpl(it throws "Unsupported file extension: " for anything but.js,.mjs,.jsonand.so) takes it, so load the file by path as a CommonJS script (LoadScript). A.sopath:LoadModule's addon path gives the addon's exports, asrequire()does; refusing it instead is the alternative. - Delete
platform::FileModuleSourceWrap(RuntimeCommonPlatform.cpp). ModuleInternal::CompileFileEsModule: as on iOS.InitLoaderConfigskips its override underappSchemeOrigins.
- The core's sources come in through
-
Expectations that move: none found, searching both test trees at iOS
dbc010c5and Android9768a8a4c. No test imports an existing local.jsfile withimport(the shared tests reachsibling-cjs.jsonly throughcreateRequire; iOS's/nonexistent-module-404.jsrow only checks that it rejects), and none checks the facade's texts. Noimportin either tree (the shared tests included) names a local file other than.mjs,.jsor.json. The sharedImport/ImportCommonJStest hasimport file from './file', but inside a.jsfile thatrequire()loads, which this unit does not change (it isxiton iOS). Android'stestEsmHttpLoader.jsalready expects "importMap must be an object or a JSON string"; iOS has no such row. -
Cached
import()trims. Android's 6.4/6.5 adoption measured a cachedimport()8–12% slower than before. Three changes:- The replaced-loop check (
LivenessFor, aplatform::LoopForandshared_ptrtraffic) runs where a walk hands work to the loop: file jobs, fetches, parked walks, the pumped wait, and the file-job wait check. A walk only creates the token, once. A walk that only meets registered modules posts nothing, so it is not checked; one that posts after a replacement still aborts. - A file
import()moves its resolution and specifier into the walk's completion, and the walk moves aFromResolutionroot's strings instead of copying them.StartModuleGraphLoadtakes its root by value (source-compatible). - A file
import()whose module is registered and neither uninstantiated nor errored settles without a walk: the walk would stop at that root and complete insideStartModuleGraphLoad, soSettleFileImportruns as its completion would, in the same call. Attribute checks run before, as they did. Settling takes 2 microtask turns with and without the walk (tested, top-level await included).
Measured with
ModuleImportTest bench(opt-in, never inall): the V8-linked lane built Release, the Android configuration, 20,000 sequential awaitedimport()s of an evaluated module per sample, the median of 15 samples per run, then the median of 5 runs with the builds interleaved. Microseconds per import:Specifier Before Liveness + moves + no walk bare, import-mapped 4.04 3.97 3.70 2.57 (−36%) ./relative3.55 3.55 3.41 2.09 (−41%) file://URL4.66 4.68 4.30 3.32 (−29%) The liveness change is within noise on the host loop, whose
LoopForis cheap; the profile's 1% was Android's. - The replaced-loop check (
-
Decided 2026-12-06 (the questions this unit raised):
- With the code cache off (Android's default, debug builds), every boot detects again. Accepted.
- Named exports:
defaultand'module.exports'only; merve is a later unit (above). - Any other extension is CommonJS, and
FileModuleSourceWrapis deleted (above). invalidateModuleson a CommonJS module leaves therequire()cache alone, so the nextimportgets the old exports, until step 8 owns that cache.- One
.jsfile under two queries is two modules and onerequire()entry. Accepted:require()has no queries. - The detection compile reports
scriptParsedorscriptFailedToParseto the inspector, as Node's does. Accepted. - An ES module
.jsstays an inline compile, never a file job: apps put ES modules in.mjs. fileUrlToPathinns-module.jskeeps a#in the path (Android's): the runtime's ownfile:URLs never carry a fragment, and legacy ones spell a#in the path verbatim (Q1).- Confirmed as built: the
'module.exports'export, a throwing CommonJS module rejectingimport()with the thrown value, the facade's texts and its throw afterloader::Quiesce.
-
Evaluation layer:
EvaluateModuleGraph,LoadESModuleand the main-entry boot (C1, C2, C5). Planned as units 7.1–7.4; the boot model below, decided 2026-12-06, replaced 7.3 and 7.4 (the boot backstop). Built (see "Built: 7").Decided 2026-12-06.
- Boot is a pumping require of the main entry: one call that returns
only after everything the entry loads has settled, or throws. The core
throws
JsError(a rejection at any poll, the deadline, a load, link or evaluate failure) orTerminated(termination outranks settlement, C1/C2), or returnskSettledorkHandedOffwith the pending entry promise. It never asserts, aborts or logs a fatal error: C5 (a boot rejection is fatal) and Q2 (termination at boot is fatal on Android too) live in each runtime's catch at its boot call. - The hold pumps
PumpMode::kPlatformWork, so timers run, for up tokModuleSettleSeconds(60 s), and settles when the entry's evaluation is no longer pending and this isolate has no graph walk running (Q11): animport()nobody awaited must not be dropped when iOS'smain()falls through toUIApplicationMain. - Hand-off: a runtime-supplied predicate, asked before each slice.
Null is strict. Android passes null. iOS passes "the
UIApplicationMaintask is queued" (!Tasks::Empty()); that is a runtime choice, and strict is the alternative, a one-line change at the iOS call. After a hand-off the runtime attaches a rejection handler to the returned promise; it runs as a microtask under the UI run loop, so it routes to the runtime's uncaught-error path and never throws C++ through V8. - Main entry only: Android's later
runModulecalls (@JavaScriptImplementationclasses,inspector_modules) lose the boot hold (B5, Q10). A CommonJS main entry stays in the runtime until step 8 and gets the same hold throughHoldBoot. - The 1 s local window (
kLocalEntryYieldSeconds) is gone, for every entry. A local worker or tooling entry is not pumped in place: the walk runs as before, then the evaluation promise comes back at once and the worker's own loop settles it, the worker enabling its message queue and reporting a rejection from that promise's handlers. An http(s) entry keeps its in-pump settle with the 60 s deadline: the dev client needs its failure synchronously. - A nested boot call throws
JsError. - Q3 a rejection that becomes a throw is marked handled; Q4 iOS's
Debug-only error modal leaves evaluation; Q5 a file root is keyed by
CanonicalFilePath; Q6 a link failure evicts the root; Q7 "The module loader is shutting down"; Q8 a pumping require waits for a module whose top-level await is still running; Q9 Node'sERR_REQUIRE_CYCLE_MODULE, as its own change; Q12 never pump off the loop's home thread; Q13 CommonJS entries stay in the runtimes until step 8; Q14 deadlines keep counting while a debugger holds the isolate paused; Q15 one timeout text, the core's; Q16 time limits are core constants.
Built: 7.
- Core API:
ns/loader/EvaluationPolicy.h(V8-free):ModuleEvaluationPolicy(kSyncStrict0,kSyncPumping1,kAsync2, the integers the require factory's JS passes),ModuleEvaluationOptions(policy,deadlineSeconds,timeoutBehavior,pumpPlatformWork) withRequire(policy),kModuleSettleSeconds(60) andIsEsModuleEntry.ns/loader/Evaluate.h:EvaluateModuleGraph(context, module, key, options),LoadEsModule(context, pathOrUrl, options)andRequireEsModule(context, path, options), which shapes the result as Node's require(esm) does: the'module.exports'export, else the namespace when it has no default or exports__esModule, else the facade's namespace.ns/loader/Boot.h:RunMainEntry,HoldBoot,RunEsModuleEntry,BootOptions,BootOutcome,BootResult.ns/loader/GraphLoad.h:HasPendingGraphWork(isolate), this isolate's walks only. The global overload stays for the runtimes' backstops until they adopt.- No up-call. The hand-off predicate is a parameter, evaluated during
the pump; iOS's
Tasks::Drain()runs afterRunMainEntryreturns, outside the Locker.
- Texts (each header lists its own):
- the strict refusal, the microtask refusal and "Top-level await timed out for ES module ", as Android spells them today;
- "Module evaluation promise rejected: — ", thrown as
the reason itself (
JsError::FromValue); - "Cannot evaluate/compile/instantiate module ", "Cannot load ES module " (an http root, with the loader's reason), "Cannot find module ";
- "The module loader is shutting down";
- "Cannot require() ES Module in a cycle." with code
ERR_REQUIRE_CYCLE_MODULE; - "The main entry module '' never settled within 60s", and "The main entry module '' is still evaluating, and a boot off the event loop's home thread cannot wait for it";
- "A boot call is already running on this isolate".
- Behaviour as built:
- Pumping happens on the loop's home thread only. Elsewhere a wait ends at once, as a deadline that has passed (Q12).
EvaluateModuleGraphnever callsEvaluate()on a module that is evaluating (V8 CHECK-fails on it): it returns empty, and a load throwsERR_REQUIRE_CYCLE_MODULEinstead (Q9).- A registered root is reused by status: errored is evicted and loaded
again; instantiated or uninstantiated is linked and evaluated; an
evaluated graph whose top-level await is still running is refused
under
kSyncStrict, waited for underkSyncPumping(Q8) and returned underkAsync. The Q8 wait holds noSyncModuleLoadScope: the walk it waits on (animport()inside the awaited module) must keep running. From a microtask, a pumping load is refused only while that evaluation is pending or before it starts; a settled one returns its namespace. - A call owns the evaluation it started (the module was instantiated
when it called
Evaluate()). Only the owner evicts on a failedEvaluate(), a termination or a deadline (kThrow, the boot), and only while the key still maps to that module instance; an evaluation started by animport()stays registered for the next caller. A rejection evicts the instance whoever started it, so the next load evaluates it again. - Termination is checked before and after
Evaluate()under every policy, pumped or not, and before a rejection is thrown. - A promise whose rejection the core turns into a throw is marked
handled before any pump (
kThrow, the boot hold, an http entry), so a late rejection is never also an unhandled one.kReturnPendingleaves it unmarked: the caller gets it back. - One deadline covers an http(s) graph walk and the settle, for a pumping load and for the boot.
loader::Quiesceends any wait: a pumping load or the boot hold with the entry pending throws "The module loader is shutting down"; the hold over walks only returnskSettled.RequireEsModuleof a module still evaluating (kAsync, or past akReturnPendingdeadline) returns its namespace unshaped: reading the default export would throw a TDZReferenceError.- The boot's ladder after the pump: termination (evict if still
pending), then a rejection (also when the hand-off is true), then
settled, then handed off (the promise if still pending), then, with
the entry pending,
loader::Quiesce("The module loader is shutting down"), a boot off the home thread (its own text, no eviction), and the deadline (evict, throw). The boot evicts on termination or the deadline only an evaluation it started. A deadline that passes with only walks running returnskSettled: each walk ends on its own transport deadline and reports to its own importer. RunMainEntrykeeps the evaluation promiseEvaluate()returned, so a late rejection is observed (B1); a caughtrequire()of a throwing module is not also an unhandled rejection (B2); an http failure carries the loader's reason (B3).RunEsModuleEntry: a local entry is evaluated without a pump. Empty when it fulfilled, the pending promise (unhandled, for the caller to report) while its top-level await runs, a throw (marked handled, evicted) when it rejected inside the call: a body that threw before its first await, or a top-level await that resumed through microtasks alone. An http(s) entry pumps platform work, with one 60 s deadline for the fetch and the settle, and throws at the deadline, as today.- Known, as the code being replaced behaves:
- Indirect cycles: a nested load whose graph imports a module still
evaluating up the stack, without its root being that module,
evaluates and sees that module's bindings in their TDZ. Only a
root evaluating up the stack throws
ERR_REQUIRE_CYCLE_MODULE. - A registered, uninstantiated file root with an http(s) import is linked without a walk: each http edge falls back to the blocking synchronous fetch and logs "module graph walk missed".
- A failing http(s) root is fetched twice, by the walk and then by the blocking fallback, which logs "module graph walk missed" for an ordinary 404.
- Indirect cycles: a nested load whose graph imports a module still
evaluating up the stack, without its root being that module,
evaluates and sees that module's bindings in their TDZ. Only a
root evaluating up the stack throws
- JS-visible changes, both:
- A boot rejection is fatal on both, at any poll; the boot deadline is 60 s instead of 120 s; timers run while the main entry boots.
- A pumping
require()of a module whose top-level await is still running waits for it instead of returning a namespace in its TDZ. - A
require()of a module still evaluating up the stack throwsERR_REQUIRE_CYCLE_MODULEinstead of returning a partial namespace. - After
loader::Quiesceevery load throws "The module loader is shutting down", replacing the four "empty namespace" texts. - A local worker entry whose top-level await waits on a task (a timer, I/O, a message) always returns before it settles, so messages wait for it in the queue and its rejection reaches the parent through the entry promise's handler, where one that settled within 1 s did both inside the entry call. One that resumes through microtasks alone still settles inside the entry call. iOS EventLoopTests "runs an ES module worker entry whose top-level await parks past the yield window" and the "outlived the settle window" spec must still pass on adoption; their names may need rewording.
- A local worker entry whose top-level await rejects within 1 s after
waiting on a task took the synchronous error route and now takes the one a later rejection
already takes. iOS: the worker's own
onerrorruns first and the worker keeps running, where before the parent got the error with its line and the worker was terminated. Android: the worker'sonerrorgets "Unhandled promise rejection: " instead of the error. A body that throws before its first await, or a rejection reached through microtasks alone, keeps the synchronous route. No test pins the task-waiting case.
- JS-visible changes, iOS: a late main-entry rejection is fatal (it
was missed, B1); a failing http entry reports the loader's reason
inside "Cannot load ES module" (B3); an ES main entry has no 1 s window
before
UIApplicationMain, it hands off as soon asUIApplicationMainis queued. - JS-visible changes, Android: a link failure evicts the root, so the
next
require()recompiles it (Q6); a path containing?is one file (Q5); termination at boot is fatal (Q2);@JavaScriptImplementationandinspector_modulesloads no longer get the boot hold (B5). - Verification:
tests/EvaluationPolicyTest.cpp(host: theRequire()factory, the policy integers,IsEsModuleEntry) andtests/v8/EvaluateTest.cppunder the default, iOS and Android configurations: every refusal, rejection shape, timeout and termination order ofEvaluateModuleGraph; file and http roots, registry hits in each status, Q5–Q9, the three export shapes and the unregistered-facade throw; boot settle, rejection at the first poll and later, rejection over hand-off, deadline, termination over settlement and before boot, hand-off with the loop reference count back where it was, null predicate is strict, the graph-walk hold for an un-awaitedimport()(both entry kinds) and its deadline, nested boot calls, B2, and worker entries (pending at once, a synchronous throw, http). Ownership: a Q8 wait on animport()-started evaluation whose own walk must finish, no eviction of it at a deadline or termination, eviction by instance, a settled async graph loaded from a microtask, termination where nothing pumps (every policy, worker entries, a registered root), no TDZ throw fromRequireEsModuleof a pending module, no unhandled-rejection event for a pumped or boot late rejection, one deadline over walk and settle, a non-root dependency's top-level await,ERR_REQUIRE_CYCLE_MODULEunderkSyncStrict. Boot edges: off the home thread, afterQuiesce, termination with the entry pending, an http main entry and its 404,Quiesceinside the hold and inside a pumping load. Lanes: host ASan+UBSan (fake and ada), V8-linked ASan and plain, TSan onCodeCacheTest,ModuleImportTest,LoaderHostTestandEvaluateTest, clang-format 22.1.8; syntax-checked against iOS's and NDK 27's headers. - Adoption, iOS (paths under
NativeScript/, lines at both runtimes'feat/runtime-common, iOS12cd4fe0):- Add
Boot.cpp,Evaluate.cppandEvaluationPolicy.cppto the RuntimeCommon target. runtime/Tasks.h/.cpp: addstatic bool Empty().runtime/Runtime.mmRunMainScript(461-482): resolve the main entry; an ES entry (loader::IsEsModuleEntry) callsloader::RunMainEntry(context, entry, {handOff = [] { return !tns::Tasks::Empty(); }}); a CommonJS one runs today'srequire, thenloader::HoldBootwith the same options. OnkHandedOffwith a pending entry, attach the rejection handler (above).JsErrorandTerminatedstay fatal there. DeletePollMainEntryEvaluation(491-508),EvictMainEntry(510-525) and their declarations (Runtime.h:83-87, 96-99).NativeScript.mmrunMainApplication(132-237): delete the backstop (152-236: the first poll, thefor (;;)loop at 170-211, the fatal assembly at 219-235); keepRunMainScript, thenTasks::Drain().runtime/ModuleInternal.h: deletekModuleEvaluateDeadlineSeconds,ModuleEvaluationPolicy,ModuleEvaluationOptions,EvaluateModuleGraphandEntryEvaluationState(9-52),CompileFileEsModule(91-93),PendingEntryEvaluation(100-101),PollEntryEvaluation(107-109) andLoadESModule(131-133); use the core's types.runtime/ModuleInternal.mm: deleteBootEntryEvaluationOptions(54-70),CanonicalizeModulePath(93-100),NamespaceHasOwn,RegisteredModuleForPathandRequireExportsForNamespace(699-759),CompileFileEsModule(999-1006), the entry probes (1011-1065),LogEsmPhaseand the throw helpers (1068-1189),EvaluateModuleGraph(1191-1372),ThrowIfLoadInterruptedByTerminationandLoadESModule(1377-1598), andIsModuleLoaderClosed(104-106) if nothing else uses it.IsESModule(38-41) becomesloader::IsEsModuleEntry.LoadModule's ES branch (809) callsloader::RequireEsModule;LoadScript(934) callsloader::LoadEsModule.RequireEvaluationOptions(78-87) builds the core's options (pumpRunLoopbecomespumpPlatformWorkat 68, 84, 348, 377, 544; the JS argument keeps its name).RunModule's ES branch (222-263) serves workers and tooling throughloader::RunEsModuleEntry.Worker.mm(570-628): use the promiseRunEsModuleEntryreturned instead of thePendingEntryEvaluationre-probe (576); the handlers stay.inspector/JsV8InspectorClient.mm(1560):inspector_modules.mjsthroughRunEsModuleEntry; its catches (1561-1568) already coverJsErrorandTerminated.
- Add
- Adoption, Android (paths under
test-app/runtime/src/main/, lines at80193feec):- Nothing to list in the build.
java/com/tns/Runtime.javarun()(922-930): call a new main-only JNI method. Its C++ side callsloader::RunMainEntry(context, path, {})(null hand-off: strict) for an ES entry, or today'sLoadthenloader::HoldBoot(context, {})for a CommonJS one, and makesJsErrorandTerminatedfatal (C5, Q2):runModule's ladder incpp/com_tns_Runtime.cpp(222-258) swallowsTerminated(247-248).cpp/Runtime.cpp: deleteHoldBootBackstop(342-419) and its calls inRunModule(429, 435).runModulekeeps serving@JavaScriptImplementation(Runtime.java:1077) andinspector_moduleswithout a hold.cpp/ModuleInternal.h: delete 20-68 (the deadline constant, policy, entry state, options andEvaluateModuleGraph),IsESModule(96),LoadESModule(112-113),CompileFileEsModule(142-143),PendingEntryEvaluation(154-155) andPollEntryEvaluation(164-166).cpp/ModuleInternal.cpp: deleteRejectionDetailandPromiseRejectionMessage(51-115),BootEntryEvaluationOptions(229-241),NamespaceHasOwn,RegisteredModuleForPathandRequireExportsForNamespace(798-856),CompileFileEsModule(1085-1091),LogEsmPhase,DescribeModuleStatus,ClassifyV8Failureand the anonymous namespace (1094-1233),EvaluateModuleGraph(1235-1368), the entry probes (1373-1436) andLoadESModule(1443-1617).LoadModule's ES branch (884, 898-900) callsloader::RequireEsModule;RequireEvaluationOptions(247-258) builds the core's options (pumpRunLoopat 236, 253, 270, 298, 358, 595).Load's ES branch (633-649) serves the worker throughloader::RunEsModuleEntry.inspector_modulesis loaded by bare name throughrequire(), not as an entry. A@JavaScriptImplementation.mjs(Runtime.java:1077) must define its class beforecreateJSInstancegoes on, so it loads throughloader::LoadEsModulewithRequire(kSyncPumping), which pumps V8 tasks only: one whose top-level await waits on a timer is unsupported, and throws the timeout after 60 s.cpp/WorkerWrapper.cpp(641-690): use the promiseRunEsModuleEntryreturned instead of the re-probe (642); the handlers stay.cpp/JsV8InspectorClient.cppinit()(1218-1246): catchJsErrorandTerminatedaroundregisterModules(); it catches onlyNativeScriptException(1242-1245).
- Specs to add on adoption (shared tests, both runtimes): one module
instance for
import()thenrequire()of the same.mjs, and the reverse, which gates Q5; acreatePumpingRequireof a module whose top-level await is still running gets its settled exports (Q8); arequire()cycle through a static import throwsERR_REQUIRE_CYCLE_MODULE(Q9). Comments that describe the entry pump go stale: AndroidesmEntryTimerWorker.mjs(its timer now fires in the worker's loop),esmEntryNeverSettlesWorker.mjsand the terminate spec intestWorkerEsmEntry.js, iOSworkerTerminate/parkedEntryWorker.mjsand the "any point of its startup" spec inWorkerTerminateTests.js; their expectations hold. - Left for step 8: the CommonJS main entry moves into
RunMainEntry, andHoldBootloses its last caller;require()'s resolver, cache and wrapper; thecreateRequirebinding andrequire-factory.js's policy plumbing (Transitional.h).
- Boot is a pumping require of the main entry: one call that returns
only after everything the entry loads has settled, or throws. The core
throws
-
CJS core: the resolver (A4–A7), the require cache and wrapper.
Module.javabecomes JNI wrappers. iOS turns onwalkNodeModules, and the shared-testxits must pass.Units: 8.1 import-map scope keys (ESM), 8.2 the resolver and entry resolution, 8.3 the CommonJS compile and its code cache, 8.4 the require cache, module object and
require()itself, 8.5 the Node surface. 8.4 and 8.5 wait for step 7. Every question of the step 8 plan (Q1–Q27) was decided on 2026-12-06 as recommended; 8.1 ships on its own. Q18 went further, the same day:__nativeRequiregoes as well as__requireOverride, and@nativescript/vite, its only user, moves tons:module'screateRequire.Built: 8.1.
- Core API:
ImportMapScopePrefix(scopeKey, config)(ns/loader/ImportMap.h) takes the isolate'sLoaderConfig;ParseImportMappassesLoaderConfigFor(isolate). - Scope keys: a file importer is matched by its path, so a key is
turned into the path it names:
- a
file:orapp:key: the pathFileUrlToPathgives (virtual roots andappRootAliasesincluded), plus the trailing/the key was written with. A keyFileUrlToPathrefuses stays verbatim and matches nothing; - a
~/key: the path a~/specifier names,..stopping atappRoot, plus its trailing/; - http(s) keys as before; root-absolute and bare keys unchanged (Q21).
Four spellings of one directory (
app:///lib/,file:///app/lib/,~/lib/,<appRoot>/lib/) are one scope, and the last one written wins, as for any duplicate key.
- a
- ESM only:
require()never reads the import map (Q20). - Runtimes adopt by the submodule bump; neither builds scopes itself.
A bump to 155e262 carries 8.1 alone. A bump past 8.3 also brings code
cache format version 3 (every existing cache is stale once) and the
detection's kept CommonJS functions, which nothing takes until the
runtime calls
CompileFileCommonJs: up to 16 functions and their source stay alive untilQuiesce. - Tests:
tests/ImportMapTest.cpp(every spelling, refused URLs, the collapse),tests/ResolverTest.cpp(scoped lookups from file importers),tests/v8/ModuleImportTest.cpp(configureLoaderwithapp:and~/scope keys, end to end).
Built: 8.2 (core).
- Core API (V8-free unless noted):
ns/loader/RequireResolver.h:ResolveRequire(specifier, fromDir, config, packages)returns aRequireResolution(kind: unresolved, invalid package, file, native addon, or URL and invalid entry path fromResolveEntryonly;format: CommonJS, JSON, ES module or native addon;path,specifier,attempted,packageJson,packageError).RequireLookupPaths(fromDir, config),RequireErrorMessage,RequireErrorCode,ResolveMainEntry(config, packages),ResolveEntry(specifier, fromDir, config, packages)andRequireResolveCache.ns/loader/PackageJson.h:ParsePackageJson(text)andPackageJsonCache(Q22).ns/loader/CommonJs.h(V8):CachedRequireResolution(isolate, specifier, fromDir),ResolveRequireFor(isolate, specifier, fromDir)andRequireError(isolate, resolution).LoaderConfig:walkNodeModules(default true; config only, Q14),globalModuleRoots,nativeLibraryScheme,nativeAddonExtensions. Both runtimes setglobalModuleRootsto{<appRoot>/tns_modules, <appRoot>/tns_modules/tns-core-modules}; Android setsnativeLibraryScheme"system_lib://"andnativeAddonExtensions{".so"}, iOS leaves both empty.
- The algorithm (decided 2026-12-06):
- Empty, or holding a NUL: unresolved, nothing tried.
nativeLibraryScheme+ name: a native addon, the name verbatim../,../,.,..: joined tofromDirlexically (A1)..foois a package name, as in Node.~and~/: belowappRoot,..stopping there (Q21)./x: a device path (Q21), never moved underappRoot, so/appleand/app/xare themselves (B3).- Package names:
<d>/node_modulesforfromDirand each ancestord, nearest first, skipping adnamednode_modules, up to and including<appRoot>/node_modulesfor afromDirunderappRootand up to/node_modulesotherwise; thenglobalModuleRootsin order (A4, Q3).walkNodeModulesfalse leaves only the global roots. - A candidate
Xis tried as a file (X,X.js,X.mjs,X.json; Q5, any extension as written, Q6), then as a directory: a validpackage.jsonmainMas a file and then asM/index.*, thenX/index.js,X/index.mjs,X/index.json. Apackage.jsonbelowMis never read (Q8), so"main": "."ends at the index (B6). A specifier ending in/,.or..names a directory only, sorequire("./")is the requiring directory's package, not the app's main (Q11). - The first
package.jsonon the path that is not valid JSON, not an object, or whosemainis a lone surrogate, U+0000 or ill-formed UTF-8 ends the lookup as an invalid package (Q9). Amainthat is not a non-empty string is no main. - The format follows the extension:
.json,.mjs,nativeAddonExtensions, else CommonJS (Q6), so.cjs,LICENSEand.tsload as CommonJS. - Every path is
CanonicalFilePath, so a file reached byrequireand byimportunder the same spelling has one path (B1). - Only files are probed (§4.3), plus one
Statper package-name lookup directory (<dir>/node_modulesand each global root): one that is not a directory is skipped without probing inside it.
- Errors (Q9, Q10): "Cannot find module '' (tried )", the parenthesis omitted when nothing was tried, with
code: 'MODULE_NOT_FOUND'andrequireStack: []; "Unable to locate main entry in <package.json>: " withcode: 'ERR_INVALID_PACKAGE_CONFIG'.RequireErrorbuilds the error object the same way in Debug and Release. - Memos (Q4, Q23): each
ModuleLoaderStatekeeps aPackageJsonCache(oneStatper use; apackage.jsonis read again when its size or freshness token changed, and a missing one is dropped, never remembered) and aRequireResolveCachekeyed byfromDir '\0' specifier(an emptyfromDirkeys asappRoot), holding found resolutions only. A lookup is heterogeneous: no allocation, noStat.InvalidateModulesclears both. The runtime checks a hit'spathagainst its own require cache and resolves again withResolveRequireForwhen the module is gone. - Boot cost. A missing candidate costs four file probes, plus one
package.jsonprobe and three index probes when it is tried as a directory: eight per node_modules directory walked that exists, one per missing one (the review round's directoryStat). A package name served fromtns-core-modulesthree directories belowappRootcost 46Stats on its first resolution per (directory, specifier) as first built; a relative./xthat namesx.js, 2. The timings below predate the directoryStatand thepackage.jsonStatper use. Measured on an M-series Mac, Release, real APFSstat(RequireResolverTest benchhas the fake-FS variant), per resolution:./x→x.js2.3–3 µs; an exact file 1.7–2.5 µs; a packagemain15 µs cold, 5 µs once itspackage.jsonis remembered; a nearest-node_modulesname 8 µs; thetns-core-modulesname 32–40 µs; a memo hit 19–20 ns. On-deviceStat(APK assets in particular) is not measured. - Departures from the plan:
- The V8-free functions return a
RequireResolution, not a string and a thrownJsError(JsErrorholds av8::Global).RequireErroris the V8 half. ResolveEntryfollows Node'sWorker(decided 2026-12-06): a URL (://) passes through askUrl;./,../,~/and/names resolve asrequire()resolves them; any other name, bare and empty ones included, iskInvalidEntryPath, whichRequireErrorthrows as Node'sTypeErrorwith codeERR_WORKER_PATHand Node v24's text (The worker script or module filename must be an absolute path or a relative path starting with './' or '../'. Received "<name>", plus Node'sdata:hint). Nothing is probed for it: no node_modules lookup and no caller-directory join. Absolute paths are canonicalized and probed (/abs/workerfindsworker.js) where the plan let them pass through.- Documented difference from Node (decided 2026-12-06):
./and../worker names resolve against the calling file's directory first, the browser's rule, and when nothing is found there, against the app root, which stands in for Node's cwd (an app has none). Both runtimes do this today; the core'sResolveEntrynow does it for both. When neither finds the file, the error is the caller-directory attempt's; a brokenpackage.jsonnext to the caller (kInvalidPackage) is reported, not retried.~/is NativeScript's app-root form and stays. nativeAddonExtensionsis new: the plan's "explicit.soor.node" needs a per-platform list.~xis an app-root form, as in ESM, not a package name.
- The V8-free functions return a
- Host tests:
tests/PackageJsonTest.cpp(strict grammar,mainrules, 200 000-deep nesting, the cache's reads),tests/RequireResolverTest.cpp(the §1.3 cases, the five node_modules cases, B3, B6, Q5–Q11, Q21, the texts, lookup paths, addons, entry resolution, agreement withResolveSpecifier,Statcounts, memo allocations).tests/v8/CommonJsTest.cpp:ParsePackageJsonagainstJSON.parseon 38 000 mutated texts, the error objects, and the per-isolate memos withInvalidateModules. - Runtimes adopt (lines as of the runtime-common worktrees,
2026-12-06):
- iOS (
NativeScript/runtime/ModuleInternal.mmunless noted):RefreshLoaderConfig(RuntimeCommonPlatform.mm:387-424) setsglobalModuleRootsandwalkNodeModules(true, so the shared node_modulesxits atRequire/index.js:318-349becomeit).RequireCallback: delete the/appexpansion (:448-452), the"./"app-main case (:454-457, Q11), the./..standardization (:458-463), the~branch (:464-472) and thetns_modulesprobes (:473-491); callCachedRequireResolution/ResolveRequireForand throwRequireError. The builtin, Node-API and HTTP checks (:357-419) stay ahead of it.LoadImpl(:541-598): thebaseDir*namekey (:549-554) becomes the memo, the "Failed to resolve module" and "Cannot find module" texts (:561-573) becomeRequireError, and the extension switch (:575-595) becomesformat, so.cjsand unknown extensions load as CommonJS instead of throwing "Unsupported file extension".- Delete
ResolvePath(:842-925),ResolvePathFromPackageJson(:927-1010),ResolveMainEntryFromPackageJson(:43-76; boot at:137-142usesResolveMainEntry), theshortParentDirshortening (:668-680) and the global require's"/app"directory (:103-106);ModuleInternal.h:13,:69,:71. LoadDatareads JSON throughplatform::ReadFile, nottns::ReadText(:722), which aborts on a failed read.Worker.mm: the caller-relative probe (:388-424, on the caller's thread) callsResolveEntry, andkInvalidEntryPaththrowsRequireError'sTypeErrorfrom the constructor, as Node's does. Today a bare name skips the caller-directory join and reaches the worker thread unresolved; it now throws. Delete the app-root fallback (:426-431):ResolveEntryretries from the app root itself. The~expansion (:482-489) and the existence probe (:518-532), on the worker thread, becomeResolveEntrythere and still report throughonerror(Q25: no resolution moves threads).- The plan's
CanonicalizeModulePathdoes not exist; iOS already calls the core'sCanonicalFilePath(:748,:790).
- Android:
RuntimeCommonPlatform.cpp:88-107setsglobalModuleRoots,nativeLibrarySchemeandnativeAddonExtensions.Module.java: deleteresolvePath,resolvePathHelper,prepareRelativeOrAbsoluteDir,resolveFromFileOrDirectory,loadAsFile,loadAsDirectory,nodeModulesPaths,isFileExternal,possibleException,folderAsModuleCacheandcheckForExternalPath(:17-27,:68-346);initkeepsApplicationFilesPathonly;bootstrapApp(:348-382) andresolveEntryPath(:58-66) become JNI wrappers overResolveMainEntryandResolveEntry.bootstrapApp's "Application entry point file not found" text and its./bootstrapfallback stay in the wrapper, whose error names the last candidate tried (the./bootstrapresolution'sattempted).ResolveMainEntry'sattemptedis the package.jsonmainit tried.ModuleInternal.cpp: delete theMODULE_CLASS,RESOLVE_PATH_METHOD_IDandGET_APPLICATION_FILES_PATH_METHOD_IDlookups (:91-100,:905-907;ModuleInternal.h:156-158).LoadImpl(:597-677): the name-only key of bare names (:601, B7) becomes the memo,system_lib://(:613-618) becomeskNativeAddon, the~rewrite with its double slash (:619-624, B4) and the JNI calls (:631-648) go, and the extension switch (:655-664) becomesformat.CheckFileExists(ModuleInternal.cpp:569-581) resolves throughModule.resolvePath, so a bare worker name today takes thenode_moduleslookup; it and the worker entry code (CallbackHandlers.cpp:1775-1843) callResolveEntryinstead, and a bare name throwsERR_WORKER_PATHfrom the constructor. Delete the retry against the app root (:1834-1842):ResolveEntryretries from the app root itself.Module.resolveEntryPath's other callers:Runtime.java:929withbootstrapApp's path and:936withRuntimeHelper.java:211'sapp/tns-java-classes.jspass absolute paths, whichResolveEntrynow probes (they passed verbatim);createJSInstancepasses a@JavaScriptImplementation'sjavaScriptFile, a relative or bare name, which the Java wrapper prefixes with./unless it starts with./,../or~/. The wrapper keeps that prefix:ResolveEntryrejects a bare name.- The order changes: Android searched
tns-core-modulesfirst and readapp/tns_modulesin place ofapp/node_modules(Module.java:134-160,:336-338). No shared spec pins either (§1.3 of the plan).
- Tests that move: Android
requireExceptionTests.js:58,:85,:94,:113,:132pin "Failed to find module: … relative to: …" and take the Q10 text. iOSNsUtilTests.js:89andLoaderHardeningTests.js:154-185match substrings that the core's texts keep. SharedRequire/index.js:222(index.json) resolves now, and becomesitwith Q7's JSON primitives in 8.4.
- iOS (
Built: 8.3 (core).
- Core API (
ns/loader/FileCompile.h,ns/loader/CodeCache.h,ns/loader/CodeCacheQueue.h):kCommonJsParameters:exports,require,module,__filename,__dirname, Node's order; callers pass arguments in it.CompileFileCommonJs(isolate, context, path, origin): the file compiled withScriptCompiler::CompileFunctionand those parameters, no text added (A7), so line-1 columns inError.stack, stack frames, messages and the inspector are the file's. It Stats, reads, consumes a fresh cache, compiles and queues a cache when there was none or V8 rejected it, like the other file compiles; "Cannot find module" and "Cannot read module" areJsErrors, a compile error is left pending.CodeCacheKind::kCommonJsFunction(3), in.fcachefiles, module formatkNone;QueueCodeCache(isolate, function, entry)creates it withCreateCodeCacheForFunction. Every kind is an explicit switch: an unknown kind has no file name or entry, reads as stale and is never written.kCodeCacheFormatVersion3 (B10): every version 2 file reads as stale once.
- Q13 reuse: the
.jsdetection compiles through the same helper. When it finds CommonJS, the function is kept inModuleLoaderState(path, size, freshness token, origin; at most 16, oldest evicted; none without a freshness token or afterQuiesce), andCompileFileCommonJstakes it once when its Stat, origin and context match.EraseKey(soInvalidateModulesandRemoveModuleFromRegistry), a new detection of the path andQuiescedrop it. When the reuse hits, the file is compiled once; a miss (the cap, no freshness token, another origin) compiles it again. Whether the inspector then sees one script per URL, which the spike showedsetBreakpointByUrlneeds, was not checked. Release,--jitless, require's compile right after detection: 0.000 / 0.002 ms kept, 0.047 / 1.39 ms dropped (V8's compilation cache), 1.98 / 46.8 ms dropped after a full GC, for babel.js / typescript.js. - A7 spike (V8 14.9.207.39, Mac Catalyst libraries):
- A function cache is consumed across processes; a different-length
source rejects it; a classic cache offered to
CompileFunctionis rejected; a same-length edit is accepted with stale code, as for every kind (B5). scriptParsedreports the file's URL, start 0:0, the file's length and hash,hasSourceURLfalse, cold and consumed;getPossibleBreakpointsandsetBreakpointuse file columns.- Line-1 errors report file columns (
test.js:1:64, wrapped1:125);import()inside the function sees the file's URL. - Cost: at parity under lazy compilation (cold 1.85 vs 1.85 ms,
consume 0.037 vs 0.042 ms for babel.js); under
--no-lazy, +1–3 % cold, up to +9 % to consume and +4–11 % cache bytes.
- A function cache is consumed across processes; a different-length
source rejects it; a classic cache offered to
- Tests:
tests/CodeCacheTest.cpp(version 3, the new kind, kinds never read as each other);tests/v8/CommonJsCompileTest.cpp(parameters andthis, line-1 columns, missing and unreadable files, the cache across isolates, the detection reuse and its mismatches, cap, invalidation,Quiesce; abenchmode). The V8 host'sRequireFileForImportcompiles throughCompileFileCommonJs.ModuleImportTest's same-size, same-token edit of a CommonJS.jsnow runs the old code: require's function cache is consumed, as any cache is when the platform reports the file unchanged. - Runtimes adopt:
- iOS:
LoadClassicScript(ModuleInternal.mm:788-810) callsCompileFileCommonJs;LoadScript(:747-776) loses its run step; deleteClassicScriptWrap(:778-786), the factory check (:653-666); the arguments (:687) take Node's order.bundle.js(:643-652,:782) runs unwrapped today and needs its own path or Q18's change. - Android:
LoadScript(ModuleInternal.cpp:827-847) callsCompileFileCommonJs; the run step at:716-721goes; deleteMODULE_PROLOGUE,MODULE_EPILOGUEandMODULE_PROLOGUE_LENGTH(:909-911,ModuleInternal.h:82,:159-160) and the line-1 column correction inMetadataNode.cpp:2499-2579. The arguments (:795) take Node's order for scripts only:.soaddons receive the same array throughNSMain(:762-773) and read it by index, so they keepmodule, exports, require, ….thisstays{__extends}(Q12 (d)) until 8.4. - Both: the detection reuse hits only when require passes the
path the registry recorded and
ReportedModuleUrl(path)as the origin; anything else recompiles.
- iOS:
Built: 8.4 (core).
- Core API (
ns/loader/CommonJs.h,ns/loader/Boot.h,ns/RuntimeAccess.h,ns/LoaderConfig.h):InstallCommonJs(context): globalrequire(appRoot,Require(kSyncStrict)). There is no__nativeRequire, and__requireOverrideis not read (Q18).RequireFunctionFor(context, dir, options): one native function per (canonical dir, policy, deadline, timeout behaviour, pump) per isolate (Q24) while anything holds it,name"require",length1, not a constructor.module.require === requireinside a module, and two modules in one directory share it.ns:module's bindingcreateRequire(baseDir, pumping, deadlineSeconds, throwOnTimeout, pumpRunLoop)returns it forFileUrlPathToPath(baseDir): a directory belowvirtualFileRoots(/app) is under appRoot, as in afile:URL, sincens-module.jshands the binding afile:URL's path and iOS's legacyimport.meta.urlisfile:///app/…. A runtime callingRequireFunctionForwith such a path maps it itself.RequireFile(context, path): import of a CommonJS file, through the same cache.RunMainEntryruns a CommonJS entry itself (noHoldBoot);RunCommonJsEntry(context, path)serves worker and tooling entries. Both run a file asrequire()does, so a file already in the require cache does not run again. The main entry becomesrequire.main, cached or not; until it runs, the firstRunCommonJsEntryis.platform::RequireNativeAddon(context, request, module)(Q19): a bare Node-API name withmoduleempty, or akNativeAddonpath with the module object, cached before the call;nulloptmeans "not mine".LoaderConfig::commonJsThisHasExtends(Q12 (d)): false (iOS),thisis a fresh empty object; true (Android), a fresh object holdingglobal.__extends. Node'smodule.exportsstays a later deprecation.ns/loader/Transitional.his deleted;RequireFileForImportandInstallCreateRequireBindingare no longer up-calls.
- Behaviour:
- The require cache holds one module object per canonical path (CommonJS, JSON, addon). A cycle sees the exports so far; a module whose code throws leaves the cache. Import of a CommonJS file and a query-less import of a JSON file read the same entry, in either order (Q7); a query keeps its own value, as in Node.
invalidateModulesdrops the entries of the paths it names, and of a CommonJS file every import of it (Q17);Quiescedrops all of them, the require functions andrequire.main.- Builtins:
ns:/node:names returnplatform::BuiltinModule'sdefault. Both runtimes already export the frozen exports object there, so noBuiltinExportsup-call was added. - Errors (same in Debug and Release):
- a non-string id: Node's
ERR_INVALID_ARG_TYPETypeError, the textCreateRequireTests.js:137-161pins; - nothing found: 8.2's
RequireError; - an http(s) id: "NativeScript: require() of URL module is not supported: . Use dynamic import() instead.";
- a compile error or a module's own throw: rethrown as it is, no
wrapper text (the
Cannot compile/Error calling module functionprefixes stay in the C++ log message only); - JSON: any JSON value, primitives included; a parse error is the SyntaxError ": <V8's message>";
- a Node-API name that fails: "Failed to initialize Node-API module ''" when the addon left nothing pending; an addon path on a runtime without addons: "Cannot load native addon : this runtime loads none";
new require()throws (not a constructor).
- a non-string id: Node's
- JS protocol:
ns-module.jsis unchanged: the binding keepscreateRequire's five arguments and meanings. The runtimes deleterequire-factory.jsandBuiltinId::kRequireFactory. Android drops two globals, each needing a release note:__requireOverride(only Android'srequire-factory.jsreads it, and neither runtime's sources nor tests set it) and__nativeRequire(iOS never had it;createRequire(dir)fromns:modulereplaces it). bundle.js(Q18): the core has nobundle.jscase: an app'sbundle.jsis an ordinary CommonJS module, called with the five arguments,thisper the flag. iOS ran it as a plain script, where top-levelthisis the global, top-levelvars become globals, andmodule,exportsandrequireare the globals (or undefined). As a module they are locals, sotypeof module/typeof exportschecks take the CommonJS branch andmodule.exportsis real. iOS adoption must check a@nativescript/webpack5 build (thebundle.jsentry and every chunk it loads) for any of these reliances, and that its chunk loading works through the core's require.- Tests:
tests/v8/RequireTest.cpp(shape, module object, cache and aliases, cycles, throw rollback, syntax errors, not found, packages, URLs, invalidation,thisboth ways, JSON and its sharing with import, builtins, addons, require(esm), import of the cached CommonJS,createRequireerrors, no__nativeRequire,requireafterQuiesce);EvaluateTestholds on a CommonJS main entry;ModuleImportTest's CommonJS-to-ESM cycle now throws Node'sERR_REQUIRE_CYCLE_MODULEtext. The V8 host's own require is gone. - Runtimes adopt (iOS paths under
NativeScript/runtime/, Android undertest-app/runtime/src/main/cpp/; lines at the runtime-common worktrees of 2026-12-06):- iOS:
- Delete
js/require-factory.jsand its line intools/js2c-inputs.xcfilelist:30. ModuleInternal::Init's require-factory run and globalrequire(ModuleInternal.mm:83-113, the global's base was a literal/app) becomeloader::InstallCommonJs(context);DefineGlobalDirname(:117) stays.- Delete
CreateRequireCallbackandInstallCreateRequireBinding(:202-261),GetRequireFunction(:263-306),DescribeValueForTypeError(:308-355),RequireCallback(:357-539),LoadImpl(:540-598),LoadModule(:600-717, thebundle.jsbranch:642-652with it),LoadData(:719-745),RequireFileForImportand theTransitional.hup-calls (:1012-1062). InModuleInternal.h:InstallCreateRequireBindingthroughLoadImpl(:33-58),requireFactoryFunction_,loadedModules_andTempModule(to:110);RunMainModule's comment (:18-21) losesHoldBoot. - The Node-API branch (
ModuleInternal.mm:389-404,NapiModules::IsRegistered/GetExports) moves toplatform::RequireNativeAddoninRuntimeCommonPlatform.mm; paths returnnullopt. RunMainModule(:132-146) callsloader::RunMainEntryfor every entry;Runtime.mm:544keeps its outcome handling.RunModule(:148-200,Runtime.mm:567,Worker.mm:538) callsloader::RunCommonJsEntryfor a CommonJS file.
- Delete
- Android:
- Delete
js/require-factory.js(runtime/CMakeLists.txt:110) and thekRequireFactoryrun (ModuleInternal.cpp:109). - The global
requireinstall (:131-140) becomesloader::InstallCommonJs(context); the__nativeRequireinstall (:124-130) andRequirePublicCallbackgo with no replacement. - Delete
m_requireFunction,m_requireFactoryFunctionandm_requireCachewith their teardown (:64-69),RequireCacheKeyand the require-function cache (:146-204),CreateRequireCallback,InstallCreateRequireBindingandRequireFileForImport(:206-297), thedetermineSpecificTypeport (:299-352),DispatchRequire,RequirePublicCallbackandRequireCallbackImpl(:354-500),LoadImpl(:597-677),LoadModule(:679-825) andLoadData(:849-887);RuntimeCommonPlatform.cpp:275-290(theTransitional.hup-calls). InModuleInternal.h:InstallCreateRequireBindingandRequireFileForImport(:66-80), the require callbacks, loaders andGetRequireFunction(:103-151, keepingLoadScriptwhile anything calls it) and the three members (:163-165). - The
.sobranch (ModuleInternal.cpp:714-777) andRequireNativeCallback(:502-507) move toplatform::RequireNativeAddonfor paths with the.soextension (its Node-API registration case included):dlopen, thenNSMainwith the array it reads by index (module, exports, require, __filename, __dirname) built from the module object (exports,require,filename,path). InitLoaderConfig(RuntimeCommonPlatform.cpp:88-107) setscommonJsThisHasExtends = true.Runtime::RunMainModule(Runtime.cpp:341-358) callsloader::RunMainEntryfor every entry; theHoldBootcall (:352) goes.ModuleInternal::Load(:509-533, also@JavaScriptImplementationclasses andinspector_modulesafter boot) andLoadWorker(:537-) callloader::RunCommonJsEntryfor a CommonJS file; like today'srequire(path), a cached file does not run again.createJSInstance'srunModule(Runtime.java:1080) can run beforerun()(:924-933); the main entry still takesrequire.mainfrom it.
- Delete
- This replaces Built: 7's CommonJS adoption lines ("a CommonJS one
runs today's
require, thenloader::HoldBoot", iOS and Android). - Pinned texts that move: Android
testCreateRequire.js:63-68(resolveandmainare present now,cachestays absent). AndroidexceptionHandlingTests.js:308-321as a whole: it readse.fullMessage, which onlyNativeScriptExceptionattaches (NativeScriptException.cpp:233-254), and the SyntaxError now arrives as V8 threw it. No spec in either tree pins "Cannot parse JSON file" or "Error calling module function". The non-string id text is unchanged on both. Android's Node-API failure text becomes iOS's.
- iOS:
Built: 8.5 (core).
- Module object:
id(read-only, non-configurable),path(its directory),exports,filename,loaded(true once its code returned),paths(RequireLookupPathsof its directory, computed when first read) andrequire.filenameis the canonical path, and so isid, except"."for the module loaded asrequire.main, as in Node (decided 2026-12-06). A module already in the require cache when it becomesrequire.mainkeeps its path asid. require.resolve(request[, {paths}]): the path require() would load, or the builtin's name; the same errors as require(). Each ofpaths(absolute, or relative to the require's directory) is a directory to resolve from instead, in order; a non-array or a non-string entry throws "The property 'options.paths' is invalid. Received " (ERR_INVALID_ARG_VALUE). Only files resolve: a Node-API name throws what an unknown name throws.require.resolve.paths(request): null for a builtin,[dir]for.,..,./…and../…,[appRoot]for~/…, otherwiseRequireLookupPaths(dir)(Node's_resolveLookupPaths).require.main: the module object of the CommonJS main entry (RunMainEntry); before it runs, of the firstRunCommonJsEntry. Undefined before one ran, for an ES module entry and afterQuiesce.require.cachestays absent.- Detection (Q13):
CompileFileForRequirecompiles a.jsfile as CommonJS and reports "an ES module" when V8's error is an ES module syntax error, or a maybe-ES-module one and the file compiles as a module; the result is remembered in the 6.6 memo, so import and require detect a file once. An ES module found that way isRequireEsModule's, and a.jsmain entry with ES module syntax runs as an ES module entry. Other extensions are never detected. - Tests:
RequireTest's module object,resolve,resolve.paths,require.main(throughRunMainEntryandRunCommonJsEntry) and detection cases, the top-level-await text included. - Runtimes adopt: nothing beyond 8.4; neither runtime has
require.resolveorrequire.maintoday.
Built: 8.4–8.5 review round (2026-12-06).
- Invalidation:
InvalidateModulesof a CommonJS file's key drops its require cache entry and every registry key recorded for that file (one per query), so no import keeps the old exports whilerequire()runs the file again. - Module-run hook (§4.8):
LoaderConfig::moduleRunScope, with the name as aconst char*(Android'sModuleScopetakes one). Android main openstns::instrumentation::Frame("LoadModule <path>")andCrashBreadcrumbs::ModuleScopeinModuleInternal::LoadModule(ModuleInternal.cpp:813-818), once per CommonJS module; the adoption branch dropped them, and implements the hook with the two instead. ES modules had no scope; the core gives each evaluation root one. iOS leaves it null. - Require functions are held weakly: one stays the same function while anything holds it, and entries whose function was collected are pruned when the table doubles, so minting one per (directory, options) stays bounded by the live ones.
- Costs of a cached
require(): the Node-API up-call runs once per bare name: a name it declined is never asked again (an addon registering that name later is not found by it), and the order stays builtin, addon, file (I25), whateverrequire.resolveremembered. A.jsdetected as an ES module is remembered as one. A cachedrequire()makes noStat, read or up-call and allocates nothing (RequireTestpins the counts). A missingnode_modulesdirectory costs oneStatinstead of eight. - Entries:
RunCommonJsEntryruns a.mjsas an ES module, and a JSON or addon entry throws "Cannot run as an entry: it is not a JavaScript module" (so doesRunMainEntry). A worker entry may be~x;require('~')is the app root as a directory only. - Directories: a require function's directory is its canonical
path; only ns:module's
createRequiremaps a virtual root (a file: URL's path) to the app root, so a real directory below a virtual root keeps its own siblings. - A main entry that throws stays
require.main(id".",loadedfalse) and leaves the require cache, so a later entry sees it asrequire.mainand booting it again runs it again. - Watch: each nested
require()costs about 2 KB of native stack (the review hit a RangeError at depth 487 on the test host's main thread). Nothing obvious to trim; a deep chain on a worker's smaller stack is the case to measure. - Behaviour changes for the release notes, verified against the
runtimes' current code:
- Android parsed package.json with
org.json(comments, trailing commas, single quotes and unquoted keys accepted, a numericmaincoerced); the core's parser is strict JSON. - iOS fell back to
index.jssilently when the app's package.json did not parse; it now fails withERR_INVALID_PACKAGE_CONFIG("Unable to locate main entry in /package.json"). - iOS's Debug-only "***** JavaScript exception occurred *****" banner is gone; a failed main entry logs "Fatal: the main module failed to run".
- Errors rethrown from
require()carry nofullMessageon Android (onlyNativeScriptException::ReThrowToV8attached it). - Worker
onerror: a throwing entry's text is unchanged (minusfullMessage); iOS's missing entry was "Worker script does not exist: " and is now "Cannot find module '' (tried )"; Android's missing entry throws from the constructor; a bare name throwsERR_WORKER_PATH. - A package.json
mainstarting with/is a device path; both runtimes resolved it inside the package. - Android's worker global
requireresolved from the calling module's directory; it is bound to the app root, as on iOS. - Unchanged, for the record: a script-style CommonJS main entry never waited for its timers, and still does not.
- Android parsed package.json with
- Android adoption:
appRootAliases(Runtime.java:915) must keep pairing/data/user/0/<pkg>with/data/data/<pkg>: the require cache now keys through it, wheregetCanonicalPathfolded the two.
- Core API:
Follow-on, on the same foundation, from the infrastructure report's ranking, easiest first:
TextEncoding,StructuredClone,StructuredSerialization.- URL and
URLSearchParams/URLPattern, after the three URL drifts and Android's deprecated setter overload are fixed. BuiltinLoader,LazyGlobals,IsolateTracked.- The builtin
js/: 14 of 28 files are already byte-identical, and both sides generate the same js2c output. Events,ErrorEvents,Performance,WeakRef.Messaging, after F1.- The
EventLoopqueue bookkeeping.
The platform-owned subsystems do not move: wrapper lifetime and leak probe,
console sinks, inspector transport, Runtime, and the body of
NativeScriptException.
These need their own pass before the matching steps:
- Catalyst and visionOS builds of the core.
- Android builds without OkHttp, beyond the existing platform-transport fallback.
- The inspector, beyond its cache-control calls.
- How workers start and stop their own loader state, beyond vocabulary copying.
An independent review (Fable, 2026-12-04) checked §4.4, §4.7, §6 and §8 against
the source. Its corrections are folded in above: #2104 identity and Stat, the
pump-mode semantics, the boot hook, the interface-growth protocol, migration
order, the URL row (removed: iOS does throw), and the deadline cites.
Investigation reports (kept with the proposal's working notes, not in this repository). Their line numbers cite the baseline snapshots.
A-esm-callbacks.md: unit-by-unit ESM inventory, invariants 1–21, #622 mapping.B-cjs-codecache.md: CJS, entry, code cache, theModule.javavs iOS resolver behaviour table, invariants I1–I29.C-http.md: HTTP policy vs transport,ModuleTransportsketch, decisions D1–D10.D-infra.md: state, loop, build flags, packaging, the porting-burden table (PR pairs and lag).
The #622 overlap metric is a set comparison of whitespace-normalized added
lines of 25 characters or more. It is iOS
origin/main...origin/perf/stream-compile-lazy-imports vs the uncommitted
diff in the Android worktree perf/stream-compile-lazy-imports, as of
2026-12-04. It overcounts trivially common lines slightly and undercounts
rewritten-but-equivalent ones.