Skip to content

feat(runtime): base64 and the HTTP module loader from runtime-common - #625

Draft
edusperoni wants to merge 27 commits into
mainfrom
feat/runtime-common
Draft

edusperoni wants to merge 27 commits into
mainfrom
feat/runtime-common

Conversation

@edusperoni

@edusperoni edusperoni commented Dec 5, 2026 •

Copy link
Copy Markdown
Collaborator

First consumer of NativeScript/runtime-common, the shared iOS/Android loader core (design: docs/DESIGN.md there). Draft, so it can be tested with vite and other dev servers before review. The Android counterpart is linked below.

What moves to the core

  • Base64 (ns/Base64.h, ns/Base64Binding.h): the codec and the atob/btoa natives. Built by a new RuntimeCommon static-lib target from the NativeScript/runtime-common submodule.

  • HTTP module loader (ns/http/): the remote-module gate and allowlist, classification, canonicalization, timeouts, the single transport-error retry, deadline clamping, the synchronous fallback's wait bound, the cache switch with its inspector holders, and Clear-Site-Data. HttpLoader.mm keeps only the NSURLSession transport (partitions, NSURLCache generations, delegate queues) and the per-isolate canonicalization vocabulary. tns:: aliases keep the call sites unchanged.

  • Foundation and event loop (core ebb7b87): RuntimeCommonPlatform.mm implements the core's platform functions (Loader(), ApplyThreadPriority, RunJob, LoopFor, IsRuntimeAlive, MainContext). tns::EventLoop implements the core's Loop and gains PumpUntil. The three ad hoc pumps (top-level await, the pumped graph walk, the boot backstop) run through it. The termination flag moves onto the loop; Runtime forwards to it. Catch boundaries that JS or the loader reach also catch the core's JsError and Terminated.

User-visible changes

  • Module requests send User-Agent: NativeScript-HTTP-ESM, as Android already does.
  • In release builds with security.remoteModuleAllowlist, a module whose redirect ends outside the allowlist is refused. Before, the gate only checked the requested URL.
  • A failed module cache clear is reported: clearHttpCache() throws, and Network.clearBrowserCache answers -32000.
  • Graph-load fetch deadlines, the top-level-await deadline and the boot backstop deadline use steady_clock instead of the wall clock.
  • A module load whose event loop has stopped ends as a termination ("interrupted by isolate termination") instead of falling through to the synchronous fallback.
  • The boot backstop holds the Locker while it pumps, and runs Tasks::Drain() between pumps with nothing held.
  • The synchronous fallback fails a malformed URL immediately with "(malformed request URL)" instead of retrying it into "(network error)".

Tests

./run_tests.sh: 2515 passed, 0 failed, both normally and under ASan (-a). The core has host unit tests of its own, including the gate and the redirect check with isDebug=false, which the device suite (always Debug) never exercises.

Related

…core

The new NativeScript/runtime-common submodule pins the
NativeScript/runtime-common repository, the C++ shared with the Android
runtime. It builds as the RuntimeCommon static library target, linked into
NativeScript.framework, with the framework's prefix header for the V8
configuration, V8 as a system header path, and no header map, so core
sources only see their own headers and V8's.

The atob/btoa natives and the forgiving-base64 codec now come from there;
Base64.cpp keeps the builtin wiring.
The gate, classification, retry and deadline policy, the cache switch and
Clear-Site-Data come from the shared core (ns/http); HttpLoader keeps the
NSURLSession transport and the per-isolate canonicalization vocabulary.

User-visible changes:
- requests send User-Agent: NativeScript-HTTP-ESM;
- in release builds with a remote module allowlist, a redirect that ends
  outside it is refused;
- a failed cache clear throws from clearHttpCache() and answers -32000 to
  Network.clearBrowserCache;
- graph-load fetch deadlines are monotonic (steady_clock).
@coderabbitai

coderabbitai Bot commented Dec 5, 2026

Copy link
Copy Markdown

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

…ions

Pin NativeScript/runtime-common to ebb7b87 (foundation headers and the
Loop interface) and compile its new sources in the RuntimeCommon target.

