@file:OptIn(ExperimentalCoroutinesApi::class) package eu.friedcutlet.yokan.services.extensions.js import app.cash.zipline.EngineApi import app.cash.zipline.InterruptHandler import app.cash.zipline.QuickJs import app.cash.zipline.Zipline import app.cash.zipline.ZiplineService import kotlinx.coroutines.CloseableCoroutineDispatcher import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlin.time.Duration import kotlin.time.Duration.Companion.seconds import kotlin.time.TimeSource private const val BridgeServiceName = "yokanJavaScriptBridge" private const val BridgeSendMessageFunctionId = "YhSjgGyh" private const val QuickJsMemoryLimitBytes = 128L * 1024L * 1024L /** * The QuickJS stack cap. JVM/Android get 8 MiB (~9,000 recursion levels); iOS needs far more for the * same depth because zipline's native QuickJS is compiled unoptimized (~22 KiB per JS call). */ internal expect val QuickJsMaxStackSizeBytes: Long // Headroom above the JS cap for the host bridge frames (HTTP, WebView, extractors) that run on top // of the deepest JS frame, as zipline recommends (6 MiB cap on 8 MiB threads). private val QuickJsThreadStackBytes = QuickJsMaxStackSizeBytes + 2L * 1024L * 1024L private val QuickJsEvaluationTimeout = 30.seconds // Creating and closing a runtime touch process-global state: QuickJS's JS_NewClassID bumps an // unsynchronized counter during creation, and zipline's leak tracking adds/removes each runtime in // one unsynchronized map. Evaluation only touches the engine's own runtime, so it runs in parallel. private val QuickJsGlobalState = Mutex() /** * A dedicated thread with a [stackBytes] native stack for one engine. QuickJS measures its stack * limit from the thread that created the runtime, so every native call of an engine must run on * that same real thread, and the thread must actually own the stack the limit allows. */ internal expect fun quickJsDispatcher(stackBytes: Long): CloseableCoroutineDispatcher private interface YokanJavaScriptBridge : ZiplineService { fun sendMessage(channel: String, payload: String): String } /** * QuickJS-backed JavaScript runtime shared by Android, desktop, and iOS. * * QuickJS is not thread-safe, so each engine creates its runtime, evaluates, and closes on its own * [quickJsDispatcher] thread. The explicit [QuickJsMaxStackSizeBytes] cap supports the large * generated parsers used by Aniyomi ports without leaving it unbounded. */ @OptIn(EngineApi::class) internal class QuickJsJavaScriptEngine( bridge: JavaScriptMessageBridge, private val evaluationTimeout: Duration = QuickJsEvaluationTimeout, ) : JavaScriptEngine { // Host bridge calls (HTTP) block this thread until they return. private val dispatcher = quickJsDispatcher(QuickJsThreadStackBytes) private val zipline = try { runBlocking(dispatcher) { val runtime = QuickJsGlobalState.withLock { Zipline.create(dispatcher) } try { runtime.bind( BridgeServiceName, object : YokanJavaScriptBridge { override fun sendMessage(channel: String, payload: String): String = bridge.sendMessage(channel, payload) }, ) runtime.quickJs.memoryLimit = QuickJsMemoryLimitBytes runtime.quickJs.maxStackSize = QuickJsMaxStackSizeBytes runtime.quickJs.evaluate(BridgeBootstrap, "yokan-bridge.js") runtime } catch (error: Throwable) { QuickJsGlobalState.withLock { runtime.close() } throw error } } } catch (error: Throwable) { dispatcher.close() throw error } private val quickJs: QuickJs = zipline.quickJs private var closed = false override fun evaluate(script: String, isCancelled: () -> Boolean): String = runBlocking(dispatcher) { check(!closed) { "JavaScript engine is closed." } val startedAt = TimeSource.Monotonic.markNow() quickJs.interruptHandler = InterruptHandler { isCancelled() || startedAt.elapsedNow() >= evaluationTimeout } try { quickJs.evaluate(script, "yokan-extension.js")?.toString().orEmpty() } finally { quickJs.interruptHandler = null } } // Fire-and-forget on the engine's own thread so disposing a runtime never blocks its caller // (possibly Main); the thread runs it after any in-flight call, then exits. @OptIn(DelicateCoroutinesApi::class) override fun close() { GlobalScope.launch(dispatcher) { if (closed) return@launch closed = true try { QuickJsGlobalState.withLock { zipline.close() } } finally { dispatcher.close() } } } private companion object { val BridgeBootstrap = """ globalThis.__bridge = { sendMessage: function(channel, payload) { var call = JSON.stringify({ service: "$BridgeServiceName", function: "$BridgeSendMessageFunctionId", args: [String(channel), String(payload)] }); var result = JSON.parse(globalThis.app_cash_zipline_outboundChannel.call(call)); if (Object.prototype.hasOwnProperty.call(result, "failure")) { var failure = result.failure || {}; throw new Error(failure.message || failure.stacktraceString || "Host bridge call failed"); } return result.success; } }; """.trimIndent() } }