A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(native): a native build can connect to the editor over the debug channel
esengine0b35fd570923
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 11f40f6f8..1ca3b0901 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- A desktop (native) development build connects to the editor like a web or mini-game one — log, profiler, the world, content status, pause and step; its renderer cannot capture frames yet and says so. The native host gained a `ws://` client for it.- Profiling a connected development build, the Profiler shows which content revision it runs, the one its next launch starts on, and a hot update it has found but not applied; `device_update_status` answers the same for an agent.- The build's size report shows the start screen on its own line — the markup and any logo inlined into index.html, which is on screen before anything else loads.- Connected development builds are named by the device they run on — `web (Chrome · Android)`, a phone's model on a mini-game — and numbered when two read alike, in the Profiler, Outliner, Frame Debugger and `device_targets`.diff --git a/desktop b/desktopindex fbab1afff..52aeac925 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit fbab1afff8faea87445fc8c6521288ed7e8d45db+Subproject commit 52aeac925b56e6911c6eba8393c052a17819aab1diff --git a/native/CMakeLists.txt b/native/CMakeLists.txtindex ae11e9cc8..c92b5b771 100644--- a/native/CMakeLists.txt+++ b/native/CMakeLists.txt@@ -326,6 +326,7 @@ if(ESTELLA_QUICKJS_DIR)# a phone's keyboard IS one, so there is nothing here for it to be.$<$<BOOL:${ESTELLA_DESKTOP}>:host/media/text_edit.cpp>host/bindings/NetBindings.cpp+ host/net/WsClient.cpphost/bindings/TextEditorBindings.cpphost/bindings/AotBindings.cpp# The name table a compiled system is dispatched through — generated@@ -393,7 +394,7 @@ if(ESTELLA_QUICKJS_DIR)# onecore for CompareObjectHandles, which Dawn's D3D shared fences call:# it lives in kernelbase, kernel32 does not re-export it, and the SDK# ships no kernelbase.lib — onecore is the umbrella that has it.- target_link_libraries(estella_js_host d3d12 dxgi dxguid dwrite winhttp onecore)+ target_link_libraries(estella_js_host d3d12 dxgi dxguid dwrite winhttp onecore ws2_32)elseif(ESTELLA_LINUX)# fontconfig for the font match; libcurl for the fetch, because Linux# is the one desktop with no OS-provided HTTP stack and no trust storediff --git a/native/host/Bindings.hpp b/native/host/Bindings.hppindex 4554b9eb6..9a61bb971 100644--- a/native/host/Bindings.hpp+++ b/native/host/Bindings.hpp@@ -72,6 +72,7 @@ void registerTextEditorBindings(HostState& h, JSValue global);/** Run the JS callbacks for HTTP replies that arrived since the last frame. JS* thread only; {@link deliverFetch} queued them from the completion thread. */void drainFetches(HostState& h);+void drainSockets(HostState& h);/** Push what the editing surface did since the last frame into JS. JS thread* only; the deliverTextEditor* calls queued it from the platform's UI thread. */diff --git a/native/host/Host.cpp b/native/host/Host.cppindex e9ed5d6b5..fcbb315d8 100644--- a/native/host/Host.cpp+++ b/native/host/Host.cpp@@ -367,6 +367,7 @@ void frame() {// Run the callbacks for any HTTP replies that landed since last frame, then// let their .then() continuations run.drainFetches(h);+ drainSockets(h);drainTextEditor(h);pumpJs(h);diff --git a/native/host/Runtime.hpp b/native/host/Runtime.hppindex c6c411704..d6ecb2edb 100644--- a/native/host/Runtime.hpp+++ b/native/host/Runtime.hpp@@ -68,6 +68,7 @@ struct HostState {int64_t nextTimerId = 1;std::unordered_map<int, JSValue> fetchCallbacks; ///< in-flight es_fetch id -> JS callbackint nextFetchId = 1;+ std::unordered_map<int, JSValue> wsCallbacks; ///< open es_wsOpen id -> JS event callbackAudioEngine audio; ///< native sound (miniaudio); silent if no devicestd::string cacheDir; ///< reclaimable — SDK bytecode cache + hot-update contentdiff --git a/native/host/bindings/NetBindings.cpp b/native/host/bindings/NetBindings.cppindex 0ac8de4fb..38f6fa09a 100644--- a/native/host/bindings/NetBindings.cpp+++ b/native/host/bindings/NetBindings.cpp@@ -19,6 +19,7 @@* Licensed under the Apache License, Version 2.0.*/#include "Bindings.hpp"+#include "../net/WsClient.hpp"#include <mutex>#include <queue>@@ -36,6 +37,10 @@ namespace {std::mutex g_fetchMutex;std::queue<FetchResult> g_fetchQueue;+// Socket events arrive on each connection's own thread, and cross the same way.+std::mutex g_wsMutex;+std::queue<WsEvent> g_wsQueue;+std::string fetchStrProp(JSContext* ctx, JSValueConst obj, const char* key, const char* dflt) {JSValue v = JS_GetPropertyStr(ctx, obj, key);std::string out = dflt ? dflt : "";@@ -126,8 +131,85 @@ JSValue makeFetchResult(HostState& h, const FetchResult& r) {return o;}+// es_wsOpen(url, onEvent) -> id: onEvent({ type: 'open' | 'message' | 'error' | 'close',+// data?: string | ArrayBuffer, code?, reason? }). 'close' is always the last event.+JSValue js_wsOpen(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ if (argc < 2 || !JS_IsFunction(ctx, argv[1])) return JS_ThrowTypeError(ctx, "es_wsOpen(url, onEvent)");+ const char* url = JS_ToCString(ctx, argv[0]);+ if (!url) return JS_EXCEPTION;+ const std::string u = url;+ JS_FreeCString(ctx, url);+ const int id = wsOpen(u, [](WsEvent e) {+ std::lock_guard<std::mutex> lk(g_wsMutex);+ g_wsQueue.push(std::move(e));+ });+ host().wsCallbacks[id] = JS_DupValue(ctx, argv[1]);+ return JS_NewInt32(ctx, id);+}++JSValue js_wsSend(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ int32_t id = 0;+ if (argc < 2 || JS_ToInt32(ctx, &id, argv[0])) return JS_FALSE;+ if (JS_IsString(argv[1])) {+ size_t len = 0;+ const char* s = JS_ToCStringLen(ctx, &len, argv[1]);+ if (!s) return JS_EXCEPTION;+ const bool ok = wsSend(id, reinterpret_cast<const uint8_t*>(s), len, true);+ JS_FreeCString(ctx, s);+ return JS_NewBool(ctx, ok);+ }+ std::vector<uint8_t> bytes;+ readByteSource(ctx, argv[1], bytes);+ return JS_NewBool(ctx, wsSend(id, bytes.data(), bytes.size(), false));+}++JSValue js_wsClose(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ int32_t id = 0, code = 1000;+ if (argc < 1 || JS_ToInt32(ctx, &id, argv[0])) return JS_UNDEFINED;+ if (argc > 1 && !JS_IsUndefined(argv[1])) JS_ToInt32(ctx, &code, argv[1]);+ std::string reason;+ if (argc > 2 && JS_IsString(argv[2])) {+ if (const char* r = JS_ToCString(ctx, argv[2])) { reason = r; JS_FreeCString(ctx, r); }+ }+ wsClose(id, code, reason);+ return JS_UNDEFINED;+}+} // namespace+void drainSockets(HostState& h) {+ std::queue<WsEvent> events;+ { std::lock_guard<std::mutex> lk(g_wsMutex); events.swap(g_wsQueue); }+ if (events.empty()) return;+ jsEntry(h);+ while (!events.empty()) {+ WsEvent e = std::move(events.front());+ events.pop();+ auto it = h.wsCallbacks.find(e.id);+ if (it == h.wsCallbacks.end()) continue;+ JSValue o = JS_NewObject(h.js);+ const char* type = e.kind == WsEvent::Kind::Open ? "open"+ : e.kind == WsEvent::Kind::Error ? "error"+ : e.kind == WsEvent::Kind::Close ? "close" : "message";+ JS_SetPropertyStr(h.js, o, "type", JS_NewString(h.js, type));+ if (e.kind == WsEvent::Kind::Text) {+ JS_SetPropertyStr(h.js, o, "data",+ JS_NewStringLen(h.js, reinterpret_cast<const char*>(e.data.data()), e.data.size()));+ } else if (e.kind == WsEvent::Kind::Binary) {+ JS_SetPropertyStr(h.js, o, "data", JS_NewArrayBufferCopy(h.js, e.data.data(), e.data.size()));+ }+ if (e.kind == WsEvent::Kind::Close) JS_SetPropertyStr(h.js, o, "code", JS_NewInt32(h.js, e.code));+ if (!e.reason.empty()) JS_SetPropertyStr(h.js, o, "reason", JS_NewString(h.js, e.reason.c_str()));+ JSValue cb = it->second;+ if (e.kind == WsEvent::Kind::Close) h.wsCallbacks.erase(it);+ JSValue ret = JS_Call(h.js, cb, JS_UNDEFINED, 1, &o);+ if (JS_IsException(ret)) logJsError(h.js, "es_wsOpen event");+ JS_FreeValue(h.js, ret);+ JS_FreeValue(h.js, o);+ if (e.kind == WsEvent::Kind::Close) JS_FreeValue(h.js, cb);+ }+}+void drainFetches(HostState& h) {jsEntry(h);std::queue<FetchResult> done;@@ -150,6 +232,9 @@ void drainFetches(HostState& h) {void registerNetBindings(HostState& h, JSValue global) {bindGlobal(h, global, "es_fetch", js_fetch, 2);+ bindGlobal(h, global, "es_wsOpen", js_wsOpen, 2);+ bindGlobal(h, global, "es_wsSend", js_wsSend, 2);+ bindGlobal(h, global, "es_wsClose", js_wsClose, 3);}// Thread-safe: the platform's HTTP completion (any thread) queues its reply here;diff --git a/native/host/net/WsClient.cpp b/native/host/net/WsClient.cppnew file mode 100644index 000000000..05ab3e95f--- /dev/null+++ b/native/host/net/WsClient.cpp@@ -0,0 +1,376 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file WsClient.cpp+ * @brief RFC 6455 client framing over blocking TCP sockets (POSIX and Winsock).+ */+#include "WsClient.hpp"++#include <algorithm>+#include <atomic>+#include <cstring>+#include <memory>+#include <mutex>+#include <random>+#include <thread>+#include <unordered_map>++#ifdef _WIN32+# ifndef WIN32_LEAN_AND_MEAN+# define WIN32_LEAN_AND_MEAN+# endif+# include <winsock2.h>+# include <ws2tcpip.h>+using SocketHandle = SOCKET;+constexpr SocketHandle kNoSocket = INVALID_SOCKET;+#else+# include <netdb.h>+# include <netinet/in.h>+# include <netinet/tcp.h>+# include <sys/socket.h>+# include <sys/types.h>+# include <unistd.h>+using SocketHandle = int;+constexpr SocketHandle kNoSocket = -1;+#endif++namespace eshost {+namespace {++#ifdef MSG_NOSIGNAL+constexpr int kSendFlags = MSG_NOSIGNAL;+#else+constexpr int kSendFlags = 0;+#endif++void closeSocket(SocketHandle s) {+#ifdef _WIN32+ closesocket(s);+#else+ ::close(s);+#endif+}++void shutdownSocket(SocketHandle s) {+#ifdef _WIN32+ shutdown(s, SD_BOTH);+#else+ shutdown(s, SHUT_RDWR);+#endif+}++void ensureSockets() {+#ifdef _WIN32+ static std::once_flag once;+ std::call_once(once, [] { WSADATA d; WSAStartup(MAKEWORD(2, 2), &d); });+#endif+}++// — SHA-1 and base64, for the handshake's Sec-WebSocket-Accept —++uint32_t rol(uint32_t v, int n) { return (v << n) | (v >> (32 - n)); }++void sha1(const std::string& in, uint8_t out[20]) {+ uint32_t h[5] = { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 };+ std::string msg = in;+ const uint64_t bits = static_cast<uint64_t>(in.size()) * 8;+ msg += static_cast<char>(0x80);+ while (msg.size() % 64 != 56) msg += '\0';+ for (int i = 7; i >= 0; --i) msg += static_cast<char>((bits >> (i * 8)) & 0xFF);+ for (size_t chunk = 0; chunk < msg.size(); chunk += 64) {+ uint32_t w[80];+ for (int i = 0; i < 16; ++i) {+ const auto* p = reinterpret_cast<const uint8_t*>(msg.data() + chunk + i * 4);+ w[i] = (uint32_t(p[0]) << 24) | (uint32_t(p[1]) << 16) | (uint32_t(p[2]) << 8) | p[3];+ }+ for (int i = 16; i < 80; ++i) w[i] = rol(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);+ uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4];+ for (int i = 0; i < 80; ++i) {+ uint32_t f, k;+ if (i < 20) { f = (b & c) | (~b & d); k = 0x5A827999; }+ else if (i < 40) { f = b ^ c ^ d; k = 0x6ED9EBA1; }+ else if (i < 60) { f = (b & c) | (b & d) | (c & d); k = 0x8F1BBCDC; }+ else { f = b ^ c ^ d; k = 0xCA62C1D6; }+ const uint32_t t = rol(a, 5) + f + e + k + w[i];+ e = d; d = c; c = rol(b, 30); b = a; a = t;+ }+ h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e;+ }+ for (int i = 0; i < 5; ++i) {+ out[i * 4] = uint8_t(h[i] >> 24); out[i * 4 + 1] = uint8_t(h[i] >> 16);+ out[i * 4 + 2] = uint8_t(h[i] >> 8); out[i * 4 + 3] = uint8_t(h[i]);+ }+}++std::string base64(const uint8_t* data, size_t len) {+ static const char* T = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+ std::string out;+ for (size_t i = 0; i < len; i += 3) {+ const uint32_t n = (uint32_t(data[i]) << 16) | (i + 1 < len ? uint32_t(data[i + 1]) << 8 : 0)+ | (i + 2 < len ? data[i + 2] : 0);+ out += T[(n >> 18) & 63];+ out += T[(n >> 12) & 63];+ out += i + 1 < len ? T[(n >> 6) & 63] : '=';+ out += i + 2 < len ? T[n & 63] : '=';+ }+ return out;+}++// — One connection —++struct Conn {+ int id = 0;+ SocketHandle sock = kNoSocket;+ WsSink sink;+ std::mutex sendMutex;+ std::atomic<bool> open{false};+ std::atomic<bool> closeSent{false};+ std::mt19937 rng{std::random_device{}()};+};++std::mutex g_connsMutex;+std::unordered_map<int, std::shared_ptr<Conn>> g_conns;+std::atomic<int> g_nextId{1};++std::shared_ptr<Conn> connOf(int id) {+ std::lock_guard<std::mutex> lk(g_connsMutex);+ auto it = g_conns.find(id);+ return it == g_conns.end() ? nullptr : it->second;+}++bool sendAll(SocketHandle s, const uint8_t* p, size_t n) {+ while (n > 0) {+ const auto sent = ::send(s, reinterpret_cast<const char*>(p), static_cast<int>(n), kSendFlags);+ if (sent <= 0) return false;+ p += sent;+ n -= static_cast<size_t>(sent);+ }+ return true;+}++bool recvAll(SocketHandle s, uint8_t* p, size_t n) {+ while (n > 0) {+ const auto got = ::recv(s, reinterpret_cast<char*>(p), static_cast<int>(n), 0);+ if (got <= 0) return false;+ p += got;+ n -= static_cast<size_t>(got);+ }+ return true;+}++/** A client frame: always masked, as RFC 6455 requires of a client. */+bool sendFrame(Conn& c, uint8_t opcode, const uint8_t* data, size_t len) {+ std::vector<uint8_t> f;+ f.reserve(len + 14);+ f.push_back(uint8_t(0x80 | opcode));+ if (len < 126) {+ f.push_back(uint8_t(0x80 | len));+ } else if (len <= 0xFFFF) {+ f.push_back(0x80 | 126);+ f.push_back(uint8_t(len >> 8)); f.push_back(uint8_t(len));+ } else {+ f.push_back(0x80 | 127);+ for (int i = 7; i >= 0; --i) f.push_back(uint8_t(uint64_t(len) >> (i * 8)));+ }+ std::lock_guard<std::mutex> lk(c.sendMutex);+ uint8_t mask[4];+ for (auto& m : mask) m = uint8_t(c.rng());+ f.insert(f.end(), mask, mask + 4);+ const size_t at = f.size();+ f.insert(f.end(), data, data + len);+ for (size_t i = 0; i < len; ++i) f[at + i] ^= mask[i % 4];+ return sendAll(c.sock, f.data(), f.size());+}++struct Url { std::string host, port, path; };++bool parseWsUrl(const std::string& url, Url& out) {+ const std::string scheme = "ws://";+ if (url.compare(0, scheme.size(), scheme) != 0) return false;+ const std::string rest = url.substr(scheme.size());+ const size_t slash = rest.find('/');+ const std::string authority = rest.substr(0, slash);+ out.path = slash == std::string::npos ? "/" : rest.substr(slash);+ const size_t colon = authority.rfind(':');+ out.host = colon == std::string::npos ? authority : authority.substr(0, colon);+ out.port = colon == std::string::npos ? "80" : authority.substr(colon + 1);+ return !out.host.empty();+}++SocketHandle dial(const Url& u) {+ addrinfo hints{};+ hints.ai_family = AF_UNSPEC;+ hints.ai_socktype = SOCK_STREAM;+ addrinfo* res = nullptr;+ if (getaddrinfo(u.host.c_str(), u.port.c_str(), &hints, &res) != 0) return kNoSocket;+ SocketHandle s = kNoSocket;+ for (addrinfo* a = res; a; a = a->ai_next) {+ s = ::socket(a->ai_family, a->ai_socktype, a->ai_protocol);+ if (s == kNoSocket) continue;+ if (::connect(s, a->ai_addr, static_cast<int>(a->ai_addrlen)) == 0) break;+ closeSocket(s);+ s = kNoSocket;+ }+ freeaddrinfo(res);+ if (s == kNoSocket) return s;+ int one = 1;+ setsockopt(s, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<const char*>(&one), sizeof one);+#ifdef SO_NOSIGPIPE+ setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof one);+#endif+ return s;+}++std::string lower(std::string s) {+ for (char& ch : s) ch = static_cast<char>(tolower(static_cast<unsigned char>(ch)));+ return s;+}++/** The opening handshake; an error message on failure, empty on success. */+std::string handshake(Conn& c, const Url& u) {+ uint8_t nonce[16];+ for (auto& b : nonce) b = uint8_t(c.rng());+ const std::string key = base64(nonce, sizeof nonce);+ const std::string req = "GET " + u.path + " HTTP/1.1\r\nHost: " + u.host + ":" + u.port+ + "\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: " + key+ + "\r\nSec-WebSocket-Version: 13\r\n\r\n";+ if (!sendAll(c.sock, reinterpret_cast<const uint8_t*>(req.data()), req.size())) return "handshake send failed";+ std::string head;+ char ch;+ while (head.size() < 8192 && head.find("\r\n\r\n") == std::string::npos) {+ if (::recv(c.sock, &ch, 1, 0) <= 0) return "the server closed during the handshake";+ head += ch;+ }+ if (head.compare(0, 12, "HTTP/1.1 101") != 0) return "refused: " + head.substr(0, head.find("\r\n"));+ const std::string lo = lower(head);+ const size_t at = lo.find("\r\nsec-websocket-accept:");+ if (at == std::string::npos) return "no Sec-WebSocket-Accept in the reply";+ size_t v = at + 23;+ while (v < head.size() && head[v] == ' ') ++v;+ const std::string accept = head.substr(v, head.find("\r\n", v) - v);+ if (accept != wsAcceptFor(key)) return "Sec-WebSocket-Accept does not answer the key";+ return {};+}++void emit(Conn& c, WsEvent::Kind kind, std::vector<uint8_t> data = {}, int code = 0, std::string reason = {}) {+ WsEvent e;+ e.id = c.id;+ e.kind = kind;+ e.data = std::move(data);+ e.code = code;+ e.reason = std::move(reason);+ c.sink(std::move(e));+}++void run(std::shared_ptr<Conn> c, std::string url) {+ auto finish = [&](int code, std::string reason) {+ c->open = false;+ {+ std::lock_guard<std::mutex> lk(c->sendMutex);+ if (c->sock != kNoSocket) { closeSocket(c->sock); c->sock = kNoSocket; }+ }+ emit(*c, WsEvent::Kind::Close, {}, code, std::move(reason));+ std::lock_guard<std::mutex> lk(g_connsMutex);+ g_conns.erase(c->id);+ };+ Url u;+ if (!parseWsUrl(url, u)) {+ emit(*c, WsEvent::Kind::Error, {}, 0, "only ws:// URLs are supported: " + url);+ return finish(1006, "bad url");+ }+ c->sock = dial(u);+ if (c->sock == kNoSocket) {+ emit(*c, WsEvent::Kind::Error, {}, 0, "could not connect to " + u.host + ":" + u.port);+ return finish(1006, "connect failed");+ }+ if (std::string why = handshake(*c, u); !why.empty()) {+ emit(*c, WsEvent::Kind::Error, {}, 0, why);+ return finish(1006, why);+ }+ c->open = true;+ emit(*c, WsEvent::Kind::Open);++ std::vector<uint8_t> message;+ uint8_t messageOp = 0;+ for (;;) {+ uint8_t hdr[2];+ if (!recvAll(c->sock, hdr, 2)) return finish(1006, "connection lost");+ const bool fin = hdr[0] & 0x80;+ const uint8_t op = hdr[0] & 0x0F;+ uint64_t len = hdr[1] & 0x7F;+ if (len == 126) {+ uint8_t b[2];+ if (!recvAll(c->sock, b, 2)) return finish(1006, "connection lost");+ len = (uint64_t(b[0]) << 8) | b[1];+ } else if (len == 127) {+ uint8_t b[8];+ if (!recvAll(c->sock, b, 8)) return finish(1006, "connection lost");+ len = 0;+ for (uint8_t x : b) len = (len << 8) | x;+ }+ uint8_t mask[4] = {0, 0, 0, 0};+ const bool masked = hdr[1] & 0x80;+ if (masked && !recvAll(c->sock, mask, 4)) return finish(1006, "connection lost");+ std::vector<uint8_t> payload(static_cast<size_t>(len));+ if (len > 0 && !recvAll(c->sock, payload.data(), payload.size())) return finish(1006, "connection lost");+ if (masked) for (size_t i = 0; i < payload.size(); ++i) payload[i] ^= mask[i % 4];++ if (op == 0x8) {+ const int code = payload.size() >= 2 ? (payload[0] << 8) | payload[1] : 1005;+ std::string reason = payload.size() > 2 ? std::string(payload.begin() + 2, payload.end()) : "";+ if (!c->closeSent.exchange(true)) sendFrame(*c, 0x8, payload.data(), std::min<size_t>(payload.size(), 2));+ return finish(code, std::move(reason));+ }+ if (op == 0x9) { sendFrame(*c, 0xA, payload.data(), payload.size()); continue; }+ if (op == 0xA) continue;+ if (op == 0x1 || op == 0x2) { message = std::move(payload); messageOp = op; }+ else if (op == 0x0) message.insert(message.end(), payload.begin(), payload.end());+ else continue;+ if (fin) {+ emit(*c, messageOp == 0x1 ? WsEvent::Kind::Text : WsEvent::Kind::Binary, std::move(message));+ message.clear();+ }+ }+}++} // namespace++std::string wsAcceptFor(const std::string& key) {+ uint8_t digest[20];+ sha1(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", digest);+ return base64(digest, sizeof digest);+}++int wsOpen(const std::string& url, WsSink sink) {+ ensureSockets();+ auto c = std::make_shared<Conn>();+ c->id = g_nextId++;+ c->sink = std::move(sink);+ {+ std::lock_guard<std::mutex> lk(g_connsMutex);+ g_conns[c->id] = c;+ }+ std::thread(run, c, url).detach();+ return c->id;+}++bool wsSend(int id, const uint8_t* data, size_t len, bool text) {+ auto c = connOf(id);+ if (!c || !c->open || c->closeSent) return false;+ return sendFrame(*c, text ? 0x1 : 0x2, data, len);+}++void wsClose(int id, int code, const std::string& reason) {+ auto c = connOf(id);+ if (!c) return;+ if (c->open && !c->closeSent.exchange(true)) {+ std::vector<uint8_t> body = { uint8_t(code >> 8), uint8_t(code) };+ body.insert(body.end(), reason.begin(), reason.end());+ sendFrame(*c, 0x8, body.data(), body.size());+ }+ // The reader thread finishes on the server's close reply, or here if none comes.+ std::lock_guard<std::mutex> lk(c->sendMutex);+ if (c->sock != kNoSocket) shutdownSocket(c->sock);+}++} // namespace eshostdiff --git a/native/host/net/WsClient.hpp b/native/host/net/WsClient.hppnew file mode 100644index 000000000..39d51f781--- /dev/null+++ b/native/host/net/WsClient.hpp@@ -0,0 +1,45 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file WsClient.hpp+ * @brief A plain `ws://` WebSocket client over the OS's TCP sockets, one thread+ * per connection, for a development build's line back to the editor.+ * @details Portable rather than per-platform like es_fetch: the editor is on the+ * LAN and speaks `ws://`, so there is no TLS stack to borrow from the OS+ * and one implementation serves every host. Events are handed out through+ * a sink that may run on the connection's thread.+ */+#pragma once++#include <cstdint>+#include <functional>+#include <string>+#include <vector>++namespace eshost {++struct WsEvent {+ enum class Kind { Open, Text, Binary, Error, Close };+ int id = 0;+ Kind kind = Kind::Open;+ std::vector<uint8_t> data;+ int code = 0;+ std::string reason;+};++using WsSink = std::function<void(WsEvent)>;++/** Dial @p url on a new thread; every event for the returned id goes to @p sink.+ * A connection that cannot be made reports Error then Close(1006). */+int wsOpen(const std::string& url, WsSink sink);++/** Send one message; false once the connection is not open. */+bool wsSend(int id, const uint8_t* data, size_t len, bool text);++/** Start the closing handshake; the Close event follows from the connection. */+void wsClose(int id, int code, const std::string& reason);++/** @internal Exposed for tests: base64(SHA-1(key + RFC 6455 GUID)). */+std::string wsAcceptFor(const std::string& key);++} // namespace eshostdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 536ee2e08..aba9aa5f9 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -5237,6 +5237,7 @@ registerInput: (listener: NativeInputListener) => () => voidremoveStorageItem: (key: string) => voidsetStorageItem: (key: string, value: string) => voidsetWindowSize: ((width: number, height: number) => void) | undefined+socket: NativeSocketBridge | undefinedsteam: NativeSteamBridge | undefinedstorageKeys: () => string[]textEditor: NativeTextEditorBridge | undefined@@ -5316,6 +5317,9 @@ es_textEditor_focus: ((value: string, selectionStart: number, selectionEnd: numbes_textEditor_write: ((value: string, selectionStart: number, selectionEnd: number) => void) | undefinedes_writeCacheFile: ((key: string, bytes: ArrayBuffer | Uint8Array | string) => boolean) | undefinedes_writeDataFile: ((key: string, bytes: ArrayBuffer | Uint8Array | string) => boolean) | undefined+es_wsClose: ((id: number, code?: number, reason?: string) => void) | undefined+es_wsOpen: ((url: string, onEvent: (event: NativeSocketEvent) => void) => number) | undefined+es_wsSend: ((id: number, data: string | ArrayBuffer) => boolean) | undefined```## NativeInputListener — interface @beta@@ -5346,6 +5350,7 @@ clearStorage: (prefix: string) => voidcreateAudioBackend: (() => PlatformAudioBackend) | undefinedcreateCanvas: (_width: number, _height: number) => PlatformCanvascreateImage: () => PlatformImage+createSocket: (options: PlatformSocketOptions) => PlatformSocketcreateTextEditor: () => PlatformTextEditor | nullcreateVideoBackend: (ctx: VideoBackendContext) => PlatformVideoBackenddevicePixelRatio: () => numberdiff --git a/sdk/src/platform/native/adapter.ts b/sdk/src/platform/native/adapter.tsindex 2b43f295f..26b8f0042 100644--- a/sdk/src/platform/native/adapter.ts+++ b/sdk/src/platform/native/adapter.ts@@ -27,7 +27,10 @@ import type {PlatformGlyph,PlatformGlyphRequest,PlatformTextEditor,+ PlatformSocket,+ PlatformSocketOptions,} from '../types';+import { NativeSocket } from './socket';import type { PlatformAudioBackend } from '../../audio/PlatformAudioBackend';import type { PlatformVideoBackend, VideoBackendContext } from '../../video/PlatformVideoBackend';import { WasmVideoBackend } from '../../video/WasmVideoBackend';@@ -275,7 +278,11 @@ export class NativePlatformAdapter implements PlatformAdapter {return () => { live = false; };}- // createSocket / loadSubpackage are optional and deferred to the shell.+ createSocket(options: PlatformSocketOptions): PlatformSocket {+ const socket = this.bridge_.socket;+ if (!socket) throw new Error('this native host carries no socket client');+ return new NativeSocket(options.url, socket);+ }}/** Install a {@link NativePlatformAdapter} built from the host `bridge` as thediff --git a/sdk/src/platform/native/bridge.ts b/sdk/src/platform/native/bridge.tsindex cb6982891..1b6aed8af 100644--- a/sdk/src/platform/native/bridge.ts+++ b/sdk/src/platform/native/bridge.ts@@ -226,6 +226,10 @@ export interface NativeBridge {* Null backend. See {@link NativeAudioBridge}. */audio?: NativeAudioBridge;+ /** `ws://` sockets, on a host that carries the client. Absent → `createSocket`+ * is unavailable, as it is on a host with no network. */+ socket?: NativeSocketBridge;+/** The OS text-editing surface (soft keyboard + IME), when the host has wired* one. Absent → fields render but cannot be typed into, exactly as a host* with no audio device stays silent. See {@link NativeTextEditorBridge}. */@@ -260,3 +264,18 @@ export interface NativeBridge {* a shell that has not wired it simply never fires. */onContextLost?(callback: () => void): () => void;}++/** One event from the host's socket client; `close` is always the last. */+export interface NativeSocketEvent {+ type: 'open' | 'message' | 'error' | 'close';+ data?: string | ArrayBuffer;+ code?: number;+ reason?: string;+}++export interface NativeSocketBridge {+ open(url: string, onEvent: (event: NativeSocketEvent) => void): {+ send(data: string | ArrayBuffer): boolean;+ close(code?: number, reason?: string): void;+ };+}diff --git a/sdk/src/platform/native/hostBridge.ts b/sdk/src/platform/native/hostBridge.tsindex f8fcaed18..0461300e6 100644--- a/sdk/src/platform/native/hostBridge.ts+++ b/sdk/src/platform/native/hostBridge.ts@@ -15,7 +15,7 @@import { log } from '../../util/logger';import type {NativeAudioBridge, NativeBridge, NativeFetchResult, NativeInputListener,- NativeTextEditorBridge, NativeTextEditorPush,+ NativeTextEditorBridge, NativeTextEditorPush, NativeSocketEvent,} from './bridge';import type { PlatformGlyph, PlatformGlyphRequest, PlatformRequestOptions } from '../types';import { assertHostEnvironment } from './hostEnvironment';@@ -106,6 +106,11 @@ export interface NativeHostBindings {}) => void,): void;+ /** The host's `ws://` client: events arrive on the JS thread, `close` last. */+ es_wsOpen?(url: string, onEvent: (event: NativeSocketEvent) => void): number;+ es_wsSend?(id: number, data: string | ArrayBuffer): boolean;+ es_wsClose?(id: number, code?: number, reason?: string): void;+/** The native audio engine, all-or-nothing (see {@link AUDIO_BINDINGS}). A* host without a sound device binds none and stays silent. */// The OS text-editing surface (soft keyboard + IME). Optional as a group:@@ -190,6 +195,17 @@ export function createHostBridge(},fileExists: (path) => Promise.resolve(bindings.es_readAsset(path) != null),fetch: (url, options) => hostFetch(bindings, url, options),+ ...(bindings.es_wsOpen && bindings.es_wsSend && bindings.es_wsClose ? {+ socket: {+ open: (url, onEvent) => {+ const id = bindings.es_wsOpen!(url, onEvent);+ return {+ send: (data) => bindings.es_wsSend!(id, data),+ close: (code, reason) => bindings.es_wsClose!(id, code, reason),+ };+ },+ },+ } : {}),loadImagePixels: async (path) => {// The host decodes packaged paths; a CDN image is bytes the script brings,// from the hot-update cache when it is there, else from the network.diff --git a/sdk/src/platform/native/socket.ts b/sdk/src/platform/native/socket.tsnew file mode 100644index 000000000..960e16aff--- /dev/null+++ b/sdk/src/platform/native/socket.ts@@ -0,0 +1,54 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file socket.ts — a platform socket over the native host's `ws://` client.+ */+import { Emitter } from '../../ecs/emitter';+import type { PlatformSocket, PlatformSocketEvents, PlatformSocketReadyState } from '../types';+import type { NativeSocketBridge } from './bridge';++export class NativeSocket implements PlatformSocket {+ readonly delivery = 'reliable-ordered' as const;+ readyState: PlatformSocketReadyState = 'closed';+ private readonly events_ = new Emitter<PlatformSocketEvents>();+ private handle_: { send(data: string | ArrayBuffer): boolean; close(code?: number, reason?: string): void } | null = null;+ private queue_: (string | ArrayBuffer)[] = [];++ constructor(private readonly url_: string, private readonly bridge_: NativeSocketBridge) {}++ on<K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void): () => void {+ return this.events_.on(event, handler);+ }++ connect(): void {+ if (this.handle_) return;+ this.readyState = 'connecting';+ this.handle_ = this.bridge_.open(this.url_, (e) => {+ if (e.type === 'open') {+ this.readyState = 'open';+ for (const m of this.queue_) this.handle_?.send(m);+ this.queue_ = [];+ this.events_.emit('open');+ } else if (e.type === 'message') {+ this.events_.emit('message', e.data ?? '');+ } else if (e.type === 'error') {+ this.events_.emit('error', new Error(e.reason ?? 'socket error'));+ } else {+ this.readyState = 'closed';+ this.handle_ = null;+ this.events_.emit('close', e.code ?? 1006, e.reason ?? '');+ }+ });+ }++ send(data: string | ArrayBuffer): void {+ if (this.readyState === 'open' && this.handle_) this.handle_.send(data);+ else this.queue_.push(data);+ }++ close(code?: number, reason?: string): void {+ if (!this.handle_) return;+ this.readyState = 'closing';+ this.handle_.close(code, reason);+ }+}diff --git a/sdk/src/runtime/debugChannel.ts b/sdk/src/runtime/debugChannel.tsindex 0f8b5da80..b88a813bb 100644--- a/sdk/src/runtime/debugChannel.ts+++ b/sdk/src/runtime/debugChannel.ts@@ -133,8 +133,13 @@ export function startDebugChannel(config: DebugChannelConfig): void {if ((q.kind === 'frameCapture' || q.kind === 'frameReplay') && !drawsFrames) {throw new Error('the game is in the background, where it draws no frames: bring it to the front');}+ if ((q.kind === 'frameCapture' || q.kind === 'frameReplay') && !game.wasmModule) {+ throw new Error('this build cannot capture frames: a native host has no frame capture yet');+ }if (q.kind === 'frameCapture') {- reply({ t: 'reply', reqId: q.reqId, data: await captureFrameReport(game, frame) });+ const report = await captureFrameReport(game, frame);+ if (!report) throw new Error('no frame arrived to capture — is the game running frames?');+ reply({ t: 'reply', reqId: q.reqId, data: report });return;}if (q.kind === 'stats') {diff --git a/sdk/tests/debug-channel.test.ts b/sdk/tests/debug-channel.test.tsindex 99eb64738..06dcfbf5f 100644--- a/sdk/tests/debug-channel.test.ts+++ b/sdk/tests/debug-channel.test.ts@@ -64,6 +64,22 @@ describe('the debug channel', () => {});});+describe('a build whose renderer cannot capture', () => {+ it('says so, rather than answering with nothing', async () => {+ vi.resetModules();+ const base = await import('../src/platform/base');+ const channel = await import('../src/runtime/debugChannel');+ const s = fakeSocket();+ base.setPlatform({ name: 'native', now: () => performance.now(), createSocket: () => s.socket } as unknown as PlatformAdapter);+ channel.startDebugChannel({ url: 'ws://editor:1/?token=t', project: 'Demo' });+ s.open();+ channel.attachDebugChannel({ hasResource: () => false, onFrameEnd: () => () => {}, wasmModule: null } as unknown as App);+ s.receive({ t: 'query', reqId: 12, kind: 'frameCapture' });+ await flush();+ expect(s.sent.find((m) => (m as { reqId?: number }).reqId === 12)).toMatchObject({ error: expect.stringMatching(/native host/) });+ });+});+describe('a device asked about its content', () => {it('answers with the revision it runs and what update is staged', async () => {vi.resetModules();diff --git a/sdk/tests/native-socket.test.ts b/sdk/tests/native-socket.test.tsnew file mode 100644index 000000000..7eb02ad1e--- /dev/null+++ b/sdk/tests/native-socket.test.ts@@ -0,0 +1,64 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A native build's socket, over the host's `ws://` client: what is sent+ * before it opens goes out when it does, and its close is the last word.+ */+import { describe, it, expect } from 'vitest';+import { NativeSocket } from '../src/platform/native/socket';+import type { NativeSocketBridge, NativeSocketEvent } from '../src/platform/native/bridge';++function host() {+ let fire: (e: NativeSocketEvent) => void = () => {};+ const sent: (string | ArrayBuffer)[] = [];+ const closed: Array<[number | undefined, string | undefined]> = [];+ const bridge: NativeSocketBridge = {+ open: (_url, onEvent) => {+ fire = onEvent;+ return { send: (d) => { sent.push(d); return true; }, close: (c, r) => { closed.push([c, r]); } };+ },+ };+ return { bridge, sent, closed, fire: (e: NativeSocketEvent) => fire(e) };+}++describe('a native socket', () => {+ it('holds what was sent before it opened, and sends it on open', () => {+ const h = host();+ const s = new NativeSocket('ws://editor:37420/?token=t', h.bridge);+ const seen: string[] = [];+ s.on('open', () => seen.push('open'));+ s.on('message', (d) => seen.push(`message ${String(d)}`));+ s.connect();+ s.send('hello');+ expect(h.sent).toEqual([]);+ h.fire({ type: 'open' });+ expect(h.sent).toEqual(['hello']);+ h.fire({ type: 'message', data: '{"t":"query"}' });+ expect(seen).toEqual(['open', 'message {"t":"query"}']);+ expect(s.readyState).toBe('open');+ });++ it('reports a refused dial as an error then a close, and can dial again', () => {+ const h = host();+ const s = new NativeSocket('ws://editor:1/', h.bridge);+ const seen: string[] = [];+ s.on('error', () => seen.push('error'));+ s.on('close', (code) => seen.push(`close ${code}`));+ s.connect();+ h.fire({ type: 'error', reason: 'could not connect to editor:1' });+ h.fire({ type: 'close', code: 1006, reason: 'connect failed' });+ expect(seen).toEqual(['error', 'close 1006']);+ expect(s.readyState).toBe('closed');+ s.connect();+ expect(s.readyState).toBe('connecting');+ });++ it('passes its close to the host', () => {+ const h = host();+ const s = new NativeSocket('ws://editor:1/', h.bridge);+ s.connect();+ h.fire({ type: 'open' });+ s.close(1000, 'bye');+ expect(h.closed).toEqual([[1000, 'bye']]);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 3d80b9eff..49f405a85 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -1126,4 +1126,8 @@ export const NOTED = {{ note: 'Profiling a connected development build, the Profiler shows which content revision it runs, the one its next launch starts on, and a hot update it has found but not applied; `device_update_status` answers the same for an agent.' },'feat(profiler): a connected build says which content it runs and what update waits':{ note: 'Profiling a connected development build, the Profiler shows which content revision it runs, the one its next launch starts on, and a hot update it has found but not applied; `device_update_status` answers the same for an agent.' },+ 'feat(native): a native build can connect to the editor over the debug channel':+ { note: 'A desktop (native) development build connects to the editor like a web or mini-game one — log, profiler, the world, content status, pause and step; its renderer cannot capture frames yet and says so. The native host gained a `ws://` client for it.' },+ 'feat(build): a desktop development build can dial the editor':+ { note: 'A desktop (native) development build connects to the editor like a web or mini-game one — log, profiler, the world, content status, pause and step; its renderer cannot capture frames yet and says so. The native host gained a `ws://` client for it.' },};