Implement the new link-time platform functions: Loader() from
RuntimeConfig (refreshed whenever initializeWithConfig writes it, with
the V8 flag string the process actually applied), ApplyThreadPriority
via pthread QoS, RunJob inside an autorelease pool, IsRuntimeAlive,
MainContext, and the kRegistry trace category.

Teach every loader-reachable catch boundary the core's JsError and
Terminated ahead of its generic clauses: RequireCallback, RunModule,
RunMainScript, the event loop's RunGuarded, the worker entry, the
inspector modules entry, the graph walk's local compile, the resolver's
file compile, and both import() settle paths.
tns::EventLoop implements the core's Loop interface. PumpUntil checks
termination (the loop's flag, a terminating isolate, a stopped loop),
then the caller's predicate, then a steady-clock deadline before every
slice, and runs kNestableOnly, kV8Tasks or kPlatformWork slices with the
waits the runtime's pumps already used.

The termination flag moves onto the loop; Runtime forwards to it.

The TLA settle pump, the pumped graph walk and the boot backstop now go
through PumpUntil, so their deadlines are monotonic. The backstop runs
short pumps under its own scopes and drains Tasks outside them, since
the drain may enter UIApplicationMain and never return. A pumped walk
that ended on a stopped loop is reported as a termination.
… platform functions

Pins the core at 95d96cc (the app-file seam and the module code cache)
and adds its new sources, src/loader/CodeCache.cpp, CodeCacheQueue.cpp
and FileCompile.cpp, to the RuntimeCommon target.

- platform::StateBag: each Runtime owns an IsolateStateBag, reached
  through the RUNTIME slot. ~Runtime closes it as its last step under the
  Locker, after Caches::Remove and while the isolate is alive, so core
  state lives through all of teardown (F1).
- platform::Stat: stat(2); the freshness token is the source's mtime with
  nanoseconds (st_mtimespec).
- platform::ReadFile: the whole file or failure; a short read fails.
- LoaderConfig.codeCacheDir is <Caches>/NativeScript/CodeCache instead of
  the bare Caches directory.
…untime-common

Classic scripts and file ES modules compile through the core's
CompileFileClassicScript / CompileFileEsModule, with the same script
origin and source wrapper as before: the CommonJS wrapper for everything
but .mjs files and the app's bundle.js. The path is normalized first. A
compile error still logs in Debug and throws "Cannot compile script" for
a classic script, and leaves the exception pending for an ES module.

The off-thread file-module loader decides with platform::Stat,
CodeCacheEntryFor and HasFreshCodeCache at dispatch. On the pool it reads
with platform::ReadFile, always re-checks SourceUnchanged before
consuming a cache, and loads it with LoadCodeCache; finalize queues
creation with QueueCodeCache.

Caches use the core's format: hashed names under codeCacheDir, a header
keyed by the path relative to the app root, sub-second mtime freshness.
The iOS cache machinery (LoadScriptCache, QueueScriptCache,
FreshScriptCachePath, GetCacheFileName, its creation queue) and the
helpers only it used (ReadModule, ReadBinary, WriteBinary,
WrapModuleContent) are gone.

The UIApplicationDidEnterBackground observer is registered once by the
platform layer and calls loader::NotifyAppBackgrounded for every live
runtime, workers included, instead of only the main one.

A missing or unreadable file now throws the core's JsError ("Cannot find
module" / "Cannot read module"); an unreadable .mjs no longer aborts the
process.
Caches written before codeCacheDir are never read again. On the first
launch that finds no codeCacheDir, a utility-QoS task deletes them from
the top level of Caches and then creates codeCacheDir, so later launches
skip the sweep. Only regular files named like the old caches match:
<flattened path>.{js,mjs,cjs}.{cache,mcache}, plus the .XXXXXX
temporaries an interrupted write left behind. Caches is shared with the
app, so nothing is recursed into and nothing else is removed.
Takes the core fix for the code cache queue's quiet period, which was
computed in nanoseconds and posted as milliseconds, so an isolate whose
first creation task fired early never created another cache.
…s bundle id

A Mac Catalyst app outside the App Sandbox (the TestRunner Catalyst build
among them) gets the user's shared ~/Library/Caches. There codeCacheDir
is <Caches>/<bundle identifier>/NativeScript/CodeCache, the macOS
convention, and the one-time deletion of old caches is skipped: the top
level of the shared directory holds other apps' files. A sandboxed app's
container and iOS keep the per-app layout.
…nder its bundle id

AppCachesDirectory() resolves where the runtime keeps the app's cache
files: Caches, or Caches/<bundle identifier> on a Mac Catalyst app
outside the App Sandbox, whose Caches is the ~/Library/Caches every such
app shares. The code cache and ns-module-http-cache both go through it,
so two unsandboxed NativeScript apps no longer trim or clear each other's
HTTP module caches.
The pin brings the core's module identity unit (ns/loader/ModuleIdentity.h),
built into the RuntimeCommon target. platform::ParseUrl parses with the
runtime's own hidden-visibility ada, as the core's tests/AdaUrl.cpp does.
Adopts unit 6.1 of the shared loader core. Registry keys, script origins,
import.meta strings and the reading back of origins and file: URLs now come
from ns/loader/ModuleIdentity.h, configured in RefreshLoaderConfig with the
iOS legacy override: appRootOrigin file:///app (the app root below BaseDir),
legacyOrigins, the /app virtual file root, and /private/var aliased to /var.

- Paths are normalized lexically (CanonicalFilePath) instead of with
  stringByStandardizingPath, in both ModuleInternalCallbacks.mm and
  ModuleInternal.mm, so one file keeps one key. The app root is standardized
  once and spelled through the alias, and /private/var still keys as /var.
- file: URL keys are read through ada (FileUrlToPath) instead of NSURL.
- ModuleUrl loses ReportedModuleUrl, ModuleQuery, FileModulePath,
  HasUrlScheme and IsHttpRegistryKey; the Foundation NormalizePath and
  FileURLToPath copies are gone.
- import.meta is ImportMetaFor. Worker.mm and the inspector read origins
  back with OriginToPath instead of re-prefixing BaseDir; the inspector keeps
  a percent-decoded fallback for the URLs DevTools encodes, and still spells
  a rewritten source map URL the way the script's origin is spelled.

Origins, stack text, import.meta.url and import.meta.dirname of files under
the app root are unchanged. A classic script in the bundle but outside the
app root now has the origin file://<absolute path> (Q5); stack text, which
strips BaseDir, still reads as before. What JS can see:
- invalidateModules with an app file's file:///app/... URL (its
  import.meta.url) now invalidates that module (Q18).
