Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .clang-format-ignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Files moved from a runtime and kept byte-comparable with its copy until the
# migration ends. They get formatted once both runtimes consume them from here.
9 changes: 9 additions & 0 deletions .github/workflows/host-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@ concurrency:
cancel-in-progress: true

jobs:
format:
name: clang-format
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: pip install clang-format==22.1.8
- name: Check
run: git ls-files -z '*.h' '*.cpp' | xargs -0 clang-format --dry-run --Werror

host-tests:
name: ${{ matrix.os }}
runs-on: ${{ matrix.os }}
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,13 @@ depend on the platform. The plan and its open decisions are in
- `include/ns/`: public headers. Include them as `"ns/<Name>.h"`, never by a bare
file name: Xcode header maps resolve bare names project-wide, so a shared
header and a runtime header with the same name would collide silently.
- Namespace: `nativescript::common`, subdivided by component
(`nativescript::common::base64`, …). Never name a nested namespace `v8`: it
would hide `::v8` inside `nativescript::common`.
- `src/`: implementation. Plain C++20, with no Objective-C and no JNI.
- Formatting: `.clang-format` is the iOS runtime's style and CI enforces it
(clang-format 22.1.8). A file moved from a runtime and kept comparable with
its copy goes in `.clang-format-ignore` until the migration ends.
- `tests/`: host unit tests for the sources that do not need V8.

Core code includes only its own headers, V8 and the standard library. Anything
Expand Down
97 changes: 74 additions & 23 deletions docs/DESIGN.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
# A shared module-loader core for the iOS and Android runtimes

Status: proposal, 2026-12-04. Step 1 of §9 (this repository and its build
wiring) is under way. F3 is decided (a private submodule repository); the
rest of §7 is open. iOS #622 has since merged
(052675a1).
Status: proposal, 2026-12-04, updated 2026-12-05. Step 1 of §9 (this
repository and its build wiring) is under way. F3 (a private submodule
repository) and F7 (the `nativescript::common` namespace) 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
Expand All @@ -19,6 +20,48 @@ 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.

## Layering and direction

