Status: proposal, 2026-12-04, updated 2026-12-05. Step 1 of §9 (this
repository and its build wiring) is done, step 4 (the app-file seam and the
code cache) is built in ns/AppFiles.h and ns/loader/, and step 5 (the
HTTP policy core) is built in ns/http/. Step 6 (the ESM core) is planned
as six units with its questions decided; unit 6.1, module identity, is built in
ns/loader/ModuleIdentity.h, and unit 6.2, loader state and the registry, in
ns/loader/LoaderState.h and ns/loader/ModuleRegistry.h; 6.3, the
resolver, in ns/loader/Resolver.h; 6.4, the graph walk, in
ns/loader/GraphLoad.h. F3 (a submodule repository), F7 (the
nativescript::common namespace) and D1–D10 are decided; the rest of §7 is
open. 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, entry probes, │
│ boot backstop loop │
│ 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. -
The iOS boot backstop has a special case: each slice also runs
Tasks::Drain(), whereUIApplicationMainmay take over and never return (NativeScript.mm:175-176). The graph walk never does this. So the core owns the backstop loop (poll entry → pump slice → evict or throw), and the platform supplies a per-slice hook (§5). Invariant: the core holds no RAII state across that hook, because it may never come back. -
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 |
TraceModuleLoad(path) → RAII scope |
Android profiler frames and crash breadcrumbs |
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 {
// Boot / per isolate
void InstallHostCallbacks(v8::Isolate*); // resolve, import(), import.meta, ns:module binding
void RunEntry(v8::Isolate*, v8::Local<v8::Context>, const std::string& path,
EntryKind /* main | worker */); // throws JsError on failure
EntryEvaluationState PollEntry(v8::Isolate*, const std::string& path, std::string* reason);
bool HasPendingGraphWork(); // a walk started and not completed or killed
// The boot backstop loop. `platformSlice` runs once per slice and may never
// return (iOS UIApplicationMain); throws JsError on a failed or timed-out entry.
void RunBootBackstop(v8::Isolate*, const std::string& entryPath,
const std::function<void()>& platformSlice);
// 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::loaderEach 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. - A local (non-HTTP) TLA settle window that stays short (1 s). The core's
PumpUntilmodes must not unify it with the 60 s deadline;EventLoopTestspins this. - 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 |
Node order. Keep the legacy roots only as config |
| A5 | node_modules walk on iOS |
none (5 shared specs xit) |
yes | Turn on through walkNodeModules; 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 ){ (stack columns corrected by length) |
Pick one. Invalidates one platform's classic caches once, which is safe only after B3 |
| 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 |
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.
Each one 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/... |
ModuleInternal.mm:547 |
step 8 |
| iOS | A package.json main entry comes back from ResolvePath unnormalized, so a CommonJS file reached through it and through import (RequireFileForImport, canonical path) can run twice under two require-cache keys |
ModuleInternal.mm ResolvePath |
step 8: one canonical require-cache key |
| 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 and JSON modules |
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 ") |
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 |
| Android | ~/x built app//x |
main (ModuleInternal.cpp:698) |
| 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, entry probes, boot backstop loop (C1, C2, C5). -
CJS core: the resolver (A4–A7), the require cache and wrapper.
Module.javabecomes JNI wrappers. iOS turns onwalkNodeModules, and the shared-testxits must pass.
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.