- A file: URL with a host other than localhost, or with %2F, %5C or %00 in
  its path, names no module key (Q3).
- The core also maps app:/// URLs onto the app root, so invalidateModules
  with one now hits; this is not yet decided for iOS.
Moves the core to the end of units 6.2 (per-isolate loader config,
module registry) and 6.3 (import maps, loader vocabulary, specifier
resolver), and adds the five new loader sources to the RuntimeCommon
target.

This commit does not build on its own: the core's platform hooks
changed (LoaderSnapshot, ParseModuleUrl, BlobStoreUrl) and the runtime
adopts them in the next commit.
…ntime-common core

Adopts units 6.2 and 6.3 of the shared loader core. The per-isolate loader
state, the module registry, the import map and volatile patterns, and
specifier resolution now come from ns/loader/LoaderState.h,
ModuleRegistry.h, ImportMap.h and Resolver.h.

- Runtime::Init takes the loader config and installs the loader for its
  isolate. The main runtime passes platform::LoaderSnapshot(); a worker
  passes the config and vocabulary (import map, volatile patterns,
  canonicalization) captured on its parent's thread.
- RefreshLoaderConfig publishes an immutable snapshot that LoaderSnapshot
  reads atomically. Everything that read tns::Loader() now reads the config
  of the isolate it serves; the inspector keeps the one captured when it
  was created.
- The iOS import-map parser, vocabulary, registry tables, facade table and
  resolver are gone. ModuleInternalCallbacks keeps the file jobs, the HTTP
  and blob loaders and the error text, and RemoveModuleFromRegistry and
  InvalidateModules wrap the core's to supersede in-flight file loads.
- import() from a classic script or eval resolves against the registry key
  of its resource name when that names a module, else against what that
  name resolves to.
- ModuleUrl implements the URL functions of ns/Platform.h over the
  runtime's ada; BlobStoreUrl pre-filters on the whole blob: scheme.

