feat: Node-style primordials for runtime builtins - #1990
Conversation
📝 WalkthroughWalkthroughThe runtime now creates frozen primordial snapshots per isolate, passes them to builtins, and cleans them up during isolate disposal. Builtins use captured intrinsic operations. ESLint enforces this pattern, and app tests validate behavior during intrinsic tampering. ChangesPrimordial runtime integration
Sequence Diagram(s)sequenceDiagram
participant BuiltinLoader
participant primordials_js
participant RuntimeBuiltin
participant IsolateDisposer
BuiltinLoader->>primordials_js: initialize snapshot for isolate
primordials_js-->>BuiltinLoader: return frozen intrinsic object
BuiltinLoader->>RuntimeBuiltin: pass binding and primordials
IsolateDisposer->>BuiltinLoader: remove isolate snapshot
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
The runtime's internal JavaScript lived as C++ string literals across eight files, unlintable and invisible to tooling. It now lives in real .js files under test-app/runtime/src/main/cpp/js, embedded into a generated C++ table by tools/js2c.mjs at build time and executed through a new BuiltinLoader. Each file is compiled with v8::ScriptCompiler::CompileFunction as a function body with the fixed parameters `exports`, `module` and `binding` (Node's module wrapper plus its internalBinding idiom): natives arrive as properties of a binding bag built at the C++ call site, results come back through module.exports, and the script origin is internal/<name>.js so runtime frames stay identifiable in stack traces. Compilation goes through a process-wide bytecode cache guarded by a mutex, since worker runtimes initialize on their own threads. Extracted: weak-ref, message-loop-timer, smart-stringify, require-factory, json-helper, events, error-events and blob-url. Each extraction was verified AST-identical to the original literal by byte-comparing esbuild-minified output of both. tools/js2c.mjs is taken from the iOS runtime's feat/ns-util branch, which includes the later `unsigned char` fix for source bytes >= 0x80 (a narrowing error in a plain char array). Its --filelist drift check is adapted to --check-dir, comparing the explicit RUNTIME_BUILTIN_JS list in CMakeLists.txt against the directory contents so a new builtin cannot be silently skipped on incremental builds. Two behavioural notes: - JSONObjectHelper recompiled its JS->org.json serializer on every MetadataNode `from` registration. It is now compiled once per isolate and released via the isolate-dispose hook. - __messageLoopTimerStart/__messageLoopTimerStop are no longer installed on the global object. Nothing outside MessageLoopTimer referenced them, and the timer's start/stop pair now reaches its builtin through the binding bag. Mirrors NativeScript/ios#411.
Runtime builtins install closures that outlive init and are then reachable from app code, so every intrinsic they use at call time is something the app can replace. internal/primordials.js snapshots exactly the intrinsics the builtins need into a frozen null-prototype namespace, taken on the first RunBuiltin of an isolate (during runtime init) and cached per isolate; builtins now compile with a fourth fixed parameter, `primordials`. Instance methods are uncurried Node-style, so the receiver becomes the first argument. ESLint fails the lint on direct use of the captured statics and constructors. Mirrors NativeScript/ios#415.
7e5f2f6 to
4687302
Compare
f32561f to
05dc54b
Compare
|
@copilot resolve the merge conflicts in this pull request |
# Conflicts: # eslint.config.mjs # test-app/runtime/CMakeLists.txt # test-app/runtime/src/main/cpp/BuiltinLoader.cpp # test-app/runtime/src/main/cpp/BuiltinLoader.h # test-app/runtime/src/main/cpp/IsolateDisposer.cpp # test-app/runtime/src/main/cpp/js/README.md # test-app/runtime/src/main/cpp/js/blob-url.js # test-app/runtime/src/main/cpp/js/error-events.js # test-app/runtime/src/main/cpp/js/events.js # test-app/runtime/src/main/cpp/js/json-helper.js # test-app/runtime/src/main/cpp/js/message-loop-timer.js # test-app/runtime/src/main/cpp/js/smart-stringify.js # test-app/runtime/src/main/cpp/js/weak-ref.js Co-authored-by: NathanWalker <457187+NathanWalker@users.noreply.github.com>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@test-app/app/src/main/assets/app/tests/testPrimordials.js`:
- Around line 167-185: Update the test “revokeObjectURL and
InternalAccessor.getData work while Map methods are tampered” to create a Blob
and object URL inside withTampered, assert InternalAccessor.getData returns the
stored Blob data, revoke that URL, then assert retrieval returns undefined;
retain the existing no-throw assertion.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d5e87995-98c0-4fc2-93b6-53f7f7d907bd
📒 Files selected for processing (16)
eslint.config.mjstest-app/app/src/main/assets/app/mainpage.jstest-app/app/src/main/assets/app/tests/testPrimordials.jstest-app/runtime/CMakeLists.txttest-app/runtime/src/main/cpp/BuiltinLoader.cpptest-app/runtime/src/main/cpp/BuiltinLoader.htest-app/runtime/src/main/cpp/IsolateDisposer.cpptest-app/runtime/src/main/cpp/js/README.mdtest-app/runtime/src/main/cpp/js/blob-url.jstest-app/runtime/src/main/cpp/js/error-events.jstest-app/runtime/src/main/cpp/js/events.jstest-app/runtime/src/main/cpp/js/json-helper.jstest-app/runtime/src/main/cpp/js/message-loop-timer.jstest-app/runtime/src/main/cpp/js/primordials.jstest-app/runtime/src/main/cpp/js/smart-stringify.jstest-app/runtime/src/main/cpp/js/weak-ref.js
| it("revokeObjectURL and InternalAccessor.getData work while Map methods are tampered", function () { | ||
| let data; | ||
| let threw = null; | ||
| try { | ||
| withTampered([ | ||
| [Map.prototype, "get"], | ||
| [Map.prototype, "set"], | ||
| [Map.prototype, "delete"], | ||
| ], function () { | ||
| URL.revokeObjectURL("blob:nativescript/primordials-missing"); | ||
| data = URL.InternalAccessor.getData("blob:nativescript/primordials-missing"); | ||
| }); | ||
| } catch (e) { | ||
| threw = e; | ||
| } | ||
|
|
||
| expect(threw).toBeNull(); | ||
| expect(data).toBeUndefined(); | ||
| }); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
ast-grep outline test-app/runtime/src/main/cpp/js/blob-url.js --items all
rg -n -C 8 '\b(createObjectURL|revokeObjectURL|getData|MapPrototypeSet|MapPrototypeGet|MapPrototypeDelete)\b' \
test-app/runtime/src/main/cpp/js/blob-url.jsRepository: NativeScript/android
Length of output: 1978
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- target test and helper ---'
sed -n '1,80p;130,205p' test-app/app/src/main/assets/app/tests/testPrimordials.js
printf '%s\n' '--- related URL/blob tests ---'
rg -n -C 6 '\b(URL\.createObjectURL|URL\.revokeObjectURL|URL\.InternalAccessor\.getData|withTampered|new Blob|new File)\b' \
test-app/app/src/main/assets/app/tests test-app/runtime/src/main/cpp/js
printf '%s\n' '--- primordial bindings ---'
rg -n -C 5 'MapPrototype(Set|Get|Delete)|primordials' \
test-app/runtime/src/main/cpp/js test-app/runtime/src/main/cpp 2>/dev/null | head -250Repository: NativeScript/android
Length of output: 41449
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
import re
test = Path("test-app/app/src/main/assets/app/tests/testPrimordials.js").read_text()
impl = Path("test-app/runtime/src/main/cpp/js/blob-url.js").read_text()
test_match = re.search(
r'it\("revokeObjectURL and InternalAccessor\.getData work while Map methods are tampered".*?\n \}\);',
test,
re.S,
)
if not test_match:
raise SystemExit("target test not found")
body = test_match.group(0)
facts = {
"target_test_calls_createObjectURL": "URL.createObjectURL" in body,
"target_test_calls_revokeObjectURL": "URL.revokeObjectURL" in body,
"target_test_calls_getData": "URL.InternalAccessor.getData" in body,
"implementation_inserts_with_captured_set": bool(
re.search(r'MapPrototypeSet\(BLOB_STORE,\s*ret,', impl)
),
"implementation_reads_with_captured_get": bool(
re.search(r'MapPrototypeGet\(BLOB_STORE,\s*url\)', impl)
),
"implementation_removes_with_captured_delete": bool(
re.search(r'MapPrototypeDelete\(BLOB_STORE,\s*url\)', impl)
),
}
for key, value in facts.items():
print(f"{key}={value}")
if facts["target_test_calls_createObjectURL"]:
raise SystemExit("unexpected createObjectURL call in target test")
if not all(facts[k] for k in (
"implementation_inserts_with_captured_set",
"implementation_reads_with_captured_get",
"implementation_removes_with_captured_delete",
)):
raise SystemExit("blob-store operation mapping is incomplete")
PYRepository: NativeScript/android
Length of output: 407
Exercise blob insertion and retrieval while Map.prototype methods are replaced.
This test only revokes and reads a missing URL. Create a Blob and object URL inside withTampered, verify the stored data, revoke the URL, and verify that URL.InternalAccessor.getData returns undefined.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@test-app/app/src/main/assets/app/tests/testPrimordials.js` around lines 167 -
185, Update the test “revokeObjectURL and InternalAccessor.getData work while
Map methods are tampered” to create a Blob and object URL inside withTampered,
assert InternalAccessor.getData returns the stored Blob data, revoke that URL,
then assert retrieval returns undefined; retain the existing no-throw assertion.
Description
Android mirror of NativeScript/ios#415. Stacked on #1989 (
feat/js-builtins) — review only the last commit.The runtime's builtin JavaScript installs globals and leaves closures behind that run for the lifetime of the app: event dispatch, the URL/blob glue, console's stringify, the JS→
org.jsonserializer. Until now those closures reached for intrinsics (Array.prototype.slice,JSON.stringify,Object.defineProperty, …) through the live globals, so app code replacing one could break runtime internals or observe them.internal/primordials.jscaptures exactly the intrinsics the other builtins need into a frozen, null-prototype namespace, Node-style — trimmed to what the Android builtins actually reach (not a mirror of Node's or iOS's list).The
(binding, primordials)contractexports,module,binding,primordials.RunBuiltinof an isolate — during runtime init, before any user code — and cached per isolate (mutex-guarded, released on isolate disposal; worker isolates snapshot their own realm's intrinsics automatically).ArrayPrototypeSlice(list, 1), viaFunction.prototype.bind.bind(Function.prototype.call)); statics keep their path (JSONStringify). Plain constructor calls made once at init time stay direct — the rule targets closures that outlive init.Blob/Fileinblob-url.js(app-layer provided),global.__requireOverrideinrequire-factory.js(app-layer hook),org.json.*injson-helper.js(metadata interceptor, not an intrinsic).Enforcement: ESLint
no-restricted-propertiesfor every captured static andno-restricted-globalsfor every captured constructor, each message naming the replacement;primordials.jsitself is exempted. Both rule classes verified to fire.Tests: new
tests/testPrimordials.js(8 specs) tampers with the intrinsics and checks the runtime keeps working — a guard spec proving the tampering is observable, globaldispatchEvent/add/remove/onceunder brokenArray.prototype.*+Function.prototype.call,reportErrordelivering a correctErrorEvent, circularconsole.logstaying non-fatal, plus Android-specific specs for thesearchParamsre-sync, the blob store under brokenMap.prototype.*, andorg.jsonserialization under brokenArray/Object/Dateintrinsics. Each spec keeps the tampered window synchronous and assertion-free, restoring originals infinally.Related Pull Requests
Does your pull request have unit tests?
Yes — 8 new device specs. Full suite: 613 specs, 0 failures (605 baseline + 8), including worker suites, which exercise per-isolate snapshot creation and disposal on worker threads.
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Tests