NativeScript has two layers, and this repository holds the first:
1. **The app runtime:** what loading a NativeScript app needs from the ground
up. Builtins, module loading, the code cache, the event loop, web globals.
2. **Native calling:** the FFI that exposes platform APIs to JS. It is heading
to an `ns:native` module 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:
1. Unify the app runtime across iOS and Android on V8 (this document).
2. Shape and build `ns:native`.
3. 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::engine`
has no module records, code cache or off-thread compile today.
4. 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 flat `nativescript::` names in
NativeScript/runtimes. No nested namespace is called `v8`, because inside
`nativescript::common` it would hide `::v8`. Headers stay under `ns/`: a
`nativescript/` include root matches the `NativeScript/` source folders of
all three repositories on case-insensitive file systems.

---

## 1. Summary
Expand Down Expand Up @@ -105,7 +148,7 @@ Already identical in substance:
┌───────────────────────────────────────────────────────────────┐
│ builtin JS (ns-module.js, require-factory.js, …) — shared │
├───────────────────────────────────────────────────────────────┤
│ ns/loader — the shared core │
│ 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 │
Expand All @@ -117,11 +160,11 @@ Already identical in substance:
│ deadline, cache switch, Clear-Site-Data, lanes │
│ jobs/ stream-compile pool, compile gate │
├───────────────────────────────────────────────────────────────┤
│ ns/ foundation — shared, bridge-free headers │
│ common foundation — shared, bridge-free headers │
│ IsolateState<T>, V8Helpers, Check, TraceLog/Log, JsError, │
│ Deadline, EventLoop interface │
├───────────────────────────────────────────────────────────────┤
│ ns/platform — implemented once per platform │
│ common::platform — implemented once per platform │
│ ios/ (ObjC++, CF, NSURLSession) android/ (JNI, ALooper, │
│ OkHttp, AppFiles) │
└───────────────────────────────────────────────────────────────┘
Expand Down Expand Up @@ -168,7 +211,7 @@ runtime.
### 4.2 Config, logging, failure

```cpp
namespace ns::platform {
namespace nativescript::common::platform {

// Filled at boot, before the first isolate. Immutable while any isolate is live
// (iOS restartWithConfig: rewrites it between runs).
Expand Down Expand Up @@ -197,7 +240,7 @@ void Log(LogLevel, std::string_view); // iOS os_log chunking / Androi
void EmitTrace(LogCategory, std::string_view); // sink for TNS_DEBUG (already the same API)
[[noreturn]] void Fatal(const char* where, std::string_view);

} // namespace ns::platform
} // namespace nativescript::common::platform
```

Today these values come from:
Expand All @@ -214,7 +257,7 @@ Shared code never reads `package.json` and never sees `id` or `jobject`.
### 4.3 App files (driven by #2104)

```cpp
namespace ns::platform {
namespace nativescript::common::platform {

// Logical paths (appRoot-based, as V8 and users see them). Any thread, no
// Locker, bounded time: pool threads call these inside the compile gate that
Expand All @@ -229,7 +272,7 @@ struct FileInfo {
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 ns::platform
} // namespace nativescript::common::platform
```

- **iOS:** `stat` and `read`, the way `Helpers.mm` does it today.
Expand Down Expand Up @@ -271,12 +314,13 @@ path. That is the concrete reason the core must only ever ask `Stat`.
### 4.4 Event loop: the one real gap

```cpp
namespace ns {
namespace nativescript::common {

class Loop { // the per-isolate EventLoop; any thread unless noted
public:
virtual bool PostInternal(std::function<void()>) = 0; // false = dropped (stopped)
virtual bool PostInternalDelayed(std::function<void()>, double ms) = 0;
// V8 layer: V8's own task type, no wrapping. Another engine adds its counterpart.
virtual void PostV8Task(std::unique_ptr<v8::Task>, bool nestable, double delaySec) = 0;
virtual void RunNestableV8Tasks() = 0; // home thread

Expand All @@ -296,11 +340,13 @@ class Loop { // the per-isolate EventLoop; any thread unless noted
virtual bool IsOnHomeThread() const = 0; // Android #622 port adds this; iOS has IsOnRuntimeThread
};

std::shared_ptr<Loop> LoopFor(v8::Isolate*); // null once the loop is gone
// For holders off the home thread; null once the loop is gone. Hot paths reach the
// loop through per-runtime state in an isolate data slot instead.
std::shared_ptr<Loop> LoopFor(v8::Isolate*);

using Deadline = std::optional<std::chrono::steady_clock::time_point>;

} // namespace ns
} // namespace nativescript::common
```

- **Android** has `PumpUntil(deadline, settled, drainLooperWork)` today. The #622
Expand All @@ -319,6 +365,10 @@ using Deadline = std::optional<std::chrono::steady_clock::time_point>;
or cut short a module wait.
- **The `Post*` return type:** iOS returns `bool` and Android returns `void`.
Unify on `bool`.
- **Engine types stay.** `v8::Task` and the `v8::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()`, where `UIApplicationMain` may take over and never return
(`NativeScript.mm:175-176`). The graph walk never does this. So the core owns
Expand All @@ -342,7 +392,7 @@ The cut is at **one attempt**. The core owns:
The transport only performs attempts.

```cpp
namespace ns::http {
namespace nativescript::common::http {

struct AttemptRequest {
std::string url; // gated, NormalizeHttpModuleUrl spelling, never canonicalized
Expand All @@ -367,9 +417,9 @@ class ModuleTransport {
virtual CacheOpResult ClearOrigin(const std::string& origin) = 0;
};

} // namespace ns::http
} // namespace nativescript::common::http

namespace ns::platform {
namespace nativescript::common::platform {
http::ModuleTransport& HttpTransport();
void OnLaneThreadStart(); // Android: JVM attach
void OnLaneThreadExit(); // Android: JVM detach
Expand All @@ -387,13 +437,13 @@ void OnLaneThreadExit(); // Android: JVM detach
### 4.6 Threads

```cpp
namespace ns::platform {
namespace nativescript::common::platform {

struct ThreadSpec { const char* name; size_t stackBytes; ThreadPriority priority; };
// Detached thread; the platform applies name, QoS and (Apple) an autorelease pool per job.
bool StartThread(const ThreadSpec&, std::function<void()> body); // false → caller falls back inline

} // namespace ns::platform
} // namespace nativescript::common::platform
```

Both sides run the stream-compile pool on dedicated pthreads. GCD and bionic
Expand All @@ -410,13 +460,13 @@ Both become one core serial worker on `StartThread`.
### 4.7 Per-isolate state

```cpp
namespace ns {
namespace nativescript::common {
template <class T> T* IsolateState::For(v8::Isolate*); // creates; null after final Clear()
template <class T> T* IsolateState::ForExisting(v8::Isolate*); // never creates; off-home-thread
// reads while holding the Locker.
// Pool/transport threads never call it
}
namespace ns::platform { IsolateStateBag* StateBag(v8::Isolate*); }
namespace nativescript::common::platform { IsolateStateBag* StateBag(v8::Isolate*); }
```

**The two contracts differ**, and the core can't be written against both.
Expand Down Expand Up @@ -447,7 +497,7 @@ change and should be its own PR (decision F1).
## 5. The core's public API (what platforms call)

```cpp
namespace ns::loader {
namespace nativescript::common::loader {

// Boot / per isolate
void InstallHostCallbacks(v8::Isolate*); // resolve, import(), import.meta, ns:module binding
Expand Down Expand Up @@ -480,7 +530,7 @@ void SetHttpCacheEnabled(bool);
void SetHttpCacheDisabledBy(uint64_t holderId, bool disabled); // inspector connection
CacheOpResult ClearHttpCache();

} // namespace ns::loader
} // namespace nativescript::common::loader
```

Each platform keeps a thin binding layer:
Expand Down Expand Up @@ -699,6 +749,7 @@ the #383/#444 ↔ android#1965/#2021 work):
| 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
Expand Down
10 changes: 5 additions & 5 deletions include/ns/Base64.h
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
#ifndef NS_BASE64_H_
#define NS_BASE64_H_
#ifndef NATIVESCRIPT_COMMON_BASE64_H_
#define NATIVESCRIPT_COMMON_BASE64_H_

#include <cstddef>
#include <cstdint>
#include <optional>
#include <string>
#include <vector>

namespace ns::base64 {
namespace nativescript::common::base64 {

// Standard base64 (RFC 4648 section 4) with `=` padding.
std::string Encode(const uint8_t* data, size_t length);
Expand All @@ -18,6 +18,6 @@ std::string Encode(const uint8_t* data, size_t length);
std::optional<std::vector<uint8_t>> ForgivingDecode(const uint8_t* data,
size_t length);

} // namespace ns::base64
} // namespace nativescript::common::base64

#endif // NS_BASE64_H_
#endif // NATIVESCRIPT_COMMON_BASE64_H_
10 changes: 5 additions & 5 deletions include/ns/Base64Binding.h
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#ifndef NS_BASE64_BINDING_H_
#define NS_BASE64_BINDING_H_
#ifndef NATIVESCRIPT_COMMON_BASE64_BINDING_H_
#define NATIVESCRIPT_COMMON_BASE64_BINDING_H_

#include "v8.h"

namespace ns::base64 {
namespace nativescript::common::base64 {

// The natives behind the atob / btoa globals. Each takes one string and
// answers a string, or null when the input has a code unit above U+00FF or,
Expand All @@ -12,6 +12,6 @@ namespace ns::base64 {
void Btoa(const v8::FunctionCallbackInfo<v8::Value>& info);
void Atob(const v8::FunctionCallbackInfo<v8::Value>& info);

} // namespace ns::base64
} // namespace nativescript::common::base64

#endif // NS_BASE64_BINDING_H_
#endif // NATIVESCRIPT_COMMON_BASE64_BINDING_H_
4 changes: 2 additions & 2 deletions src/Base64.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#include "ns/Base64.h"

namespace ns::base64 {
namespace nativescript::common::base64 {

namespace {

Expand Down Expand Up @@ -106,4 +106,4 @@ std::optional<std::vector<uint8_t>> ForgivingDecode(const uint8_t* data,
return out;
}

} // namespace ns::base64
} // namespace nativescript::common::base64
10 changes: 4 additions & 6 deletions src/Base64Binding.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

#include "ns/Base64.h"

namespace ns::base64 {
namespace nativescript::common::base64 {

namespace {

Expand All @@ -22,8 +22,7 @@ bool GetLatin1Bytes(v8::Isolate* isolate, v8::Local<v8::Value> value,
const int length = str->Length();
out->resize(static_cast<size_t>(length));
if (length > 0) {
str->WriteOneByteV2(isolate, 0, static_cast<uint32_t>(length),
out->data());
str->WriteOneByteV2(isolate, 0, static_cast<uint32_t>(length), out->data());
}
return true;
}
Expand Down Expand Up @@ -52,8 +51,7 @@ void Btoa(const v8::FunctionCallbackInfo<v8::Value>& info) {
return;
}
const std::string out = Encode(input.data(), input.size());
ReturnOneByte(info, reinterpret_cast<const uint8_t*>(out.data()),
out.size());
ReturnOneByte(info, reinterpret_cast<const uint8_t*>(out.data()), out.size());
}

void Atob(const v8::FunctionCallbackInfo<v8::Value>& info) {
Expand All @@ -71,4 +69,4 @@ void Atob(const v8::FunctionCallbackInfo<v8::Value>& info) {
ReturnOneByte(info, out->data(), out->size());
}

} // namespace ns::base64
} // namespace nativescript::common::base64
6 changes: 3 additions & 3 deletions tests/Base64Test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ void Check(bool ok, const char* what, const std::string& input) {
}

std::string Encode(const std::string& in) {
return ns::base64::Encode(reinterpret_cast<const uint8_t*>(in.data()),
in.size());
return nativescript::common::base64::Encode(
reinterpret_cast<const uint8_t*>(in.data()), in.size());
}

std::optional<std::string> Decode(const std::string& in) {
auto out = ns::base64::ForgivingDecode(
auto out = nativescript::common::base64::ForgivingDecode(
reinterpret_cast<const uint8_t*>(in.data()), in.size());
if (!out) {
return std::nullopt;
Expand Down
Loading