What JS can see (decided):
- A file:// URL naming an absolute device path loads that file; the
  <appRoot>/app/x fallback for file:///app/x is gone (A3).
- Relative specifiers join lexically, by path segments (A1, A9).
- app:/// names the app root, from an http(s) importer too (A10).
- A file: specifier with a host other than localhost, or %2F, %5C or %00 in
  its path, names no file (Q3).
- Index-like import-map keys such as "404" are accepted.
- A root-absolute specifier already under the app root is used as is,
  not prefixed with the app root again (Q7).
Takes the fixes from an independent review of units 6.2 and 6.3: app:
URLs without a rooted path and specifiers holding a NUL name no file, a
relative import from a non-file importer resolves to nothing, '..' stays
below the app root, file:/app: schemes resolve in any case, import-map
scopes match per WHATWG, app://localhost/ names the app root, and
InstallLoader aborts on a null config or a second call.
Updated expectations, each from a decision on the shared loader core:
- import() of an absolute device path (__dirname + "/...") loads the file
  instead of prefixing the app root again (Q7).
- import() of "file://" + an absolute device path loads the file (A3).
- From an http(s) importer, a missing file:///app/x reports
  <appRoot>/x as tried; the <appRoot>/app/x fallback is gone (A3).
- An http(s) scope key without a trailing '/' names one URL and no longer
  matches as a prefix inside a path segment (WHATWG scopes).

New specs:
- '..' in root-absolute, ~/ and bare specifiers stops at the app root.
- A NUL reached through a '/'-terminated import-map key is refused.
- app:///, app://localhost/, FILE:/// and file:/ name the app root and
  resolve; app: without a rooted path names no file (A10).
- File import-map scopes apply below a '/'-terminated key and to the
  module a key names exactly, but not below a key without a trailing '/'.
- An app file whose name has '#' or a percent escape is invalidated through
  its own import.meta.url, and resolves a relative import() against its
  own directory (A2).
Takes units 6.4 and 6.5 of the shared loader core: the module graph walk,
file jobs and streamed compiles on a shared compile pool, the liveness
token and loader::Quiesce; static import, import(), JSON as synthetic
modules and import attributes.
…SON modules from the runtime-common core

Adopts runtime-common units 6.4 and 6.5. The core now owns the module
graph walk, background file jobs, streamed compiles on its shared compile
pool, the liveness token and loader::Quiesce, plus static import,
import(), JSON modules and import attributes. The iOS copies of all of
these are deleted.

- EventLoop::PostV8Task and the platform's task forwarding report
  whether the task was accepted (false once the loop has stopped).
- ~Runtime calls loader::Quiesce before the event loop shuts down and
  before the loader state closes, for the main runtime and for workers.
- Platform up-calls: FileModuleSourceWrap keeps the CommonJS wrapper for
  .js files, BuiltinModule hands back an evaluated ns:/node: module.
- LoaderConfig.enforceImportAttributes is wired and defaults to false.

Changes JS can see:
- JSON modules are parsed with JSON.parse. Trailing commas, comments and
  code after the value are SyntaxErrors, nothing in the file runs, and
  __proto__ is an own property. A JSON root's import() rejects with
  that SyntaxError, its message prefixed with the module URL.
- Rejection reasons follow the Android runtime's wording; import('')
  rejects with "Cannot find module '' (tried )".
- Debug builds log a mismatch between import attributes and the module
  type; with enforceImportAttributes it rejects with a TypeError.
- import() issued after the loader quiesced never settles, and a static
  resolve after it throws "The module loader is shutting down".
- A code cache is consumed synchronously when the module is finalized.
… the runtime-common core

- import('') rejects with the core's "Cannot find module '' (tried )".
- JSON modules: trailing comma, comment, code after the value (which
  must not run), empty file, __proto__ as an own property, and a static
  import of an invalid JSON module failing its importer's instantiation.
- An http(s) JSON root that is not strict JSON rejects with the
  SyntaxError itself (new /esm/bad.json route on the XCTest server).
- Workers that close() themselves and then import large, small, JSON and
  missing modules end cleanly while those loads are in flight.
- Release: a large module consumed from its code cache reports the same
  source positions as the compiled one.
- A static import of '' throws Cannot find module '' (tried ).
- The Debug import-attribute warning is logged once per module, whatever
  its query.
