diff --git a/.clang-format-ignore b/.clang-format-ignore new file mode 100644 index 0000000..d2626ee --- /dev/null +++ b/.clang-format-ignore @@ -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. diff --git a/.github/workflows/host-tests.yml b/.github/workflows/host-tests.yml index d8e446c..92779e2 100644 --- a/.github/workflows/host-tests.yml +++ b/.github/workflows/host-tests.yml @@ -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 }} diff --git a/README.md b/README.md index eb7f788..e0d44a3 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,13 @@ depend on the platform. The plan and its open decisions are in - `include/ns/`: public headers. Include them as `"ns/.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 diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 1aa870e..de3e935 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -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 @@ -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 @@ -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 │ @@ -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, 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) │ └───────────────────────────────────────────────────────────────┘ @@ -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). @@ -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: @@ -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 @@ -229,7 +272,7 @@ struct FileInfo { std::optional 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. @@ -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) = 0; // false = dropped (stopped) virtual bool PostInternalDelayed(std::function, double ms) = 0; + // V8 layer: V8's own task type, no wrapping. Another engine adds its counterpart. virtual void PostV8Task(std::unique_ptr, bool nestable, double delaySec) = 0; virtual void RunNestableV8Tasks() = 0; // home thread @@ -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 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 LoopFor(v8::Isolate*); using Deadline = std::optional; -} // namespace ns +} // namespace nativescript::common ``` - **Android** has `PumpUntil(deadline, settled, drainLooperWork)` today. The #622 @@ -319,6 +365,10 @@ using Deadline = std::optional; 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 @@ -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 @@ -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 @@ -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 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 @@ -410,13 +460,13 @@ Both become one core serial worker on `StartThread`. ### 4.7 Per-isolate state ```cpp -namespace ns { +namespace nativescript::common { template T* IsolateState::For(v8::Isolate*); // creates; null after final Clear() template 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. @@ -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 @@ -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: @@ -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 diff --git a/include/ns/Base64.h b/include/ns/Base64.h index abb81da..c036a95 100644 --- a/include/ns/Base64.h +++ b/include/ns/Base64.h @@ -1,5 +1,5 @@ -#ifndef NS_BASE64_H_ -#define NS_BASE64_H_ +#ifndef NATIVESCRIPT_COMMON_BASE64_H_ +#define NATIVESCRIPT_COMMON_BASE64_H_ #include #include @@ -7,7 +7,7 @@ #include #include -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); @@ -18,6 +18,6 @@ std::string Encode(const uint8_t* data, size_t length); std::optional> ForgivingDecode(const uint8_t* data, size_t length); -} // namespace ns::base64 +} // namespace nativescript::common::base64 -#endif // NS_BASE64_H_ +#endif // NATIVESCRIPT_COMMON_BASE64_H_ diff --git a/include/ns/Base64Binding.h b/include/ns/Base64Binding.h index d6acfea..a622cc6 100644 --- a/include/ns/Base64Binding.h +++ b/include/ns/Base64Binding.h @@ -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, @@ -12,6 +12,6 @@ namespace ns::base64 { void Btoa(const v8::FunctionCallbackInfo& info); void Atob(const v8::FunctionCallbackInfo& info); -} // namespace ns::base64 +} // namespace nativescript::common::base64 -#endif // NS_BASE64_BINDING_H_ +#endif // NATIVESCRIPT_COMMON_BASE64_BINDING_H_ diff --git a/src/Base64.cpp b/src/Base64.cpp index 0f09ebb..094f8d8 100644 --- a/src/Base64.cpp +++ b/src/Base64.cpp @@ -1,6 +1,6 @@ #include "ns/Base64.h" -namespace ns::base64 { +namespace nativescript::common::base64 { namespace { @@ -106,4 +106,4 @@ std::optional> ForgivingDecode(const uint8_t* data, return out; } -} // namespace ns::base64 +} // namespace nativescript::common::base64 diff --git a/src/Base64Binding.cpp b/src/Base64Binding.cpp index 6e7bd2f..48ddfbb 100644 --- a/src/Base64Binding.cpp +++ b/src/Base64Binding.cpp @@ -4,7 +4,7 @@ #include "ns/Base64.h" -namespace ns::base64 { +namespace nativescript::common::base64 { namespace { @@ -22,8 +22,7 @@ bool GetLatin1Bytes(v8::Isolate* isolate, v8::Local value, const int length = str->Length(); out->resize(static_cast(length)); if (length > 0) { - str->WriteOneByteV2(isolate, 0, static_cast(length), - out->data()); + str->WriteOneByteV2(isolate, 0, static_cast(length), out->data()); } return true; } @@ -52,8 +51,7 @@ void Btoa(const v8::FunctionCallbackInfo& info) { return; } const std::string out = Encode(input.data(), input.size()); - ReturnOneByte(info, reinterpret_cast(out.data()), - out.size()); + ReturnOneByte(info, reinterpret_cast(out.data()), out.size()); } void Atob(const v8::FunctionCallbackInfo& info) { @@ -71,4 +69,4 @@ void Atob(const v8::FunctionCallbackInfo& info) { ReturnOneByte(info, out->data(), out->size()); } -} // namespace ns::base64 +} // namespace nativescript::common::base64 diff --git a/tests/Base64Test.cpp b/tests/Base64Test.cpp index e420d99..5543589 100644 --- a/tests/Base64Test.cpp +++ b/tests/Base64Test.cpp @@ -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(in.data()), - in.size()); + return nativescript::common::base64::Encode( + reinterpret_cast(in.data()), in.size()); } std::optional Decode(const std::string& in) { - auto out = ns::base64::ForgivingDecode( + auto out = nativescript::common::base64::ForgivingDecode( reinterpret_cast(in.data()), in.size()); if (!out) { return std::nullopt;