Repository navigation
feat(runtime)!: load modules through the shared runtime-common core - #625
Draft
edusperoni wants to merge 41 commits into
Draft
edusperoni wants to merge 41 commits into
edusperoni wants to merge 41 commits into
Conversation
…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).
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
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. |
…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.
Drain advanced its iterator a second time after each erase, so it skipped the task after every one it ran and could step past the end. Each task now leaves the queue before it runs, so a task may register more tasks and one that never returns (UIApplicationMain) leaves nothing queued behind it.
… the runtime-common core
Pins runtime-common at 0d6bea8 (step 7: the evaluation layer and the
main-entry boot) and adopts it.
- RunMainScript boots an ES main entry through loader::RunMainEntry and
a CommonJS one through require() and then loader::HoldBoot. Both hand
off as soon as the entry queued UIApplicationMain (!Tasks::Empty());
dropping that one line makes the boot strict. A JsError or Terminated
from the boot is logged and thrown as NativeScriptException, the same
fatal path in Debug and Release.
- An entry still pending at the hand-off gets a rejection handler that
reports through the uncaught-error path (error event, __onUncaughtError,
uncaughtErrorPolicy) without throwing through V8.
- runMainApplication runs RunMainScript, then Tasks::Drain outside the
Locker; its boot backstop, PollMainEntryEvaluation and EvictMainEntry
are deleted. Tasks gains Empty().
- require() of an ES module calls loader::RequireEsModule; worker and
inspector_modules entries run through loader::RunEsModuleEntry and the
worker settles the promise it returns. A pending inspector_modules entry
logs a later rejection.
- Deleted from ModuleInternal: the evaluation policy types and the 60 s
constant (the core's are used; pumpRunLoop is pumpPlatformWork natively,
the JS option keeps its name), EvaluateModuleGraph, LoadESModule,
CompileFileEsModule, the entry probes, the throw helpers and the Debug
error modal, RequireExportsForNamespace and the path helpers they used.
- Boot.cpp, Evaluate.cpp and EvaluationPolicy.cpp join the RuntimeCommon
target.
Changes JS can see:
- A main-entry rejection is fatal at any poll during boot, and one after
the hand-off reaches the uncaught-error path instead of going unseen.
- The boot deadline is 60 s instead of 120 s, and an ES main entry hands
off as soon as UIApplicationMain is queued.
- A pumping require() of a module whose top-level await is still running
waits for it instead of returning a namespace in its TDZ.
- A require() of an ES module still evaluating up the stack throws
ERR_REQUIRE_CYCLE_MODULE ("Cannot require() ES Module <key> in a
cycle.").
- After loader::Quiesce a load throws "The module loader is shutting
down" instead of returning an empty namespace.
- A local worker entry with top-level await returns before it settles, so
messages wait in its queue; one that rejects within its first second
reaches the worker's onerror and keeps the worker running, as a later
rejection already did.
- A failing http(s) entry reports the loader's reason inside "Cannot load
ES module"; texts of evaluation failures are the core's.
…r a running top-level await - import() then require() of one .mjs, and the reverse, give one module instance evaluated once. - A CommonJS file a static import evaluates gets ERR_REQUIRE_CYCLE_MODULE from require() of the ES module importing it. - A pumping require() of a module whose top-level await is still running returns its settled exports. - Worker entry specs and fixtures describe a local ES module entry as settled by the worker's own loop.
…runtime-common core
A main entry still pending when boot hands off to UIApplicationMain and rejecting later ends the process the way a failed boot does, in every build and under every uncaughtErrorPolicy: "Fatal: the main module failed to run: Module evaluation promise rejected after UIApplicationMain started: <entry> — <message>" with the stack, then an uncaught NativeScriptException. The promise handler only builds the text; the throw runs from a loop task with no V8 scopes on the stack, inside a noexcept frame so it never unwinds into the run loop.
…til its deferred throw Under "throw", an error reported from the loop (a timer, a microtask, a rejection) crashed with SIGSEGV inside objc_exception_throw instead of terminating with NativeScriptFatalJSException. NSZombieEnabled shows "-[NSException retain]: message sent to deallocated instance". - The runtime is built without ARC, so the per-isolate slot (NSException* __strong in a std::unordered_map) and the posted fallback's capture held no reference: the autoreleased exception was freed when the run loop drained its pool, before the fallback threw it. The slot now retains what it holds and a claim hands it back autoreleased; the fallback task and a scheduled escapeException throw hold their own reference. - With the exception alive, it unwound out of UIApplicationMain into Interop's @catch, which builds a JS error from it. UIApplicationMain runs from Tasks with the isolate unlocked, so that touched V8 without the Locker and crashed. A call made without the isolate locked now rethrows the NSException untouched. Checked by launching an app whose timer throws after UIApplicationMain under "throw": it now terminates with "Terminating app due to uncaught exception 'NativeScriptFatalJSException'" (SIGABRT); under "report" it keeps running.
One deadline covers a graph walk and its settle, the boot's entry promise comes back marked handled, and evaluations are evicted only by the call that started them.
Repins runtime-common to 212f22b (step 8: the CommonJS core) and adopts it. - The global require is loader::InstallCommonJs; resolution, the require cache, module objects, the wrapper and createRequire are the core's. require() walks node_modules, then app/tns_modules and app/tns_modules/tns-core-modules (walkNodeModules, globalModuleRoots); a module's `this` is a fresh empty object. - The main entry resolves through loader::ResolveMainEntry and boots through loader::RunMainEntry whether it is an ES module or CommonJS; worker and tooling CommonJS entries run through loader::RunCommonJsEntry. - bundle.js is an ordinary CommonJS module. - Node-API modules reach require() through platform::RequireNativeAddon. - Worker entries resolve through loader::ResolveEntry: "./" and "../" against the calling module on the caller's thread, "~/" and "/" on the worker's; a bare name throws ERR_WORKER_PATH from the constructor, and a missing entry still reports through onerror. - Deleted: the iOS resolver and package.json reader, the require cache, LoadModule/LoadData/LoadScript, require-factory.js and kRequireFactory, the Transitional.h up-calls (InstallCreateRequireBinding, RequireFileForImport) and the CommonJS boot branch with HoldBoot. - CommonJs.cpp, PackageJson.cpp and RequireResolver.cpp join the RuntimeCommon target.
…formats and worker entry names
…es under the CommonJS core
The step 8 review round: a cached require() costs no Stat, package-name lookup directories are Statted once each, require functions are weak, and worker entries accept the ~x app-root form, which the Worker constructor now sends to the worker's thread with the other app-root names.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The iOS runtime loads modules through NativeScript/runtime-common, the module-loader core it now shares with Android (design:
docs/DESIGN.mdthere). The core is theNativeScript/runtime-commonsubmodule, built by theRuntimeCommonstatic-lib target. It is pinned at8c4e81d, which is on the core'smain. The Android counterpart is NativeScript/android#2179.80 files change: +2855 / −9723.
What moves to the core
atob/btoanatives.RuntimeCommonPlatform.mmimplements the core's platform functions.tns::EventLoopimplements the core'sLoop. Every pump (top-level await, the pumped graph walk, boot) goes throughPumpUntil, with monotonic deadlines.HttpLoader.mmkeeps only the NSURLSession transport.Cachesare deleted once.Caches/<bundle id>.import.meta), the per-isolate loader state, the registry, import maps and resolution;import(), JSON modules and import attributes;import.meta, therequire(esm)facade and thens:modulebinding.ModuleInternalCallbacksis deleted.UIApplicationMain. Dropping one line at the call site makes boot strict.createRequireand Node-API addons.ScriptCompiler::CompileFunction, with no wrapper text.package.jsonreader, its require cache andrequire-factory.jsare deleted.Changes JS can see
Loading and resolution
require()follows Node's order:node_modules, walking up to the app root;app/tns_modules;app/tns_modules/tns-core-modules.Cannot find module '<spec>' (tried <path>)with codeMODULE_NOT_FOUND.package.jsonis read as strict JSON. If it doesn't parse, boot fails withERR_INVALID_PACKAGE_CONFIG("Unable to locate main entry in /package.json") instead of silently falling back toindex.js.package.jsonmainstarting with/is a device path. Before, it resolved inside the package.importorrequire(). Paths are normalized lexically.importof a.jsfile with module syntax loads it as an ES module. Without module syntax, or with any other extension (.cjsincluded), it goes throughrequire()and its cache.bundle.jsis an ordinary CommonJS module. Before, it ran as a plain script, where top-levelvars became globals.idis".", and it isrequire.main. A module's top-levelthisis a fresh empty object.JSON.parse: comments, trailing commas and code after the value areSyntaxErrors."enforceImportAttributes": trueinpackage.jsonmakes them reject with aTypeError."appSchemeOrigins": truereports app files asapp:///<path>.file:URLs are read with ada:localhost, or%2F,%5Cor%00in the path, names no module;file:///app/xno longer falls back to<appRoot>/app/x.invalidateModuleswith an app file'simport.meta.url, or anapp:///URL, now invalidates that module. It also drops the module from the require cache.Evaluation and boot
UIApplicationMainstarted is fatal too: "Fatal: the main module failed to run: Module evaluation promise rejected after UIApplicationMain started: …".require()of a module whose top-level await is still running waits for it.require()of an ES module still evaluating up the stack throwsERR_REQUIRE_CYCLE_MODULE.import()during evaluation: animport()of a module that is still evaluating settles after the evaluation. Before, it crashed.import()started after teardown never settles.Workers
ERR_WORKER_PATHfrom the constructor;./and../resolve from the calling module, then from the app root;~/and~nameare app-root names;Cannot find module '<spec>' (tried <path>)throughonerror. Before, it was "Worker script does not exist".onerror.HTTP loader
User-Agent: NativeScript-HTTP-ESM, as Android does.security.remoteModuleAllowlist, a redirect that ends outside the allowlist is refused.clearHttpCache()and answers-32000toNetwork.clearBrowserCache.Code cache
.mjsthrows "Cannot read module" instead of aborting the process.Fixes found along the way
Tasks::Drainskipped the task after every one it ran.uncaughtErrorPolicy: "throw", an error reported from the loop crashed with SIGSEGV inobjc_exception_throw. It now ends withNativeScriptFatalJSException. The exception was freed before its deferred throw (MRC), and the@catchin Interop touched V8 without the Locker.Tests
./run_tests.sh:-a)main(http imports in Release)Not exercised yet:
bundle.mjs);NSMainaddon load.Merge order
589478f, which turns 9 specs back on for iOS.Related
docs/DESIGN.md§9 records each step and its decisions)