Skip to content

feat: Node-style primordials for runtime builtins - #1990

Merged
NathanWalker merged 3 commits into
mainfrom
feat/primordials
Aug 11, 2026
Merged

feat: Node-style primordials for runtime builtins#1990
NathanWalker merged 3 commits into
mainfrom
feat/primordials

Conversation

@edusperoni

@edusperoni edusperoni commented Jul 30, 2026

Copy link
Copy Markdown
Collaborator

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.json serializer. 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.js captures 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) contract

  • Builtins now compile with four fixed parameters: exports, module, binding, primordials.
  • The snapshot is built lazily on the first RunBuiltin of 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).
  • Instance methods are uncurried exactly as Node does it (ArrayPrototypeSlice(list, 1), via Function.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.
  • Deliberately left live: Blob/File in blob-url.js (app-layer provided), global.__requireOverride in require-factory.js (app-layer hook), org.json.* in json-helper.js (metadata interceptor, not an intrinsic).

Enforcement: ESLint no-restricted-properties for every captured static and no-restricted-globals for every captured constructor, each message naming the replacement; primordials.js itself 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, global dispatchEvent/add/remove/once under broken Array.prototype.* + Function.prototype.call, reportError delivering a correct ErrorEvent, circular console.log staying non-fatal, plus Android-specific specs for the searchParams re-sync, the blob store under broken Map.prototype.*, and org.json serialization under broken Array/Object/Date intrinsics. Each spec keeps the tampered window synchronous and assertion-free, restoring originals in finally.

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

    • Added protected runtime handling for built-in JavaScript functionality, improving reliability when application code modifies standard globals.
    • Runtime components now share stable intrinsic references throughout an isolate’s lifetime.
  • Bug Fixes

    • Improved event handling, timers, URL and blob operations, JSON serialization, error reporting, and weak-reference behavior under altered built-ins.
    • Added cleanup to prevent stale runtime state after an execution context is disposed.
  • Documentation

    • Documented the runtime’s protected built-in behavior and usage guidelines.
  • Tests

    • Added comprehensive coverage for intrinsic replacement, event dispatch, logging, URL operations, serialization, and related runtime behavior.

@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The 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.

Changes

Primordial runtime integration

Layer / File(s) Summary
Snapshot creation and lifecycle
test-app/runtime/CMakeLists.txt, test-app/runtime/src/main/cpp/BuiltinLoader.*, test-app/runtime/src/main/cpp/IsolateDisposer.cpp, test-app/runtime/src/main/cpp/js/primordials.js
The runtime generates primordials.js, creates a frozen snapshot per isolate, passes it to builtins, caches it, and removes it during disposal.
Builtin primordial adoption
test-app/runtime/src/main/cpp/js/{blob-url,error-events,events,json-helper,message-loop-timer,smart-stringify,weak-ref}.js, test-app/runtime/src/main/cpp/js/README.md
Builtins use captured constructors, static methods, and uncurried prototype methods. The builtin contract and usage rules are documented.
Primordial lint enforcement
eslint.config.mjs
ESLint declares primordials and restricts direct access to selected constructors and static methods outside primordials.js.
Tampering resilience tests
test-app/app/src/main/assets/app/mainpage.js, test-app/app/src/main/assets/app/tests/testPrimordials.js
The app runs tests that replace intrinsic methods and checks event, error, URL, blob, and JSON behavior.
Estimated code review effort: 4 (Complex) ~60 minutes

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
Loading

Possibly related PRs

Poem

A rabbit guards the methods bright,
Frozen safely before user flight.
Maps and events now hop with care,
Tests replace them—builtins don’t scare.
Primordials keep the runtime right.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the PR's main change: adding Node-style primordials for runtime builtins.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

Comment @coderabbitai help to get the list of available commands.

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.
Base automatically changed from feat/js-builtins to main August 11, 2026 03:14
@NathanWalker

Copy link
Copy Markdown
Contributor

@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>

Copilot AI commented Aug 11, 2026

Copy link
Copy Markdown

@copilot resolve the merge conflicts in this pull request

Merge conflicts resolved in d9ea139. All 13 conflicted files were add/add conflicts from the feat/js-builtins base landing on main — kept our versions (with primordials) throughout.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between b5edc78 and d9ea139.

📒 Files selected for processing (16)
  • eslint.config.mjs
  • test-app/app/src/main/assets/app/mainpage.js
  • test-app/app/src/main/assets/app/tests/testPrimordials.js
  • 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/primordials.js
  • test-app/runtime/src/main/cpp/js/smart-stringify.js
  • test-app/runtime/src/main/cpp/js/weak-ref.js

Comment on lines +167 to +185
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();
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.js

Repository: 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 -250

Repository: 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")
PY

Repository: 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.

@NathanWalker
NathanWalker merged commit 98b63ba into main Aug 11, 2026
5 checks passed
@NathanWalker
NathanWalker deleted the feat/primordials branch August 11, 2026 04:05
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.

3 participants