- A resolved import() root is not stat'ed a second time.
…e attribute

- A module statically importing '' fails its importer's instantiation
  with "Cannot find module '' (tried )".
- Imports of JSON whose subject is not attributes (the request-stats
  polling, the HTTP JSON specs, identity.json, the JSON strictness specs
  and the closing-worker spec) pass with { type: "json" }, so Debug runs
  log no attribute warnings for them. The import() resolution table
  keeps its attribute-less data.json rows.
Core main at 04b80bc (import() of a module being evaluated settles after
the evaluation instead of hitting V8's CHECK; an http(s) import() of a
module a static import is evaluating waits for it too) and unit 6.6 on
top: InstallHostCallbacks and import.meta, the require(esm) facade, the
ns:module binding, Node-style detection of a .js file reached by import
(Q13), CommonJS for any other extension, code cache format 2, and the
cached import() trims.
…odule binding from the runtime-common core

Adopts runtime-common unit 6.6.

- Runtime installs loader::InstallHostCallbacks; the iOS import.meta
  callback is deleted.
- ModuleInternalCallbacks.{h,mm} are deleted: require(esm) calls the
  core's GetOrCreateRequireFacade, and ns:module's native half is the
  core's BuildNsModuleBinding (diagnostics in debug builds).
- Platform up-calls: RequireFileForImport loads a CommonJS file through
  require()'s cache (any extension, as a CommonJS script), and
  InstallCreateRequireBinding hands over createRequire.
  FileModuleSourceWrap is deleted; classic scripts take their wrapper
  from a private helper.
- The file loader compiles through loader::CompileFileModule.
- ns-module.js forwards httpFetchDiagnostics and streamedCompileStats,
  and fileUrlToPath keeps a '#' in a file: URL string's path.
- tns::CanonicalizeHttpUrlKey and the id overload of
  RemoteModuleAllowlistFromConfig, used only by the deleted binding, go
  too. docs/ns-builtin-modules.md lists the two new debug members.
- RefreshLoaderConfig keeps the LoaderConfig origin defaults when the
  app's package.json sets "appSchemeOrigins": true.

Changes JS can see:
- import of a .js file with module syntax (or top-level await, or a
  redeclared CommonJS name) loads it as an ES module instead of failing
  with a SyntaxError.
- import of a .js file without module syntax, or of any other extension
  (.cjs included), runs it through require() and its cache and exports
  `default` and 'module.exports'; a throw rejects import() with the
  thrown value. bundle.js reached by import is CommonJS: require() runs
  it once and `default` is {}.
- import() of a module being evaluated (a self-import, or a cycle back
  to it) settles after the evaluation instead of crashing; an http(s)
  import() of a module a static import is evaluating waits for it too.
- configureLoader with a function importMap, or one whose toJSON returns
  undefined, throws TypeError "configureLoader: importMap must be an
  object or a JSON string".
- Debug builds' ns:module gains httpFetchDiagnostics and
  streamedCompileStats; a remoteUrlMatchesAllowlist entry with a lone
  surrogate is dropped.
- A C++ exception in an ns:module member is a JS exception.
- createRequire with a file: URL string keeps a '#' in the path; a URL
  object's fragment is still dropped.
- The require() facade's errors use the core's texts, and it throws "The
  module loader is shutting down" after loader::Quiesce.
- import.meta is left empty once the loader state is gone.
- Every code cache file is stale once (format 2).
…t() of a module being evaluated

- A .js file with module syntax, and one with only top-level await,
  loads as an ES module; its import.meta has url and dirname and no
  filename.
- A CommonJS .js file reached by import exports `default` and
  'module.exports', which are require()'s exports for the file, in
  either order, with one evaluation.
- A .cjs file reached by import is CommonJS.
- A throwing CommonJS module rejects import() with the thrown value.
- A CommonJS file's import() of itself, an ES module's import() of
  itself, and an import() back through a cycle settle after the
  evaluation.
- Debug builds' ns:module surface includes httpFetchDiagnostics and
  streamedCompileStats.
- createRequire keeps a '#' in a file: URL string's path and drops a
  URL object's fragment.
Format 2 adds the module format after the payload length, so the key
and freshness token start at offset 36.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant