Skip to content

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.

feat(native): HTTP over the platform's native stack (es_fetch)

esenginea7621d6a411d
diff --git a/native/README.md b/native/README.md
index c5b3ee561..0c3a1e911 100644
--- a/native/README.md
+++ b/native/README.md
@@ -239,8 +239,13 @@ System bindings landing incrementally through the real SDK surfaces:
(`eshost::memoryWarning`, iOS `didReceiveMemoryWarning` / Android `APP_CMD_LOW_MEMORY`) →
the SDK's residency caches trim (the audio buffer cache). Simulator-verified across a
background/foreground cycle.
+- **Networking** — `bridge.fetch` runs a real HTTP request through `es_fetch`
+ (`Platform::startFetch`): iOS `NSURLSession`, Android a JNI `HttpURLConnection` on a
+ detached thread — the OS owns the TLS stack, so this is one seam that legitimately
+ differs per platform. Replies cross back thread-safely (`deliverFetch`) and run on the JS
+ thread in the frame loop. This is what remote asset groups and hot-update need. Simulator-
+ verified (an HTTPS GET returns bytes and a 200); the Android path needs a device retest.
Remaining: KTX2 / compressed textures (native decodes to RGBA only — no basis transcoder
-yet), networking (`bridge.fetch` is offline, so remote asset groups and hot-update do not
-resolve), and hardening on a physical device (audio output, the background/foreground
-transition, Android's miniaudio AAudio path).
+yet) and hardening on a physical device (audio output, the background/foreground
+transition, Android's miniaudio audio + JNI fetch paths).
diff --git a/native/host_js/game.js b/native/host_js/game.js
index efef9e763..4dff30ca5 100644
--- a/native/host_js/game.js
+++ b/native/host_js/game.js
@@ -63,6 +63,15 @@ function init() {
} else {
console.log('[demo] audio: no Audio resource');
}
+
+ // Stage: prove native networking — es_fetch over NSURLSession/OkHttp, TLS by
+ // the OS. The async reply lands back on the JS thread via the frame loop.
+ globalThis.__esNativeBridge.fetch('https://example.com').then(function (r) {
+ var bytes = r.arrayBuffer ? r.arrayBuffer.byteLength : (r.text ? r.text.length : 0);
+ console.log('[demo] fetch: ok=' + r.ok + ' status=' + r.status + ' bytes=' + bytes);
+ }, function (e) {
+ console.error('[demo] fetch failed:', e && e.message ? e.message : e);
+ });
}
function update(dt) {
diff --git a/native/host_js/host_core.cpp b/native/host_js/host_core.cpp
index 5032764c7..d29c888ea 100644
--- a/native/host_js/host_core.cpp
+++ b/native/host_js/host_core.cpp
@@ -50,7 +50,11 @@
#include <cstdio>
#include <cstring>
#include <ctime>
+#include <mutex>
+#include <queue>
#include <string>
+#include <unordered_map>
+#include <utility>
#include <vector>
using namespace esengine;
@@ -116,6 +120,8 @@ struct App {
std::string cacheDir; // app private dir — SDK bytecode cache
std::vector<Timer> timers;
int64_t next_timer_id = 1;
+ std::unordered_map<int, JSValue> fetchCallbacks; // in-flight es_fetch id -> JS callback
+ int nextFetchId = 1;
glm::vec4 clear{0.07f, 0.08f, 0.12f, 1.0f};
f32 w = 0, h = 0;
bool ready = false; // engine + JS booted once
@@ -125,6 +131,13 @@ struct App {
App* g_app = nullptr;
+// HTTP replies cross back from whatever thread the platform's completion runs on.
+// The platform enqueues here (POD only, no JS); the frame loop drains it on the JS
+// thread and runs the callbacks. Kept outside App so deliverFetch (a free function
+// the glue calls) needs no App pointer and is safe before/after boot.
+std::mutex g_fetchMutex;
+std::queue<eshost::FetchResult> g_fetchQueue;
+
double nowMs();
void hostLog(bool error, const char* fmt, ...) {
@@ -630,6 +643,118 @@ void callJs(App& a, const char* fn, int argc, JSValue* argv) {
JS_FreeValue(a.js, global);
}
+// ---- HTTP: es_fetch over the platform's native networking -------------------
+
+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 : "";
+ if (JS_IsString(v)) {
+ if (const char* s = JS_ToCString(ctx, v)) { out = s; JS_FreeCString(ctx, s); }
+ }
+ JS_FreeValue(ctx, v);
+ return out;
+}
+
+void readFetchHeaders(JSContext* ctx, JSValueConst obj, eshost::FetchRequest& req) {
+ JSValue h = JS_GetPropertyStr(ctx, obj, "headers");
+ if (JS_IsObject(h)) {
+ JSPropertyEnum* tab = nullptr;
+ uint32_t len = 0;
+ if (JS_GetOwnPropertyNames(ctx, &tab, &len, h, JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY) == 0) {
+ for (uint32_t i = 0; i < len; ++i) {
+ const char* key = JS_AtomToCString(ctx, tab[i].atom);
+ JSValue val = JS_GetProperty(ctx, h, tab[i].atom);
+ const char* vs = JS_ToCString(ctx, val);
+ if (key && vs) req.headers.emplace_back(key, vs);
+ if (vs) JS_FreeCString(ctx, vs);
+ if (key) JS_FreeCString(ctx, key);
+ JS_FreeValue(ctx, val);
+ }
+ JS_FreePropertyEnum(ctx, tab, len);
+ }
+ }
+ JS_FreeValue(ctx, h);
+}
+
+// es_fetch(request, callback): request = { url, method?, headers?, body?,
+// responseType? }. Runs the request off the main thread and calls back with
+// { ok, status, statusText, headers, arrayBuffer | text, error? }. The bridge
+// wraps this in a Promise. responseType 'text' returns a string; everything else
+// returns an ArrayBuffer (the bridge decodes text/json from it on demand).
+JSValue js_fetch(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {
+ if (argc < 2 || !JS_IsObject(argv[0]) || !JS_IsFunction(ctx, argv[1])) return JS_UNDEFINED;
+ eshost::FetchRequest req;
+ req.id = g_app->nextFetchId++;
+ req.url = fetchStrProp(ctx, argv[0], "url", "");
+ req.method = fetchStrProp(ctx, argv[0], "method", "GET");
+ req.wantText = fetchStrProp(ctx, argv[0], "responseType", "arraybuffer") == "text";
+ readFetchHeaders(ctx, argv[0], req);
+ JSValue body = JS_GetPropertyStr(ctx, argv[0], "body");
+ if (JS_IsString(body)) {
+ size_t len = 0;
+ if (const char* s = JS_ToCStringLen(ctx, &len, body)) {
+ req.body.assign(s, s + len);
+ JS_FreeCString(ctx, s);
+ }
+ } else if (!JS_IsUndefined(body) && !JS_IsNull(body)) {
+ readByteSource(ctx, body, req.body);
+ }
+ JS_FreeValue(ctx, body);
+
+ g_app->fetchCallbacks[req.id] = JS_DupValue(ctx, argv[1]);
+ if (req.url.empty()) {
+ eshost::FetchResult err;
+ err.id = req.id;
+ err.error = "es_fetch: missing url";
+ eshost::deliverFetch(std::move(err));
+ } else {
+ g_app->platform->startFetch(req);
+ }
+ return JS_UNDEFINED;
+}
+
+JSValue makeFetchResult(App& a, const eshost::FetchResult& r) {
+ JSValue o = JS_NewObject(a.js);
+ JS_SetPropertyStr(a.js, o, "ok", JS_NewBool(a.js, r.ok));
+ JS_SetPropertyStr(a.js, o, "status", JS_NewInt32(a.js, r.status));
+ JS_SetPropertyStr(a.js, o, "statusText", JS_NewString(a.js, r.statusText.c_str()));
+ if (!r.error.empty()) JS_SetPropertyStr(a.js, o, "error", JS_NewString(a.js, r.error.c_str()));
+ JSValue h = JS_NewObject(a.js);
+ for (const auto& kv : r.headers) {
+ JS_SetPropertyStr(a.js, h, kv.first.c_str(), JS_NewString(a.js, kv.second.c_str()));
+ }
+ JS_SetPropertyStr(a.js, o, "headers", h);
+ if (r.isText) {
+ JS_SetPropertyStr(a.js, o, "text",
+ JS_NewStringLen(a.js, reinterpret_cast<const char*>(r.body.data()), r.body.size()));
+ } else {
+ JS_SetPropertyStr(a.js, o, "arrayBuffer",
+ JS_NewArrayBufferCopy(a.js, r.body.data(), r.body.size()));
+ }
+ return o;
+}
+
+// Run the JS callbacks for HTTP replies that arrived since the last frame — JS
+// thread only. deliverFetch queued them (POD) from the completion thread.
+void drainFetches(App& a) {
+ std::queue<eshost::FetchResult> done;
+ { std::lock_guard<std::mutex> lk(g_fetchMutex); done.swap(g_fetchQueue); }
+ while (!done.empty()) {
+ const eshost::FetchResult r = std::move(done.front());
+ done.pop();
+ auto it = a.fetchCallbacks.find(r.id);
+ if (it == a.fetchCallbacks.end()) continue; // never happens, but stay safe
+ JSValue cb = it->second;
+ a.fetchCallbacks.erase(it);
+ JSValue arg = makeFetchResult(a, r);
+ JSValue ret = JS_Call(a.js, cb, JS_UNDEFINED, 1, &arg);
+ if (JS_IsException(ret)) logJsError(a.js, "es_fetch callback");
+ JS_FreeValue(a.js, ret);
+ JS_FreeValue(a.js, arg);
+ JS_FreeValue(a.js, cb);
+ }
+}
+
// Drain QuickJS's microtask queue. app.tick() is async: its synchronous prefix
// (finishPlugins, resource inserts) runs on call, but the systems run in jobs.
void pumpJobs(App& a) {
@@ -765,6 +890,7 @@ void initJS(App& a) {
bindGlobal(a, global, "es_utf8Decode", js_utf8Decode, 1);
bindGlobal(a, global, "es_readCacheFile", js_readCacheFile, 1);
bindGlobal(a, global, "es_writeCacheFile", js_writeCacheFile, 2);
+ bindGlobal(a, global, "es_fetch", js_fetch, 2);
// Entity + hierarchy (base Registry surface).
bindGlobal(a, global, "es_createEntity", js_createEntity, 0);
@@ -936,6 +1062,11 @@ void frame() {
JS_FreeValue(a.js, arg);
});
+ // Run the callbacks for any HTTP replies that landed since last frame, then
+ // let their .then() continuations run.
+ drainFetches(a);
+ pumpJs(a);
+
ctx.require<RenderContext>().setFrameTime((f32)a.frame / 60.0f, (u32)a.w, (u32)a.h);
World world{*a.registry, ctx.services(), 1.0f / 60.0f};
ctx.require<ecs::TransformSystem>().update(world);
@@ -992,4 +1123,11 @@ void memoryWarning() {
pumpJs(*g_app);
}
+// Thread-safe: the platform's HTTP completion (any thread) queues its reply here;
+// the frame loop drains it on the JS thread (drainFetches). No JS is touched here.
+void deliverFetch(FetchResult result) {
+ std::lock_guard<std::mutex> lk(g_fetchMutex);
+ g_fetchQueue.push(std::move(result));
+}
+
} // namespace eshost
diff --git a/native/host_js/host_core.hpp b/native/host_js/host_core.hpp
index 9ef3e28dd..143978e62 100644
--- a/native/host_js/host_core.hpp
+++ b/native/host_js/host_core.hpp
@@ -25,6 +25,7 @@
#pragma once
#include <string>
+#include <utility>
#include <vector>
#include "esengine/core/Types.hpp"
@@ -32,6 +33,30 @@
namespace eshost {
+/** One HTTP request the host performs off the main thread. `id` matches the
+ * reply back to its JS callback; `wantText` selects a string vs ArrayBuffer body. */
+struct FetchRequest {
+ int id = 0;
+ std::string method; ///< GET / POST / ...
+ std::string url;
+ std::vector<std::pair<std::string, std::string>> headers;
+ std::vector<esengine::u8> body;
+ bool wantText = false;
+};
+
+/** The reply the platform hands back via {@link deliverFetch}. A non-empty
+ * `error` rejects the JS promise; otherwise the body is delivered per `isText`. */
+struct FetchResult {
+ int id = 0;
+ bool ok = false;
+ int status = 0;
+ std::string statusText;
+ std::vector<std::pair<std::string, std::string>> headers;
+ std::vector<esengine::u8> body;
+ bool isText = false;
+ std::string error;
+};
+
/**
* @brief The platform seam: what the host needs that Android and iOS answer
* differently. The glue implements it; host_core owns everything else.
@@ -54,8 +79,19 @@ struct Platform {
virtual void surfaceSize(esengine::u32& width, esengine::u32& height) = 0;
virtual void log(bool error, const char* message) = 0;
+
+ /** Perform an HTTP request off the main thread (NSURLSession / a JNI
+ * HttpURLConnection), then hand the reply back through {@link deliverFetch}
+ * with the same `req.id`. The OS owns the TLS stack, so this is where native
+ * networking necessarily differs between iOS and Android. */
+ virtual void startFetch(const FetchRequest& req) = 0;
};
+/** Deliver an HTTP reply for a {@link Platform::startFetch}. Thread-safe: the
+ * platform calls it from whatever thread its completion runs on; the result is
+ * queued and the JS callback runs on the next frame, on the JS thread. */
+void deliverFetch(FetchResult result);
+
/** @brief Boots Dawn, EstellaContext, QuickJS, the SDK bundle and game.js. Call
* once, when a window first exists; @p platform must outlive the host.
* @return false if any stage failed (the reason is already logged). */
diff --git a/native/host_js/main_android.cpp b/native/host_js/main_android.cpp
index 85050fdd2..27a742e3a 100644
--- a/native/host_js/main_android.cpp
+++ b/native/host_js/main_android.cpp
@@ -18,6 +18,9 @@
#include <android/input.h>
#include <android/asset_manager.h>
#include <android/native_window.h>
+#include <jni.h>
+
+#include <thread>
#include "host_core.hpp"
@@ -29,9 +32,111 @@ using esengine::WebGPUDevice;
namespace {
+// Read a java.io.InputStream fully into `out`, reusing one byte[] buffer.
+void jniReadStream(JNIEnv* env, jobject stream, std::vector<u8>& out) {
+ if (!stream) return;
+ jclass isCls = env->GetObjectClass(stream);
+ jmethodID readM = env->GetMethodID(isCls, "read", "([B)I");
+ jbyteArray buf = env->NewByteArray(16384);
+ while (true) {
+ jint n = env->CallIntMethod(stream, readM, buf);
+ if (env->ExceptionCheck()) { env->ExceptionClear(); break; }
+ if (n <= 0) break;
+ jbyte* elems = env->GetByteArrayElements(buf, nullptr);
+ out.insert(out.end(), reinterpret_cast<u8*>(elems), reinterpret_cast<u8*>(elems) + n);
+ env->ReleaseByteArrayElements(buf, elems, JNI_ABORT);
+ }
+ jmethodID closeM = env->GetMethodID(isCls, "close", "()V");
+ env->CallVoidMethod(stream, closeM);
+ if (env->ExceptionCheck()) env->ExceptionClear();
+ env->DeleteLocalRef(buf);
+ env->DeleteLocalRef(isCls);
+}
+
+// Perform one HTTP request through java.net.HttpURLConnection (the OS owns TLS).
+// Runs on a JNI-attached background thread; fills `r`.
+void performHttp(JNIEnv* env, const eshost::FetchRequest& req, eshost::FetchResult& r) {
+ jclass urlCls = env->FindClass("java/net/URL");
+ jstring jurl = env->NewStringUTF(req.url.c_str());
+ jobject urlObj = env->NewObject(urlCls, env->GetMethodID(urlCls, "<init>", "(Ljava/lang/String;)V"), jurl);
+ env->DeleteLocalRef(jurl);
+ if (env->ExceptionCheck() || !urlObj) { env->ExceptionClear(); r.error = "invalid url"; env->DeleteLocalRef(urlCls); return; }
+
+ jobject conn = env->CallObjectMethod(urlObj, env->GetMethodID(urlCls, "openConnection", "()Ljava/net/URLConnection;"));
+ env->DeleteLocalRef(urlObj);
+ env->DeleteLocalRef(urlCls);
+ if (env->ExceptionCheck() || !conn) { env->ExceptionClear(); r.error = "openConnection failed"; return; }
+
+ jclass httpCls = env->FindClass("java/net/HttpURLConnection");
+ jstring jmethod = env->NewStringUTF(req.method.c_str());
+ env->CallVoidMethod(conn, env->GetMethodID(httpCls, "setRequestMethod", "(Ljava/lang/String;)V"), jmethod);
+ env->DeleteLocalRef(jmethod);
+ if (env->ExceptionCheck()) env->ExceptionClear();
+
+ jmethodID setPropM = env->GetMethodID(httpCls, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
+ for (const auto& kv : req.headers) {
+ jstring k = env->NewStringUTF(kv.first.c_str());
+ jstring v = env->NewStringUTF(kv.second.c_str());
+ env->CallVoidMethod(conn, setPropM, k, v);
+ env->DeleteLocalRef(k);
+ env->DeleteLocalRef(v);
+ }
+ if (env->ExceptionCheck()) env->ExceptionClear();
+
+ if (!req.body.empty()) {
+ env->CallVoidMethod(conn, env->GetMethodID(httpCls, "setDoOutput", "(Z)V"), JNI_TRUE);
+ jobject os = env->CallObjectMethod(conn, env->GetMethodID(httpCls, "getOutputStream", "()Ljava/io/OutputStream;"));
+ if (!env->ExceptionCheck() && os) {
+ jbyteArray b = env->NewByteArray(static_cast<jsize>(req.body.size()));
+ env->SetByteArrayRegion(b, 0, static_cast<jsize>(req.body.size()), reinterpret_cast<const jbyte*>(req.body.data()));
+ jclass osCls = env->GetObjectClass(os);
+ env->CallVoidMethod(os, env->GetMethodID(osCls, "write", "([B)V"), b);
+ env->CallVoidMethod(os, env->GetMethodID(osCls, "close", "()V"));
+ env->DeleteLocalRef(b);
+ env->DeleteLocalRef(osCls);
+ env->DeleteLocalRef(os);
+ }
+ if (env->ExceptionCheck()) env->ExceptionClear();
+ }
+
+ jint code = env->CallIntMethod(conn, env->GetMethodID(httpCls, "getResponseCode", "()I"));
+ if (env->ExceptionCheck()) { env->ExceptionClear(); r.error = "no response"; env->DeleteLocalRef(httpCls); env->DeleteLocalRef(conn); return; }
+ r.status = static_cast<int>(code);
+ r.ok = code >= 200 && code < 300;
+
+ jmethodID keyM = env->GetMethodID(httpCls, "getHeaderFieldKey", "(I)Ljava/lang/String;");
+ jmethodID valM = env->GetMethodID(httpCls, "getHeaderField", "(I)Ljava/lang/String;");
+ for (int i = 0; i < 64; ++i) {
+ jstring k = static_cast<jstring>(env->CallObjectMethod(conn, keyM, i));
+ jstring v = static_cast<jstring>(env->CallObjectMethod(conn, valM, i));
+ if (!k && !v) { break; }
+ if (k && v) {
+ const char* kc = env->GetStringUTFChars(k, nullptr);
+ const char* vc = env->GetStringUTFChars(v, nullptr);
+ r.headers.emplace_back(kc ? kc : "", vc ? vc : "");
+ if (kc) env->ReleaseStringUTFChars(k, kc);
+ if (vc) env->ReleaseStringUTFChars(v, vc);
+ }
+ if (k) env->DeleteLocalRef(k);
+ if (v) env->DeleteLocalRef(v);
+ }
+
+ jobject stream = env->CallObjectMethod(conn, env->GetMethodID(httpCls,
+ r.ok ? "getInputStream" : "getErrorStream", "()Ljava/io/InputStream;"));
+ if (env->ExceptionCheck()) { env->ExceptionClear(); stream = nullptr; }
+ jniReadStream(env, stream, r.body);
+ if (stream) env->DeleteLocalRef(stream);
+
+ env->CallVoidMethod(conn, env->GetMethodID(httpCls, "disconnect", "()V"));
+ if (env->ExceptionCheck()) env->ExceptionClear();
+ env->DeleteLocalRef(httpCls);
+ env->DeleteLocalRef(conn);
+}
+
struct AndroidPlatform final : eshost::Platform {
AAssetManager* assets = nullptr; // APK assets/ — the game + its content
ANativeWindow* window = nullptr;
+ JavaVM* vm = nullptr; // for JNI HttpURLConnection off-thread
std::string cache; // app private dir — SDK bytecode cache
// Read an APK asset (assets/<path>) fully into a buffer; empty if missing.
@@ -65,6 +170,30 @@ struct AndroidPlatform final : eshost::Platform {
void log(bool error, const char* message) override {
__android_log_print(error ? ANDROID_LOG_ERROR : ANDROID_LOG_INFO, LOG_TAG, "%s", message);
}
+
+ // A detached JNI thread runs the request; deliverFetch is thread-safe and the
+ // JS callback runs back on the main thread in drainFetches.
+ void startFetch(const eshost::FetchRequest& req) override {
+ JavaVM* jvm = vm;
+ if (!jvm) {
+ eshost::FetchResult r; r.id = req.id; r.isText = req.wantText; r.error = "no JavaVM";
+ eshost::deliverFetch(std::move(r));
+ return;
+ }
+ std::thread([jvm, req]() {
+ eshost::FetchResult r;
+ r.id = req.id;
+ r.isText = req.wantText;
+ JNIEnv* env = nullptr;
+ if (jvm->AttachCurrentThread(&env, nullptr) == JNI_OK && env) {
+ performHttp(env, req, r);
+ jvm->DetachCurrentThread();
+ } else {
+ r.error = "jni attach failed";
+ }
+ eshost::deliverFetch(std::move(r));
+ }).detach();
+ }
};
AndroidPlatform g_platform;
@@ -121,6 +250,7 @@ void onAppCmd(android_app* app, int32_t cmd) {
void android_main(android_app* app) {
g_platform.assets = app->activity->assetManager; // APK assets/ (game.js + content)
+ g_platform.vm = app->activity->vm; // for JNI HttpURLConnection (es_fetch)
if (app->activity->internalDataPath) g_platform.cache = app->activity->internalDataPath;
app->onAppCmd = onAppCmd;
app->onInputEvent = onInput;
diff --git a/native/host_js/main_ios.mm b/native/host_js/main_ios.mm
index 6091c182c..2991ce6ff 100644
--- a/native/host_js/main_ios.mm
+++ b/native/host_js/main_ios.mm
@@ -74,6 +74,55 @@ struct IOSPlatform final : eshost::Platform {
void log(bool error, const char* message) override {
NSLog(@"[Estella]%s %s", error ? " ERROR:" : "", message);
}
+
+ // NSURLSession runs the request (TLS via the OS) on a background queue and
+ // calls its completion there; deliverFetch is thread-safe and the JS callback
+ // runs back on the main thread in drainFetches.
+ void startFetch(const eshost::FetchRequest& req) override {
+ NSURL* url = [NSURL URLWithString:[NSString stringWithUTF8String:req.url.c_str()]];
+ if (!url) {
+ eshost::FetchResult r; r.id = req.id; r.error = "invalid url";
+ eshost::deliverFetch(std::move(r));
+ return;
+ }
+ NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
+ request.HTTPMethod = [NSString stringWithUTF8String:req.method.c_str()];
+ for (const auto& kv : req.headers) {
+ [request setValue:[NSString stringWithUTF8String:kv.second.c_str()]
+ forHTTPHeaderField:[NSString stringWithUTF8String:kv.first.c_str()]];
+ }
+ if (!req.body.empty()) {
+ request.HTTPBody = [NSData dataWithBytes:req.body.data() length:req.body.size()];
+ }
+ const int id = req.id;
+ const bool wantText = req.wantText;
+ NSURLSessionDataTask* task = [NSURLSession.sharedSession dataTaskWithRequest:request
+ completionHandler:^(NSData* data, NSURLResponse* response, NSError* error) {
+ eshost::FetchResult r;
+ r.id = id;
+ r.isText = wantText;
+ if (error) {
+ r.error = error.localizedDescription.UTF8String ?: "network error";
+ eshost::deliverFetch(std::move(r));
+ return;
+ }
+ NSHTTPURLResponse* http = [response isKindOfClass:NSHTTPURLResponse.class]
+ ? (NSHTTPURLResponse*)response : nil;
+ r.status = http ? (int)http.statusCode : 200;
+ r.ok = r.status >= 200 && r.status < 300;
+ r.statusText = [NSHTTPURLResponse localizedStringForStatusCode:r.status].UTF8String ?: "";
+ for (NSString* key in http.allHeaderFields) {
+ NSString* val = [http.allHeaderFields[key] description];
+ r.headers.emplace_back(key.UTF8String, val.UTF8String ?: "");
+ }
+ if (data.length) {
+ const u8* bytes = (const u8*)data.bytes;
+ r.body.assign(bytes, bytes + data.length);
+ }
+ eshost::deliverFetch(std::move(r));
+ }];
+ [task resume];
+ }
};
IOSPlatform g_platform;
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index d3bcea87f..c3ea06c86 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -4009,6 +4009,7 @@ es_audioSuspendAll: (() => void) | undefined
es_audioUnload: ((bufferId: number) => void) | undefined
es_audioVoiceState: ((voiceId: number) => { playing: boolean; currentTime: number; } | null) | undefined
es_devicePixelRatio: (() => number) | undefined
+es_fetch: ((request: { url: string; method?: string; headers?: Record<string, string>; body?: string | ArrayBuffer; responseType?: string; }, callback: (result: { ok: boolean; status: number; statusText: string; headers: Record<string, string>; arrayBuffer?: ArrayBuffer; text?: string; error?: string; }) => void) => void) | undefined
es_getStorageItem: ((key: string) => string | null) | undefined
es_loadImagePixels: (path: string) => { width: number; height: number; pixels: ArrayBuffer; } | null
es_readAsset: (path: string) => ArrayBuffer | null
diff --git a/sdk/src/platform/native/hostBridge.ts b/sdk/src/platform/native/hostBridge.ts
index 60c0a9485..86f7ef242 100644
--- a/sdk/src/platform/native/hostBridge.ts
+++ b/sdk/src/platform/native/hostBridge.ts
@@ -13,7 +13,8 @@
*/
import { log } from '../../logger';
-import type { NativeAudioBridge, NativeBridge, NativeInputListener } from './bridge';
+import type { NativeAudioBridge, NativeBridge, NativeFetchResult, NativeInputListener } from './bridge';
+import type { PlatformRequestOptions } from '../types';
import { assertHostEnvironment } from './hostEnvironment';
import { hasAudioBindings } from '../../ecs/nativeBindings';
@@ -41,6 +42,28 @@ export interface NativeHostBindings {
/** Screen scale (1 when the host reports surface pixels directly). */
es_devicePixelRatio?(): number;
+ /** Perform an HTTP request off the main thread (native TLS stack), calling
+ * back with the reply. Optional — a host without it stays offline (remote
+ * asset groups and hot-update do not resolve). */
+ es_fetch?(
+ request: {
+ url: string;
+ method?: string;
+ headers?: Record<string, string>;
+ body?: string | ArrayBuffer;
+ responseType?: string;
+ },
+ callback: (result: {
+ ok: boolean;
+ status: number;
+ statusText: string;
+ headers: Record<string, string>;
+ arrayBuffer?: ArrayBuffer;
+ text?: string;
+ error?: string;
+ }) => void,
+ ): void;
+
/** The native audio engine, all-or-nothing (see {@link AUDIO_BINDINGS}). A
* host without a sound device binds none and stays silent. */
es_audioLoad?(bytes: ArrayBuffer): { id: number; duration: number; bytes: number } | null;
@@ -98,9 +121,7 @@ export function createHostBridge(
return bytes ? Promise.resolve(bytes) : Promise.reject(new Error(`asset not found: ${path}`));
},
fileExists: (path) => Promise.resolve(bindings.es_readAsset(path) != null),
- // Networking is the shell's to add (NSURLSession / OkHttp); until then a
- // packaged game is offline and remote groups simply do not resolve.
- fetch: () => Promise.resolve({ ok: false, status: 404 }),
+ fetch: (url, options) => hostFetch(bindings, url, options),
loadImagePixels: (path) => {
const decoded = bindings.es_loadImagePixels(path);
return decoded
@@ -131,6 +152,44 @@ export function createHostBridge(
};
}
+/**
+ * Perform an HTTP request through the host's native stack (es_fetch), wrapping
+ * its callback in the Promise the adapter expects. A host without es_fetch is
+ * offline — a 404, exactly as before, so remote groups just fail to resolve.
+ */
+function hostFetch(
+ bindings: NativeHostBindings, url: string, options?: PlatformRequestOptions,
+): Promise<NativeFetchResult> {
+ if (typeof bindings.es_fetch !== 'function') {
+ return Promise.resolve({ ok: false, status: 404, statusText: 'no network' });
+ }
+ return new Promise((resolve, reject) => {
+ bindings.es_fetch!(
+ {
+ url,
+ method: options?.method,
+ headers: options?.headers,
+ body: options?.body,
+ responseType: options?.responseType,
+ },
+ (r) => {
+ if (r.error) {
+ reject(new Error(r.error));
+ return;
+ }
+ resolve({
+ ok: r.ok,
+ status: r.status,
+ statusText: r.statusText,
+ headers: r.headers,
+ arrayBuffer: r.arrayBuffer,
+ text: r.text,
+ });
+ },
+ );
+ });
+}
+
/**
* Assemble the audio bridge from the host's es_audio* primitives, or undefined
* when the host bound none (→ silent Null backend). Also installs
diff --git a/sdk/tests/native-host-bridge.test.ts b/sdk/tests/native-host-bridge.test.ts
index 4c1da1dff..3cc33b65e 100644
--- a/sdk/tests/native-host-bridge.test.ts
+++ b/sdk/tests/native-host-bridge.test.ts
@@ -110,6 +110,37 @@ describe('createHostBridge', () => {
});
});
+describe('createHostBridge — fetch', () => {
+ it('is offline (404) when the host bound no es_fetch', async () => {
+ const res = await createHostBridge(hostScope()).fetch('https://x/y');
+ expect(res.ok).toBe(false);
+ expect(res.status).toBe(404);
+ });
+
+ it('wraps es_fetch, passing the request and resolving its reply', async () => {
+ let seen: unknown;
+ const scope = hostScope({
+ es_fetch: (request: unknown, cb: (r: unknown) => void) => {
+ seen = request;
+ cb({ ok: true, status: 200, statusText: 'OK', headers: { etag: 'a' },
+ arrayBuffer: new ArrayBuffer(8) });
+ },
+ });
+ const res = await createHostBridge(scope).fetch('https://cdn/asset.ktx2', { method: 'GET' });
+ expect(seen).toMatchObject({ url: 'https://cdn/asset.ktx2', method: 'GET' });
+ expect(res).toMatchObject({ ok: true, status: 200, headers: { etag: 'a' } });
+ expect(res.arrayBuffer!.byteLength).toBe(8);
+ });
+
+ it('rejects when the host reports an error', async () => {
+ const scope = hostScope({
+ es_fetch: (_request: unknown, cb: (r: unknown) => void) =>
+ cb({ ok: false, status: 0, statusText: '', headers: {}, error: 'timeout' }),
+ });
+ await expect(createHostBridge(scope).fetch('https://x')).rejects.toThrow(/timeout/);
+ });
+});
+
describe('assertNativeHost', () => {
/** Everything a complete shell binds. */
function fullHost(): Record<string, unknown> {