# 08 — Reimplement the yokan-ext submodule

Pinned commit: `67788fa29ae61f053beeaf3284a638cc0bbbe561`. [Every submodule file](../reference/08-files.md). This is a separate KMP library, not a collection of catalog source scripts.

[chapter-content-start]: #
## How to write this chapter

Recreate yokan-ext as an independent library with the original extension ABI, Android RPC host, desktop process lifecycle and iOS bridge. The main app consumes its public ExtensionServer contract.

The 93 assigned entries are integrated below at their implementation steps. Every text listing is complete, including imports, helpers and tests. Create the displayed paths in your new project; dependencies imported from other chapters are linked beside the file. Binary assets have direct downloads.

Read each step’s explanation, write its contracts and implementation, then trace the test assertions. The final application graph has dependencies across chapters: the ordering is a construction plan, and a step is not a promise that the whole app compiles before its referenced contracts exist.

Implementation sequence:

- Step 1: Create the library build and shared server/release contracts.
- Step 2: Write the exact Tachiyomi/anime ABI and networking compatibility helpers.
- Step 3: Load Android classes and expose them through structured RPC.
- Step 4: Install verified desktop bundles and own the server subprocess.
- Step 5: Connect iOS headers, installation and embedded-runtime lifecycle.
- Verification: recreate the full test/fixture listings and run the relevant target tasks.
[chapter-content-end]: #


## Step 1: create the independent library build

Recreate root settings/wrapper/build files, common, Android, desktop, iOS and Wasm targets and C interop headers. Inspect actual Gradle pins rather than the outdated short README. The group/artifact used by the main build is `eu.friedcutlet.yokan:yokan-ext:0.1.0-SNAPSHOT`. Android needs the existing RxJava 1, Injekt, OkHttp, Jsoup, NanoHTTPD and Jackson compatibility dependencies.

Define `ExtensionServer`, `ExtensionServerConfig`, `ExtensionServerStatus`, phase enum and exception. Port must be in 1..65535; default local base URL is loopback. Start/stop are suspend operations with observable status and deterministic failure transitions. Build release/bundle selection models next.

[chapter-content-start]: #
### Follow the code

Recreate the independent settings/build before connecting dependency substitution from the main app. The shared server interface exposes lifecycle/status without assuming a local Android host, desktop JVM or embedded iOS runtime. Release/bundle models select the correct external payload. Preserve the group/artifact and public package names so the main build resolves the reconstructed library instead of a published binary.

Write these files in this order:

- `vendor/yokan-ext/src/commonMain/kotlin/eu/friedcutlet/yokan/ext/ExtensionServer.kt`
- `vendor/yokan-ext/src/commonMain/kotlin/eu/friedcutlet/yokan/ext/ExtensionServerRelease.kt`
- `vendor/yokan-ext/.gitignore`
- `vendor/yokan-ext/LICENSE-APACHE-MIHON`
- `vendor/yokan-ext/README.md`
- `vendor/yokan-ext/build.gradle.kts`
- `vendor/yokan-ext/gradle.properties`
- `vendor/yokan-ext/gradle/wrapper/gradle-wrapper.jar`
- `vendor/yokan-ext/gradle/wrapper/gradle-wrapper.properties`
- `vendor/yokan-ext/gradlew`
- `vendor/yokan-ext/gradlew.bat`
- `vendor/yokan-ext/settings.gradle.kts`

[chapter-file-start]: #vendor/yokan-ext/src/commonMain/kotlin/eu/friedcutlet/yokan/ext/ExtensionServer.kt
### Write `vendor/yokan-ext/src/commonMain/kotlin/eu/friedcutlet/yokan/ext/ExtensionServer.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/commonMain/kotlin/eu/friedcutlet/yokan/ext/ExtensionServer.kt).

The common API is the stable connection point for the main app. Keep configuration validation and status transitions independent of any specific platform host.

The implementation below defines `ExtensionServer`, `start`, `stop`, `ExtensionServerConfig`, `ExtensionServerPhase`, `ExtensionServerStatus`, `ExtensionServerException`.

The source describes its contract as:

> Lifecycle shared by the embedded Android bridge and JVM-backed desktop/iOS servers.

```kotlin
package eu.friedcutlet.yokan.ext

import kotlinx.coroutines.flow.StateFlow

/** Lifecycle shared by the embedded Android bridge and JVM-backed desktop/iOS servers. */
interface ExtensionServer {
    val status: StateFlow<ExtensionServerStatus>

    suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus

    suspend fun stop(): ExtensionServerStatus
}

data class ExtensionServerConfig(
    val port: Int,
    val jvmPath: String? = null,
    val serverJarPath: String? = null,
) {
    init {
        require(port in 1..65535) { "Port must be between 1 and 65535" }
    }

    val baseUrl: String get() = "http://127.0.0.1:$port"
}

enum class ExtensionServerPhase {
    Stopped,
    Starting,
    Running,
    Stopping,
    Failed,
}

data class ExtensionServerStatus(
    val phase: ExtensionServerPhase,
    val port: Int? = null,
    val message: String = "",
) {
    val isRunning: Boolean get() = phase == ExtensionServerPhase.Running
    val baseUrl: String? get() = port?.let { "http://127.0.0.1:$it" }

    companion object {
        val Stopped = ExtensionServerStatus(ExtensionServerPhase.Stopped)
    }
}

class ExtensionServerException(
    val code: String,
    message: String,
    cause: Throwable? = null,
) : IllegalStateException(message, cause)
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/commonMain/kotlin/eu/friedcutlet/yokan/ext/ExtensionServerRelease.kt
### Write `vendor/yokan-ext/src/commonMain/kotlin/eu/friedcutlet/yokan/ext/ExtensionServerRelease.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/commonMain/kotlin/eu/friedcutlet/yokan/ext/ExtensionServerRelease.kt).

Bundle selection is a protocol/build contract. Keep host architecture, version and archive paths paired rather than deriving a plausible filename independently.

The implementation below defines `ExtensionServerRelease`, `ExtensionServerReleaseAsset`, `InstalledExtensionServerBundle`, `ExtensionServerHostOs`, `ExtensionServerHostArch`, `ExtensionServerHost`, `parseExtensionServerRelease`, `ExtensionServerRelease.selectBundle`, `ExtensionServerRelease.trustedSha256`, `unsupported` and 2 further declarations.

```kotlin
package eu.friedcutlet.yokan.ext

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

const val ExtensionServerLatestReleaseUrl =
    "https://api.github.com/repos/kodjodevf/M-Extension-Server/releases/latest"

@Serializable
data class ExtensionServerRelease(
    val version: String,
    val assets: List<ExtensionServerReleaseAsset>,
)

@Serializable
data class ExtensionServerReleaseAsset(
    val name: String,
    val downloadUrl: String,
    val size: Long,
    val sha256: String?,
)

data class InstalledExtensionServerBundle(
    val version: String,
    val rootPath: String,
    val jvmPath: String,
    val serverJarPath: String,
)

enum class ExtensionServerHostOs { Windows, MacOs, Linux, Ios }
enum class ExtensionServerHostArch { X64, Arm64 }

data class ExtensionServerHost(
    val os: ExtensionServerHostOs,
    val arch: ExtensionServerHostArch,
)

fun parseExtensionServerRelease(json: String): ExtensionServerRelease {
    val payload = releaseJson.decodeFromString<GitHubReleasePayload>(json)
    val version = payload.tagName.ifBlank { payload.name.orEmpty() }.removePrefix("v")
    require(version.isNotBlank()) { "GitHub release has no version" }
    return ExtensionServerRelease(
        version = version,
        assets = payload.assets.map { asset ->
            ExtensionServerReleaseAsset(
                name = asset.name,
                downloadUrl = asset.browserDownloadUrl,
                size = asset.size,
                sha256 = asset.digest?.removePrefix("sha256:")?.lowercase()?.takeIf { it.length == 64 },
            )
        },
    )
}

fun ExtensionServerRelease.selectBundle(host: ExtensionServerHost): ExtensionServerReleaseAsset {
    val expected = when (host.os) {
        ExtensionServerHostOs.Windows -> when (host.arch) {
            ExtensionServerHostArch.X64 -> "windows-x64-bundle.zip"
            ExtensionServerHostArch.Arm64 -> unsupported(host)
        }
        ExtensionServerHostOs.MacOs -> when (host.arch) {
            ExtensionServerHostArch.X64 -> "macOS-x64-bundle.zip"
            ExtensionServerHostArch.Arm64 -> "macOS-arm64-bundle.zip"
        }
        ExtensionServerHostOs.Linux -> when (host.arch) {
            ExtensionServerHostArch.X64 -> "linux-x64-bundle.zip"
            ExtensionServerHostArch.Arm64 -> unsupported(host)
        }
        // The upstream server has no iOS build. Sideloaded iOS embeds its own
        // signed runtime and uses the architecture-independent JAR from this bundle.
        ExtensionServerHostOs.Ios -> "macOS-arm64-bundle.zip"
    }
    return assets.firstOrNull { it.name.equals(expected, ignoreCase = true) }
        ?: throw ExtensionServerException("ASSET_MISSING", "Release $version has no $expected asset")
}

fun ExtensionServerRelease.trustedSha256(asset: ExtensionServerReleaseAsset): String {
    val key = "${version.removePrefix("v")}/${asset.name.lowercase()}"
    return trustedExtensionServerDigests[key]
        ?: throw ExtensionServerException(
            "UNTRUSTED_RELEASE",
            "Extension server ${version}/${asset.name} is not trusted by this Yokan build; update Yokan before installing it",
        )
}

private val trustedExtensionServerDigests = mapOf(
    "1.0.4/linux-x64-bundle.zip" to "cb0076ebab3dd3cd42c7fcb0f15f8b34655cade7f6f3d5e547c3ea015dd491a8",
    "1.0.4/macos-arm64-bundle.zip" to "30a3f039b213c9e1075572e6e2d3eba533888f6b393ba8633a0128e43187c326",
    "1.0.4/macos-x64-bundle.zip" to "5fd0c4bb91ecd3fbdbd0f5d2145aa2cfe8162633be5dfa597a6791e5120d2be4",
    "1.0.4/windows-x64-bundle.zip" to "4bdd8e068914a769b4ff132080210d2a8be806e9c401a577dd700cb662a302ee",
    "1.0.5/linux-x64-bundle.zip" to "1e46a75576776c8c71ff83326238bea779fcfd1f31626557d291c141310b96fe",
    "1.0.5/macos-arm64-bundle.zip" to "2fc07c86d1d9598bb8e15835bfd1b39db5948c2048c83e05f2d1171f267eeb5f",
    "1.0.5/macos-x64-bundle.zip" to "32319f151b9a9ebae418b2df175c656746e32c8fc04efade40bf41094c83d398",
    "1.0.5/windows-x64-bundle.zip" to "dd00a09b4fc23db23ab1a1f629e2d1d363f1bb67cd34c48e8505d82b2417b210",
)

private fun unsupported(host: ExtensionServerHost): Nothing = throw ExtensionServerException(
    "UNSUPPORTED_PLATFORM",
    "No extension server bundle is published for ${host.os}/${host.arch}",
)

private val releaseJson = Json { ignoreUnknownKeys = true }

@Serializable
private data class GitHubReleasePayload(
    @SerialName("tag_name") val tagName: String = "",
    val name: String? = null,
    val assets: List<GitHubReleaseAssetPayload> = emptyList(),
)

@Serializable
private data class GitHubReleaseAssetPayload(
    val name: String,
    @SerialName("browser_download_url") val browserDownloadUrl: String,
    val size: Long = 0,
    val digest: String? = null,
)
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/.gitignore
### Write `vendor/yokan-ext/.gitignore`

Create this path in your reconstruction project. Source set: **build / host / supporting material**. [Exact file download](../reference/source/vendor/yokan-ext/.gitignore).

```text
build
.gradle
local.properties
.kotlin
.project
.classpath
.settings/
.idea/
*.iml
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/LICENSE-APACHE-MIHON
### Write `vendor/yokan-ext/LICENSE-APACHE-MIHON`

Create this path in your reconstruction project. Source set: **build / host / supporting material**. [Exact file download](../reference/source/vendor/yokan-ext/LICENSE-APACHE-MIHON).

```text
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/README.md
### Write `vendor/yokan-ext/README.md`

Create this path in your reconstruction project. Source set: **build / host / supporting material**. [Exact file download](../reference/source/vendor/yokan-ext/README.md).

````markdown
# yokan-ext

Kotlin Multiplatform extension server library.

## Prerequisites

- JDK 17
- Android SDK Platform 36

Gradle is pinned to 8.13 by the checked-in wrapper.

## Build and test

If Gradle cannot find the Android SDK automatically, copy
`local.properties.example` to `local.properties` and set `sdk.dir` to the
SDK location.

Run the supported local checks:

```sh
./gradlew desktopTest assembleRelease
```

The same command is run in GitHub Actions.
````
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/build.gradle.kts
### Write `vendor/yokan-ext/build.gradle.kts`

Create this path in your reconstruction project. Source set: **build / host / supporting material**. [Exact file download](../reference/source/vendor/yokan-ext/build.gradle.kts).

```kotlin
import org.jetbrains.kotlin.gradle.dsl.JvmTarget

plugins {
    kotlin("multiplatform") version "2.4.21"
    kotlin("plugin.serialization") version "2.4.21"
    id("com.android.kotlin.multiplatform.library") version "9.4.1"
}

group = "eu.friedcutlet.yokan"
version = "0.1.0-SNAPSHOT"

kotlin {
    compilerOptions {
        freeCompilerArgs.add("-Xexpect-actual-classes")
    }

    android {
        namespace = "eu.friedcutlet.yokan.ext"
        compileSdk = 37
        minSdk = 26
        compilerOptions.jvmTarget.set(JvmTarget.JVM_17)
        withHostTest {}
    }
    jvm("desktop")
    @OptIn(org.jetbrains.kotlin.gradle.ExperimentalWasmDsl::class)
    wasmJs { browser() }
    // JNI headers are vendored beside JvmBridge.h so cinterop does not depend on the JDK running Gradle.
    listOf(iosX64(), iosArm64(), iosSimulatorArm64()).forEach { target ->
        target.compilations.getByName("main").cinterops.create("JvmBridge") {
            definitionFile.set(project.file("src/nativeInterop/cinterop/JvmBridge.def"))
            compilerOpts("-I${project.file("src/nativeInterop/cinterop").absolutePath}")
        }
    }

    sourceSets {
        commonMain.dependencies {
            implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
            implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.12.0")
        }
        iosMain.dependencies {
            implementation("com.squareup.okio:okio:3.18.2")
            implementation("io.ktor:ktor-client-core:3.6.0")
            implementation("io.ktor:ktor-client-darwin:3.6.0")
        }
        commonTest.dependencies {
            implementation(kotlin("test"))
            implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.11.0")
        }
        androidMain.dependencies {
            implementation("io.reactivex:rxjava:1.3.8")
            implementation("io.reactivex:rxandroid:1.2.1")
            implementation("uy.kohesive.injekt:injekt-core:1.16.1")
            implementation("com.squareup.okhttp3:logging-interceptor:5.5.1")
            implementation("com.squareup.okhttp3:okhttp:5.5.1")
            implementation("com.squareup.okio:okio:3.18.2")
            implementation("com.squareup.okhttp3:okhttp-brotli:5.5.1")
            implementation("androidx.core:core-ktx:1.19.1")
            implementation("androidx.preference:preference-ktx:1.2.1")
            implementation("org.jsoup:jsoup:1.23.2")
            implementation("org.nanohttpd:nanohttpd:2.3.1")
            implementation("com.fasterxml.jackson.core:jackson-databind:2.22.4")
            implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.22.4")
        }
    }
}

```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/gradle.properties
### Write `vendor/yokan-ext/gradle.properties`

Create this path in your reconstruction project. Source set: **build / host / supporting material**. [Exact file download](../reference/source/vendor/yokan-ext/gradle.properties).

```properties
org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8
kotlin.code.style=official
android.useAndroidX=true
kotlin.mpp.enableCInteropCommonization=true
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/gradle/wrapper/gradle-wrapper.jar
### Write `vendor/yokan-ext/gradle/wrapper/gradle-wrapper.jar`

Create this path in your reconstruction project. Source set: **build / host / supporting material**. [Exact file download](../reference/source/vendor/yokan-ext/gradle/wrapper/gradle-wrapper.jar).

This file is binary. Retain the downloaded asset at this exact path, with its applicable license. It is an input to the code/configuration in this step; it cannot be recreated by typing a Kotlin snippet.
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/gradle/wrapper/gradle-wrapper.properties
### Write `vendor/yokan-ext/gradle/wrapper/gradle-wrapper.properties`

Create this path in your reconstruction project. Source set: **build / host / supporting material**. [Exact file download](../reference/source/vendor/yokan-ext/gradle/wrapper/gradle-wrapper.properties).

```properties
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/gradlew
### Write `vendor/yokan-ext/gradlew`

Create this path in your reconstruction project. Source set: **build / host / supporting material**. [Exact file download](../reference/source/vendor/yokan-ext/gradlew).

```text
#!/bin/sh

#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#

##############################################################################
#
#   Gradle start up script for POSIX generated by Gradle.
#
#   Important for running:
#
#   (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
#       noncompliant, but you have some other compliant shell such as ksh or
#       bash, then to run this script, type that shell name before the whole
#       command line, like:
#
#           ksh Gradle
#
#       Busybox and similar reduced shells will NOT work, because this script
#       requires all of these POSIX shell features:
#         * functions;
#         * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
#           «${var#prefix}», «${var%suffix}», and «$( cmd )»;
#         * compound commands having a testable exit status, especially «case»;
#         * various built-in commands including «command», «set», and «ulimit».
#
#   Important for patching:
#
#   (2) This script targets any POSIX shell, so it avoids extensions provided
#       by Bash, Ksh, etc; in particular arrays are avoided.
#
#       The "traditional" practice of packing multiple parameters into a
#       space-separated string is a well documented source of bugs and security
#       problems, so this is (mostly) avoided, by progressively accumulating
#       options in "$@", and eventually passing that to Java.
#
#       Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
#       and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
#       see the in-line comments for details.
#
#       There are tweaks for specific operating systems such as AIX, CygWin,
#       Darwin, MinGW, and NonStop.
#
#   (3) This script is generated from the Groovy template
#       https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
#       within the Gradle project.
#
#       You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################

# Attempt to set APP_HOME

# Resolve links: $0 may be a link
app_path=$0

# Need this for daisy-chained symlinks.
while
    APP_HOME=${app_path%"${app_path##*/}"}  # leaves a trailing /; empty if no leading path
    [ -h "$app_path" ]
do
    ls=$( ls -ld "$app_path" )
    link=${ls#*' -> '}
    case $link in             #(
      /*)   app_path=$link ;; #(
      *)    app_path=$APP_HOME$link ;;
    esac
done

# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum

warn () {
    echo "$*"
} >&2

die () {
    echo
    echo "$*"
    echo
    exit 1
} >&2

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in                #(
  CYGWIN* )         cygwin=true  ;; #(
  Darwin* )         darwin=true  ;; #(
  MSYS* | MINGW* )  msys=true    ;; #(
  NONSTOP* )        nonstop=true ;;
esac

CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar


# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
        # IBM's JDK on AIX uses strange locations for the executables
        JAVACMD=$JAVA_HOME/jre/sh/java
    else
        JAVACMD=$JAVA_HOME/bin/java
    fi
    if [ ! -x "$JAVACMD" ] ; then
        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
else
    JAVACMD=java
    if ! command -v java >/dev/null 2>&1
    then
        die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
fi

# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
    case $MAX_FD in #(
      max*)
        # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
        # shellcheck disable=SC2039,SC3045
        MAX_FD=$( ulimit -H -n ) ||
            warn "Could not query maximum file descriptor limit"
    esac
    case $MAX_FD in  #(
      '' | soft) :;; #(
      *)
        # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
        # shellcheck disable=SC2039,SC3045
        ulimit -n "$MAX_FD" ||
            warn "Could not set maximum file descriptor limit to $MAX_FD"
    esac
fi

# Collect all arguments for the java command, stacking in reverse order:
#   * args from the command line
#   * the main class name
#   * -classpath
#   * -D...appname settings
#   * --module-path (only if needed)
#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.

# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
    APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
    CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )

    JAVACMD=$( cygpath --unix "$JAVACMD" )

    # Now convert the arguments - kludge to limit ourselves to /bin/sh
    for arg do
        if
            case $arg in                                #(
              -*)   false ;;                            # don't mess with options #(
              /?*)  t=${arg#/} t=/${t%%/*}              # looks like a POSIX filepath
                    [ -e "$t" ] ;;                      #(
              *)    false ;;
            esac
        then
            arg=$( cygpath --path --ignore --mixed "$arg" )
        fi
        # Roll the args list around exactly as many times as the number of
        # args, so each arg winds up back in the position where it started, but
        # possibly modified.
        #
        # NB: a `for` loop captures its iteration list before it begins, so
        # changing the positional parameters here affects neither the number of
        # iterations, nor the values presented in `arg`.
        shift                   # remove old arg
        set -- "$@" "$arg"      # push replacement arg
    done
fi


# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'

# Collect all arguments for the java command:
#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
#     and any embedded shellness will be escaped.
#   * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
#     treated as '${Hostname}' itself on the command line.

set -- \
        "-Dorg.gradle.appname=$APP_BASE_NAME" \
        -classpath "$CLASSPATH" \
        org.gradle.wrapper.GradleWrapperMain \
        "$@"

# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
    die "xargs is not available"
fi

# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
#   readarray ARGS < <( xargs -n1 <<<"$var" ) &&
#   set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#

eval "set -- $(
        printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
        xargs -n1 |
        sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
        tr '\n' ' '
    )" '"$@"'

exec "$JAVACMD" "$@"
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/gradlew.bat
### Write `vendor/yokan-ext/gradlew.bat`

Create this path in your reconstruction project. Source set: **build / host / supporting material**. [Exact file download](../reference/source/vendor/yokan-ext/gradlew.bat).

```bat
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem      https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem

@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem  Gradle startup script for Windows
@rem
@rem ##########################################################################

@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal

set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%

@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi

@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"

@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome

set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute

echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2

goto fail

:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto execute

echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2

goto fail

:execute
@rem Setup the command line

set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar


@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*

:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd

:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%

:mainEnd
if "%OS%"=="Windows_NT" endlocal

:omega
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/settings.gradle.kts
### Write `vendor/yokan-ext/settings.gradle.kts`

Create this path in your reconstruction project. Source set: **build / host / supporting material**. [Exact file download](../reference/source/vendor/yokan-ext/settings.gradle.kts).

```kotlin
pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.name = "yokan-ext"
```
[chapter-file-end]: #

### Check your understanding

Build the submodule on its own and instantiate a fake ExtensionServer. Check invalid port/configuration behavior before connecting any extension APK.
[chapter-content-end]: #


## Step 2: reproduce the Android extension ABI

Create `eu.kanade.tachiyomi.source` and `animesource` interfaces with their exact package/class/member signatures. These names are loaded by existing extensions; renaming breaks binary compatibility. Implement source factories, configurable/unmetered sources, HTTP and parsed HTTP bases, filters/lists, manga/anime pages, titles, chapters/episodes, video, update strategy, fetch type, relations and credits.

Keep manga and anime variants distinct where the ABI differs. Preserve RxJava return types and synchronous/network helper behavior expected by third-party APKs. Recreate App/AppInfo/AppModule/SourceManager host services, Injekt initialization, preferences and context handling.

Implement request builders, OkHttp extensions, memory cookies, progress listeners, rate limiting, host-specific rate limiting, gzip/Cloudflare interceptors, Jsoup helpers and coroutine adapters. These support the loaded code's contract, even if the main app uses different HTTP abstractions.

[chapter-content-start]: #
### Follow the code

Existing extension bytecode resolves classes by full package and signatures. Write the manga/anime model/filter/source contracts before their host implementations, keeping Rx return types and JVM-facing names. Networking, preferences, Injekt and parsing helpers are part of that compatibility surface, even though Yokan itself has different abstractions. An implementation that looks equivalent at source level may still break a compiled extension if its ABI differs.

Write these files in this order:

- `vendor/yokan-ext`
- `vendor/yokan-ext/.github/workflows/ci.yml`
- `vendor/yokan-ext/local.properties.example`
- `vendor/yokan-ext/src/androidMain/AndroidManifest.xml`
- `vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/controller/MExtensionServerController.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/impl/MExtensionServerLoader.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/model/DataBody.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/model/ResponseModels.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/friedcutlet/yokan/ext/AndroidExtensionServer.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/App.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/AppInfo.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/AppModule.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/AnimeCatalogueSource.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/AnimeSource.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/AnimeSourceFactory.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/ConfigurableAnimeSource.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/UnmeteredSource.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeFilter.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeFilterList.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeRelation.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeUpdateStrategy.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimesPage.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/Credit.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/FetchType.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SAnime.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SAnimeImpl.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SEpisode.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SEpisodeImpl.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/Video.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/online/AnimeHttpSource.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/online/ParsedAnimeHttpSource.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/online/ResolvableAnimeSource.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/MemoryCookieJar.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/NetworkHelper.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/OkHttpExtensions.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/ProgressListener.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/Requests.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/CloudflareInterceptor.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/IgnoreGzipInterceptor.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/RateLimitInterceptor.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/SpecificHostRateLimitInterceptor.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/CatalogueSource.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/ConfigurableSource.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/LocalSource.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/Source.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/SourceFactory.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/SourceManager.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/UnmeteredSource.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/Filter.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/FilterList.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/MangasPage.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/Page.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SChapter.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SChapterImpl.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SManga.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SMangaImpl.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/UpdateStrategy.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/online/HttpSource.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/online/HttpSourceFetcher.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/online/ParsedHttpSource.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/util/JsoupExtensions.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/util/lang/CoroutinesExtensions.kt`

[chapter-file-start]: #vendor/yokan-ext
### Write `vendor/yokan-ext`

This is a separate repository/build boundary: revision `67788fa29ae61f053beeaf3284a638cc0bbbe561`. Recreate its directory and build independently. Its tracked contents are included individually in this chapter.
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/.github/workflows/ci.yml
### Write `vendor/yokan-ext/.github/workflows/ci.yml`

Create this path in your reconstruction project. Source set: **build / host / supporting material**. [Exact file download](../reference/source/vendor/yokan-ext/.github/workflows/ci.yml).

```yaml
name: CI

on:
  push:
  pull_request:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: '17'
      - uses: android-actions/setup-android@v3
      - name: Install Android SDK 36
        run: sdkmanager "platforms;android-36"
      - name: Test and assemble
        run: ./gradlew desktopTest assembleRelease --no-daemon
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/local.properties.example
### Write `vendor/yokan-ext/local.properties.example`

Create this path in your reconstruction project. Source set: **build / host / supporting material**. [Exact file download](../reference/source/vendor/yokan-ext/local.properties.example).

```text
# Copy this file to local.properties and set sdk.dir to your Android SDK path.
# sdk.dir=/path/to/android/sdk
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/AndroidManifest.xml
### Write `vendor/yokan-ext/src/androidMain/AndroidManifest.xml`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/AndroidManifest.xml).

```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/controller/MExtensionServerController.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/controller/MExtensionServerController.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/controller/MExtensionServerController.kt).

The implementation below defines `MExtensionServerController`, `start`, `stop`, `isRunning`, `serve`.

```kotlin
package m_extension_server.controller

import fi.iki.elonen.NanoHTTPD
import com.kodjodevf.m_extension_server.server.controller.DalvikHandler
import java.io.IOException

class MExtensionServerController(
) {
    private var server: WebServer? = null

    fun start(port: Int) {
        try {
            server = WebServer(port?:8080)
            server?.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false)
        } catch (e: IOException) {
            throw e
        }
    }

    fun stop() {
        server?.stop()
    }

    fun isRunning(): Boolean = server?.isAlive == true

    private inner class WebServer(
        port: Int,
        // Loopback-only: the bridge executes arbitrary APK code on behalf of the
        // caller, so it must never be reachable from other devices on the network.
    ) : NanoHTTPD("127.0.0.1", port) {
        override fun serve(session: IHTTPSession): Response =
            when (session.uri) {
                "/dalvik" -> DalvikHandler().serve(session)
                "/" -> newFixedLengthResponse("MExtensionServer Server Running")
                // No /stop route: Yokan owns the controller in-process
                // (AndroidExtensionServer.stop()), so an HTTP kill switch is
                // unauthenticated attack surface with no caller.
                else -> newFixedLengthResponse(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Not Found")
            }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/impl/MExtensionServerLoader.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/impl/MExtensionServerLoader.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/impl/MExtensionServerLoader.kt).

The implementation below defines `MExtensionServerLoader`, `LoadedExtension`, `getSource`, `loadSourceFromBase64`, `load`.

```kotlin
package m_extension_server.impl

import android.annotation.SuppressLint
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import dalvik.system.DexClassLoader
import eu.kanade.tachiyomi.animesource.AnimeSource
import eu.kanade.tachiyomi.animesource.AnimeSourceFactory
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.CatalogueSource
import eu.kanade.tachiyomi.source.SourceFactory
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.util.Arrays
import java.util.Base64
import java.util.UUID
import kotlin.jvm.optionals.toList
import com.kodjodevf.m_extension_server.pm

object MExtensionServerLoader {
    private var pmm: PackageManager? = null
    private const val MANGA_PACKAGE = "tachiyomi.extension"
    private const val ANIME_PACKAGE = "tachiyomi.animeextension"
    private const val METADATA_SOURCE_CLASS_SUFFIX = ".class"

    init {
        pmm = pm;
    }
    data class LoadedExtension(
        val sources: List<Any>,
        val tempApkFile: File,
    )

    fun getSource(
        classLoader: DexClassLoader?,
        file: File,
    ): List<Any>? {
        if (pmm == null) {
            return emptyList<Any>();
        }
        val info: PackageInfo? = pmm!!.getPackageArchiveInfo(
            file.absolutePath,
            PackageManager.GET_CONFIGURATIONS or PackageManager.GET_META_DATA
        )
        if (info != null && info.applicationInfo != null) {
            println(info.applicationInfo!!.metaData.toString())
            val metaData = info.applicationInfo!!.metaData
            var metaSourceClass = metaData.getString(MANGA_PACKAGE + METADATA_SOURCE_CLASS_SUFFIX)
            if (metaSourceClass == null) {
                metaSourceClass = metaData.getString(ANIME_PACKAGE + METADATA_SOURCE_CLASS_SUFFIX)
            }
            if (metaSourceClass == null) {
                throw IllegalArgumentException("No source class found in extension metadata")
            }

            return Arrays.stream<String>(
                metaSourceClass.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            )
                .map<String?> { s: String? ->
                    val sourceClass = s!!.trim { it <= ' ' }
                    if (sourceClass.startsWith(".")) {
                        return@map info.packageName + sourceClass
                    }
                    sourceClass
                }.findFirst().map<List<Any>> { sourceClass->
                    val obj: Any =
                        Class.forName(sourceClass!!, false, classLoader).getDeclaredConstructor()
                            .newInstance()
                    val sources: List<Any> =
                        when (obj) {
                            is Source -> listOf(obj)
                            is SourceFactory -> obj.createSources()
                            is AnimeSource -> listOf(obj)
                            is AnimeSourceFactory -> obj.createSources()
                            else -> throw RuntimeException("Unknown source class type! ${obj.javaClass}")
                        }
                    sources;
                }.toList().firstOrNull()
        }
        return emptyList<Any>();
    }
    @SuppressLint("SuspiciousIndentation")
    fun loadSourceFromBase64(base64Data: String): LoadedExtension {
        val apkData = Base64.getDecoder().decode(base64Data)
        val tempApkFile = File.createTempFile("ext", ".apk")
            tempApkFile.setWritable(true)
            // Write APK data to temp file
            tempApkFile.writeBytes(apkData)
            tempApkFile.setReadOnly()
            val loader: DexClassLoader = load(tempApkFile)
            val sources = getSource(loader,tempApkFile)
            return LoadedExtension(sources.orEmpty(),tempApkFile)

    }

    private fun load(file: File): DexClassLoader {
        return DexClassLoader(file.getAbsolutePath(), null, null, this.javaClass.getClassLoader())
    }

}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/model/DataBody.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/model/DataBody.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/model/DataBody.kt).

The implementation below defines `DataBody`, `MangaData`, `ChapterData`, `AnimeData`, `EpisodeData`, `JFilterList`, `JGroupFilter`, `JSortFilter`.

```kotlin
package m_extension_server.model

data class DataBody(
    val data: String, // Base64 encoded APK data
    val method: String,
    val page: Int? = null,
    val search: String? = null,
    val filterList: List<JFilterList>? = null,
    val mangaData: MangaData? = null,
    val chapterData: ChapterData? = null,
    val animeData: AnimeData? = null,
    val episodeData: EpisodeData? = null,
    val preferences: MutableList<Map<String, Any>>? = null,
)

data class MangaData(
    val url: String?,
    val title: String?,
    val artist: String?,
    val author: String?,
    val description: String?,
    val genre: String?,
    val status: Int?,
    val thumbnail_url: String?,
    val initialized: Boolean?,
)

data class ChapterData(
    val url: String?,
    val name: String?,
    val date_upload: Long?,
    val chapter_number: Float?,
    val scanlator: String?,
)

data class AnimeData(
    val url: String?,
    val title: String?,
    val artist: String?,
    val author: String?,
    val description: String?,
    val genre: String?,
    val status: Int?,
    val thumbnail_url: String?,
    val initialized: Boolean?,
)

data class EpisodeData(
    val url: String?,
    val name: String?,
    val date_upload: Long?,
    val episode_number: Float?,
    val scanlator: String?,
)

data class JFilterList(
    val name: String?,
    val type: String?,
    val stateString: String?,
    val stateInt: Int?,
    val stateList: List<JGroupFilter>?,
    val stateSort: JSortFilter?,
)

data class JGroupFilter(
    val name: String?,
    val type: String?,
    val stateBoolean: Boolean?,
    val stateInt: Int?,
)

data class JSortFilter(
    val ascending: Boolean?,
    val index: Int?,
)
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/model/ResponseModels.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/model/ResponseModels.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/model/ResponseModels.kt).

The implementation below defines `MangaResponse`, `AnimeResponse`, `PageResponse`, `FiltersResponse`, `AnimeFiltersResponse`, `PreferencesResponse`, `JManga`, `JAnime`, `JChapter`, `JEpisode` and 6 further declarations.

```kotlin
package m_extension_server.model

import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.animesource.model.Credit
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga

// Response models matching MExtensionServer format
data class MangaResponse(
    val mangas: List<JManga>? = null,
    val hasNextPage: Boolean? = null,
)

data class AnimeResponse(
    val animes: List<JAnime>? = null,
    val hasNextPage: Boolean? = null,
)

data class PageResponse(
    val pageList: List<JPage>? = null,
)

data class FiltersResponse(
    val filterList: FilterList? = null,
)

data class AnimeFiltersResponse(
    val filterList: AnimeFilterList? = null,
)

data class PreferencesResponse(
    val preferences: List<JPreference>? = null,
)

data class JManga(
    val url: String,
    val title: String,
    val artist: String?,
    val author: String?,
    val description: String?,
    val genre: String?,
    val status: Int,
    val thumbnail_url: String?,
    val initialized: Boolean,
)

data class JAnime(
    val url: String,
    val title: String,
    val artist: String?,
    val author: String?,
    val description: String?,
    val genre: String?,
    val status: Int,
    val thumbnail_url: String?,
    val initialized: Boolean,
    val cast: List<Credit>? = null,
    val fetch_type: String = "Episodes",
    val season_number: Double = -1.0,
)

data class JChapter(
    val url: String,
    val name: String,
    val date_upload: Long,
    val chapter_number: Float,
    val scanlator: String?,
)

data class JEpisode(
    val url: String,
    val name: String,
    val date_upload: Long,
    val episode_number: Float,
    val scanlator: String?,
)

data class JPage(
    val index: Int,
    val url: String,
    val imageUrl: String?,
)

data class JPreference(
    val type: String,
    val props: Map<String, Any>,
)

fun SManga.toJManga(): JManga =
    JManga(
        url = runCatching { this.url }.getOrDefault(""),
        title = runCatching { this.title }.getOrDefault(""),
        artist = runCatching { this.artist }.getOrNull(),
        author = runCatching { this.author }.getOrNull(),
        description = runCatching { this.description }.getOrNull(),
        genre = runCatching { this.genre }.getOrNull(),
        status = runCatching { this.status }.getOrDefault(0),
        thumbnail_url = runCatching { this.thumbnail_url }.getOrNull(),
        initialized = runCatching { this.initialized }.getOrDefault(false),
    )

fun SChapter.toJChapter(): JChapter =
    JChapter(
        url = runCatching { this.url }.getOrDefault(""),
        name = runCatching { this.name }.getOrDefault(""),
        date_upload = runCatching { this.date_upload }.getOrDefault(0L),
        chapter_number = runCatching { this.chapter_number }.getOrDefault(0f),
        scanlator = runCatching { this.scanlator }.getOrNull(),
    )

fun SAnime.toJAnime(): JAnime =
    JAnime(
        url = runCatching { this.url }.getOrDefault(""),
        title = runCatching { this.title }.getOrDefault(""),
        artist = runCatching { this.artist }.getOrNull(),
        author = runCatching { this.author }.getOrNull(),
        description = runCatching { this.description }.getOrNull(),
        genre = runCatching { this.genre }.getOrNull(),
        status = runCatching { this.status }.getOrDefault(0),
        thumbnail_url = runCatching { this.thumbnail_url }.getOrNull(),
        initialized = runCatching { this.initialized }.getOrDefault(false),
        cast = try { this.cast } catch (_: AbstractMethodError) { null },
        fetch_type = try { this.fetch_type.name } catch (_: AbstractMethodError) { "Episodes" },
        season_number = try { this.season_number } catch (_: AbstractMethodError) { -1.0 },
    )

fun SEpisode.toJEpisode(): JEpisode =
    JEpisode(
        url = runCatching { this.url }.getOrDefault(""),
        name = runCatching { this.name }.getOrDefault(""),
        date_upload = runCatching { this.date_upload }.getOrDefault(0L),
        episode_number = runCatching { this.episode_number }.getOrDefault(0f),
        scanlator = runCatching { this.scanlator }.getOrNull(),
    )
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/friedcutlet/yokan/ext/AndroidExtensionServer.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/friedcutlet/yokan/ext/AndroidExtensionServer.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/friedcutlet/yokan/ext/AndroidExtensionServer.kt).

The implementation below defines `AndroidExtensionServer`, `start`, `stop`, `stopLocked`.

The source describes its contract as:

> \[preferencesPrefix\] namespaces the extensions' SharedPreferences; "" keeps the legacy names.

```kotlin
package eu.friedcutlet.yokan.ext

import android.content.Context
import com.kodjodevf.m_extension_server.acquireBridgeEnvironment
import com.kodjodevf.m_extension_server.releaseBridgeEnvironment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import m_extension_server.controller.MExtensionServerController

/** [preferencesPrefix] namespaces the extensions' SharedPreferences; "" keeps the legacy names. */
class AndroidExtensionServer(
    context: Context,
    private val preferencesPrefix: String = "",
) : ExtensionServer {
    private val appContext = context.applicationContext
    private val lock = Mutex()
    private val mutableStatus = MutableStateFlow(ExtensionServerStatus.Stopped)
    private var controller: MExtensionServerController? = null
    private var activeConfig: ExtensionServerConfig? = null

    override val status: StateFlow<ExtensionServerStatus> = mutableStatus

    override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus = lock.withLock {
        if (controller?.isRunning() == true && activeConfig == config) return mutableStatus.value
        stopLocked()
        mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Starting, config.port, "Starting Android APK bridge")
        try {
            acquireBridgeEnvironment(this, appContext, preferencesPrefix)
            val created = MExtensionServerController()
            withContext(Dispatchers.IO) { created.start(config.port) }
            controller = created
            activeConfig = config
            ExtensionServerStatus(ExtensionServerPhase.Running, config.port, "APK bridge started on port ${config.port}")
                .also { mutableStatus.value = it }
        } catch (error: Throwable) {
            releaseBridgeEnvironment(this)
            val message = "Failed to start Android APK bridge: ${error.message.orEmpty()}"
            mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Failed, config.port, message)
            throw ExtensionServerException("START_ERROR", message, error)
        }
    }

    override suspend fun stop(): ExtensionServerStatus = lock.withLock { stopLocked() }

    private suspend fun stopLocked(): ExtensionServerStatus {
        val current = controller
        if (current == null) return ExtensionServerStatus.Stopped.also { mutableStatus.value = it }
        mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Stopping, activeConfig?.port, "Stopping Android APK bridge")
        withContext(Dispatchers.IO) { current.stop() }
        controller = null
        activeConfig = null
        releaseBridgeEnvironment(this)
        return ExtensionServerStatus.Stopped.copy(message = "APK bridge stopped").also { mutableStatus.value = it }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/App.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/App.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/App.kt).

The implementation below defines `App`, `onCreate`, `attachBaseContext`.

```kotlin
package eu.kanade.tachiyomi

import android.app.Application
import android.content.Context
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.InjektScope
import uy.kohesive.injekt.registry.default.DefaultRegistrar

open class App : Application() {
    override fun onCreate() {
        super.onCreate()
        Injekt = InjektScope(DefaultRegistrar())
        Injekt.importModule(AppModule(this))
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/AppInfo.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/AppInfo.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/AppInfo.kt).

The implementation below defines `AppInfo`, `getVersionCode`, `getVersionName`.

```kotlin
package eu.kanade.tachiyomi

import rx.android.BuildConfig

/**
 * Used by extensions.
 *
 * @since extension-lib 1.3
 */
object AppInfo {
    fun getVersionCode() = BuildConfig.VERSION_CODE

    fun getVersionName() = BuildConfig.VERSION_NAME
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/AppModule.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/AppModule.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/AppModule.kt).

The implementation below defines `AppModule`, `InjektRegistrar.registerInjectables`.

```kotlin
package eu.kanade.tachiyomi

import android.app.Application
import eu.kanade.tachiyomi.network.NetworkHelper
import kotlinx.serialization.json.Json
import uy.kohesive.injekt.api.InjektModule
import uy.kohesive.injekt.api.InjektRegistrar
import uy.kohesive.injekt.api.addSingleton
import uy.kohesive.injekt.api.addSingletonFactory

class AppModule(
    val app: Application,
) : InjektModule {
    override fun InjektRegistrar.registerInjectables() {
        addSingleton(app)

        addSingletonFactory { NetworkHelper(app) }
        
        addSingletonFactory { Json { ignoreUnknownKeys = true } }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/AnimeCatalogueSource.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/AnimeCatalogueSource.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/AnimeCatalogueSource.kt).

The implementation below defines `AnimeCatalogueSource`, `getPopularAnime`, `getSearchAnime`, `getLatestUpdates`, `getFilterList`, `fetchPopularAnime`, `fetchSearchAnime`, `fetchLatestUpdates`.

The source describes its contract as:

> An ISO 639-1 compliant language code (two letters in lower case).

```kotlin
package eu.kanade.tachiyomi.animesource

import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.animesource.model.AnimesPage
import eu.kanade.tachiyomi.util.lang.awaitSingle
import rx.Observable

interface AnimeCatalogueSource : AnimeSource {
    /**
     * An ISO 639-1 compliant language code (two letters in lower case).
     */
    override val lang: String

    /**
     * Whether the source has support for latest updates.
     */
    val supportsLatest: Boolean

    /**
     * Get a page with a list of anime.
     *
     * @since extensions-lib 1.5
     * @param page the page number to retrieve.
     */
    @Suppress("DEPRECATION")
    suspend fun getPopularAnime(page: Int): AnimesPage = fetchPopularAnime(page).awaitSingle()

    /**
     * Get a page with a list of anime.
     *
     * @since extensions-lib 1.5
     * @param page the page number to retrieve.
     * @param query the search query.
     * @param filters the list of filters to apply.
     */
    @Suppress("DEPRECATION")
    suspend fun getSearchAnime(
        page: Int,
        query: String,
        filters: AnimeFilterList,
    ): AnimesPage = fetchSearchAnime(page, query, filters).awaitSingle()

    /**
     * Get a page with a list of latest anime updates.
     *
     * @since extensions-lib 1.5
     * @param page the page number to retrieve.
     */
    @Suppress("DEPRECATION")
    suspend fun getLatestUpdates(page: Int): AnimesPage = fetchLatestUpdates(page).awaitSingle()

    /**
     * Returns the list of filters for the source.
     */
    fun getFilterList(): AnimeFilterList

    // Should be replaced as soon as Anime Extension reach 1.5
    @Deprecated(
        "Use the non-RxJava API instead",
        ReplaceWith("getPopularAnime"),
    )
    fun fetchPopularAnime(page: Int): Observable<AnimesPage>

    // Should be replaced as soon as Anime Extension reach 1.5
    @Deprecated(
        "Use the non-RxJava API instead",
        ReplaceWith("getSearchAnime"),
    )
    fun fetchSearchAnime(
        page: Int,
        query: String,
        filters: AnimeFilterList,
    ): Observable<AnimesPage>

    // Should be replaced as soon as Anime Extension reach 1.5
    @Deprecated(
        "Use the non-RxJava API instead",
        ReplaceWith("getLatestUpdates"),
    )
    fun fetchLatestUpdates(page: Int): Observable<AnimesPage>
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/AnimeSource.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/AnimeSource.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/AnimeSource.kt).

The implementation below defines `AnimeSource`, `getRelatedAnimeList`, `getSeasonList`, `getAnimeDetails`, `getEpisodeList`, `getVideoList`, `fetchAnimeDetails`, `fetchEpisodeList`, `fetchVideoList`.

The source describes its contract as:

> A basic interface for creating a source. It could be an online source, a local source, etc.

```kotlin
package eu.kanade.tachiyomi.animesource

import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.AnimeRelation
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.util.lang.awaitSingle
import rx.Observable

/**
 * A basic interface for creating a source. It could be an online source, a local source, etc.
 */
interface AnimeSource {
    /**
     * ID for the source. Must be unique.
     */
    val id: Long

    /**
     * Name of the source.
     */
    val name: String

    val lang: String
        get() = ""

    val supportsRelatedAnime: Boolean
        get() = false

    suspend fun getRelatedAnimeList(anime: SAnime): List<AnimeRelation> = emptyList()

    /**
     * Seasons of a [eu.kanade.tachiyomi.animesource.model.FetchType.Seasons] anime; each is its own anime.
     *
     * @since extensions-lib 16
     */
    suspend fun getSeasonList(anime: SAnime): List<SAnime> = emptyList()

    /**
     * Get the updated details for a anime.
     *
     * @since extensions-lib 1.5
     * @param anime the anime to update.
     * @return the updated anime.
     */
    @Suppress("DEPRECATION")
    suspend fun getAnimeDetails(anime: SAnime): SAnime = fetchAnimeDetails(anime).awaitSingle()

    /**
     * Get all the available episodes for a anime.
     *
     * @since extensions-lib 1.5
     * @param anime the anime to update.
     * @return the episodes for the anime.
     */
    @Suppress("DEPRECATION")
    suspend fun getEpisodeList(anime: SAnime): List<SEpisode> = fetchEpisodeList(anime).awaitSingle()

    /**
     * Get the list of videos a episode has. Pages should be returned
     * in the expected order; the index is ignored.
     *
     * @since extensions-lib 1.5
     * @param episode the episode.
     * @return the videos for the episode.
     */
    @Suppress("DEPRECATION")
    suspend fun getVideoList(episode: SEpisode): List<Video> = fetchVideoList(episode).awaitSingle()

    @Deprecated(
        "Use the non-RxJava API instead",
        ReplaceWith("getAnimeDetails"),
    )
    fun fetchAnimeDetails(anime: SAnime): Observable<SAnime> = throw IllegalStateException("Not used")

    @Deprecated(
        "Use the non-RxJava API instead",
        ReplaceWith("getEpisodeList"),
    )
    fun fetchEpisodeList(anime: SAnime): Observable<List<SEpisode>> = throw IllegalStateException("Not used")

    @Deprecated(
        "Use the non-RxJava API instead",
        ReplaceWith("getVideoList"),
    )
    fun fetchVideoList(episode: SEpisode): Observable<List<Video>> = throw IllegalStateException("Not used")
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/AnimeSourceFactory.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/AnimeSourceFactory.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/AnimeSourceFactory.kt).

The implementation below defines `AnimeSourceFactory`, `createSources`.

The source describes its contract as:

> A factory for creating sources at runtime.

```kotlin
package eu.kanade.tachiyomi.animesource

/**
 * A factory for creating sources at runtime.
 */
interface AnimeSourceFactory {
    /**
     * Create a new copy of the sources
     * @return The created sources
     */
    fun createSources(): List<AnimeSource>
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/ConfigurableAnimeSource.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/ConfigurableAnimeSource.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/ConfigurableAnimeSource.kt).

The implementation below defines `ConfigurableAnimeSource`, `getSourcePreferences`, `setupPreferenceScreen`, `ConfigurableAnimeSource.preferenceKey`.

The source describes its contract as:

> Gets instance of \[SharedPreferences\] scoped to the specific source.

```kotlin
package eu.kanade.tachiyomi.animesource

import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import androidx.preference.PreferenceScreen
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get

interface ConfigurableAnimeSource : AnimeSource {
    /**
     * Gets instance of [SharedPreferences] scoped to the specific source.
     *
     * @since extensions-lib 14
     */
    fun getSourcePreferences(): SharedPreferences = Injekt.get<Application>().getSharedPreferences(preferenceKey(), Context.MODE_PRIVATE)

    fun setupPreferenceScreen(screen: PreferenceScreen)
}

private fun ConfigurableAnimeSource.preferenceKey(): String = "source_$id"
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/UnmeteredSource.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/UnmeteredSource.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/UnmeteredSource.kt).

The implementation below defines `UnmeteredSource`.

The source describes its contract as:

> A source that explicitly doesn't require traffic considerations. This typically applies for self-hosted sources.

```kotlin
package eu.kanade.tachiyomi.animesource

/**
 * A source that explicitly doesn't require traffic considerations.
 *
 * This typically applies for self-hosted sources.
 */
interface UnmeteredSource
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeFilter.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeFilter.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeFilter.kt).

The implementation below defines `AnimeFilter`, `Header`, `Separator`, `Select`, `Text`, `CheckBox`, `TriState`, `isIgnored`, `isIncluded`, `isExcluded` and 5 further declarations.

```kotlin
package eu.kanade.tachiyomi.animesource.model

@Suppress("UnnecessaryAbstractClass")
sealed class AnimeFilter<T>(
    val name: String,
    var state: T,
) {
    open class Header(
        name: String,
    ) : AnimeFilter<Any>(name, 0)

    open class Separator(
        name: String = "",
    ) : AnimeFilter<Any>(name, 0)

    abstract class Select<V>(
        name: String,
        val values: Array<V>,
        state: Int = 0,
    ) : AnimeFilter<Int>(name, state)

    abstract class Text(
        name: String,
        state: String = "",
    ) : AnimeFilter<String>(name, state)

    abstract class CheckBox(
        name: String,
        state: Boolean = false,
    ) : AnimeFilter<Boolean>(name, state)

    abstract class TriState(
        name: String,
        state: Int = STATE_IGNORE,
    ) : AnimeFilter<Int>(name, state) {
        fun isIgnored() = state == STATE_IGNORE

        fun isIncluded() = state == STATE_INCLUDE

        fun isExcluded() = state == STATE_EXCLUDE

        companion object {
            const val STATE_IGNORE = 0
            const val STATE_INCLUDE = 1
            const val STATE_EXCLUDE = 2
        }
    }

    abstract class Group<V>(
        name: String,
        state: List<V>,
    ) : AnimeFilter<List<V>>(name, state)

    abstract class Sort(
        name: String,
        val values: Array<String>,
        state: Selection? = null,
    ) : AnimeFilter<Sort.Selection?>(name, state) {
        data class Selection(
            val index: Int,
            val ascending: Boolean,
        )
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is AnimeFilter<*>) return false

        return name == other.name && state == other.state
    }

    override fun hashCode(): Int {
        var result = name.hashCode()
        result = 31 * result + (state?.hashCode() ?: 0)
        return result
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeFilterList.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeFilterList.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeFilterList.kt).

The implementation below defines `AnimeFilterList`.

```kotlin
package eu.kanade.tachiyomi.animesource.model

data class AnimeFilterList(
    val list: List<AnimeFilter<*>>,
) : List<AnimeFilter<*>> by list {
    constructor(vararg fs: AnimeFilter<*>) : this(if (fs.isNotEmpty()) fs.asList() else emptyList())
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeRelation.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeRelation.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeRelation.kt).

The implementation below defines `AnimeRelation`.

```kotlin
package eu.kanade.tachiyomi.animesource.model

data class AnimeRelation(val name: String, val animes: List<SAnime>)
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeUpdateStrategy.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeUpdateStrategy.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeUpdateStrategy.kt).

The implementation below defines `AnimeUpdateStrategy`.

```kotlin
package eu.kanade.tachiyomi.animesource.model

enum class AnimeUpdateStrategy {
    ALWAYS_UPDATE,
    ONLY_FETCH_ONCE,
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimesPage.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimesPage.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimesPage.kt).

The implementation below defines `AnimesPage`.

```kotlin
package eu.kanade.tachiyomi.animesource.model

data class AnimesPage(
    val animes: List<SAnime>,
    val hasNextPage: Boolean,
)
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/Credit.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/Credit.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/Credit.kt).

The implementation below defines `Credit`.

The source describes its contract as:

> Optional Animetail-compatible source credit, also used by the JSON bridge.

```kotlin
package eu.kanade.tachiyomi.animesource.model

import kotlinx.serialization.Serializable

/** Optional Animetail-compatible source credit, also used by the JSON bridge. */
@Serializable
data class Credit(
    val name: String,
    val role: String? = null,
    val character: String? = null,
    val image_url: String? = null,
)
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/FetchType.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/FetchType.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/FetchType.kt).

The implementation below defines `FetchType`.

The source describes its contract as:

> Extensions-lib 16: a \[SAnime\] lists either seasons (`getSeasonList`) or episodes (`getEpisodeList`).

```kotlin
package eu.kanade.tachiyomi.animesource.model

/** Extensions-lib 16: a [SAnime] lists either seasons (`getSeasonList`) or episodes (`getEpisodeList`). */
enum class FetchType {
    Seasons,
    Episodes,
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SAnime.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SAnime.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SAnime.kt).

The implementation below defines `SAnime`, `copyFrom`, `create`.

The source describes its contract as:

> Older extension implementations need not provide optional credits.

```kotlin
@file:Suppress("ktlint:standard:property-naming")

package eu.kanade.tachiyomi.animesource.model

import java.io.Serializable

interface SAnime : Serializable {
    var url: String

    var title: String

    var artist: String?

    var author: String?

    var description: String?

    var genre: String?

    var status: Int

    var thumbnail_url: String?

    var update_strategy: AnimeUpdateStrategy

    var initialized: Boolean

    /** Older extension implementations need not provide optional credits. */
    var cast: List<Credit>?
        get() = null
        set(_) = Unit

    /** Older extension implementations are episode lists. */
    var fetch_type: FetchType
        get() = FetchType.Episodes
        set(_) = Unit

    /** -1 is unknown, as upstream. */
    var season_number: Double
        get() = -1.0
        set(_) = Unit

    fun copyFrom(other: SAnime) {
        title = other.title

        if (other.author != null) {
            author = other.author
        }

        if (other.artist != null) {
            artist = other.artist
        }

        if (other.description != null) {
            description = other.description
        }

        if (other.genre != null) {
            genre = other.genre
        }

        if (other.thumbnail_url != null) {
            thumbnail_url = other.thumbnail_url
        }

        status = other.status

        // APKs may implement the older interface themselves rather than use SAnime.create().
        try {
            other.cast?.let { cast = it }
        } catch (_: AbstractMethodError) {
            // No credits accessor in that binary; its existing metadata remains usable.
        }

        try {
            fetch_type = other.fetch_type
            season_number = other.season_number
        } catch (_: AbstractMethodError) {
            // Pre-season binary: it stays an episode list.
        }

        if (!initialized) {
            initialized = other.initialized
        }
    }

    companion object {
        const val UNKNOWN = 0
        const val ONGOING = 1
        const val COMPLETED = 2
        const val LICENSED = 3
        const val PUBLISHING_FINISHED = 4
        const val CANCELLED = 5
        const val ON_HIATUS = 6
        const val UPCOMING = 7

        fun create(): SAnime = SAnimeImpl()
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SAnimeImpl.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SAnimeImpl.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SAnimeImpl.kt).

The implementation below defines `SAnimeImpl`.

```kotlin
@file:Suppress("ktlint:standard:property-naming")

package eu.kanade.tachiyomi.animesource.model

class SAnimeImpl : SAnime {
    override lateinit var url: String

    override lateinit var title: String

    override var artist: String? = null

    override var author: String? = null

    override var description: String? = null

    override var genre: String? = null

    override var status: Int = 0

    override var thumbnail_url: String? = null

    override var update_strategy: AnimeUpdateStrategy = AnimeUpdateStrategy.ALWAYS_UPDATE

    override var initialized: Boolean = false

    override var cast: List<Credit>? = null

    override var fetch_type: FetchType = FetchType.Episodes

    override var season_number: Double = -1.0
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SEpisode.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SEpisode.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SEpisode.kt).

The implementation below defines `SEpisode`, `copyFrom`, `create`.

```kotlin
@file:Suppress("ktlint:standard:property-naming")

package eu.kanade.tachiyomi.animesource.model

import java.io.Serializable

interface SEpisode : Serializable {
    var url: String

    var name: String

    var date_upload: Long

    var episode_number: Float

    var scanlator: String?

    fun copyFrom(other: SEpisode) {
        name = other.name
        url = other.url
        date_upload = other.date_upload
        episode_number = other.episode_number
        scanlator = other.scanlator
    }

    companion object {
        fun create(): SEpisode = SEpisodeImpl()
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SEpisodeImpl.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SEpisodeImpl.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SEpisodeImpl.kt).

The implementation below defines `SEpisodeImpl`.

```kotlin
@file:Suppress("ktlint:standard:property-naming")

package eu.kanade.tachiyomi.animesource.model

class SEpisodeImpl : SEpisode {
    override lateinit var url: String

    override lateinit var name: String

    override var date_upload: Long = 0

    override var episode_number: Float = -1f

    override var scanlator: String? = null
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/Video.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/Video.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/Video.kt).

The implementation below defines `Track`, `Video`, `update`, `setStatusSubject`, `setProgressSubject`, `setStatusCallback`.

```kotlin
package eu.kanade.tachiyomi.animesource.model

import android.net.Uri
import eu.kanade.tachiyomi.network.ProgressListener
import okhttp3.Headers
import rx.subjects.Subject

data class Track(
    val url: String,
    val lang: String,
)

open class Video(
    val url: String = "",
    val quality: String = "",
    var videoUrl: String? = null,
    val headers: Headers? = null,
    // "url", "language-label-2", "url2", "language-label-2"
    val subtitleTracks: List<Track> = emptyList(),
    val audioTracks: List<Track> = emptyList(),
) : ProgressListener {
    @Suppress("UNUSED_PARAMETER")
    constructor(
        url: String,
        quality: String,
        videoUrl: String?,
        uri: Uri? = null,
        headers: Headers? = null,
    ) : this(url, quality, videoUrl, headers)

    @Transient
    @Volatile
    var status: Int = 0
        set(value) {
            field = value
            statusSubject?.onNext(value)
            statusCallback?.invoke(this)
        }

    @Transient
    @Volatile
    var progress: Int = 0
        set(value) {
            progressSubject?.onNext(value)
            field = value
            statusCallback?.invoke(this)
        }

    @Transient
    @Volatile
    var totalBytesDownloaded: Long = 0L

    @Transient
    @Volatile
    var totalContentLength: Long = 0L

    @Transient
    @Volatile
    var bytesDownloaded: Long = 0L
        set(value) {
            totalBytesDownloaded +=
                if (value < field) {
                    value
                } else {
                    value - field
                }
            field = value
            statusCallback?.invoke(this)
        }

    @Transient
    private var statusSubject: Subject<Int, Int>? = null

    @Transient
    private var progressSubject: Subject<Int, Int>? = null

    @Transient
    private var statusCallback: ((Video) -> Unit)? = null

    override fun update(
        bytesRead: Long,
        contentLength: Long,
        done: Boolean,
    ) {
        bytesDownloaded = bytesRead
        if (contentLength > totalContentLength) {
            totalContentLength = contentLength
        }
        val newProgress =
            if (totalContentLength > 0) {
                (100 * totalBytesDownloaded / totalContentLength).toInt()
            } else {
                -1
            }
        if (progress != newProgress) progress = newProgress
    }

    fun setStatusSubject(subject: Subject<Int, Int>?) {
        this.statusSubject = subject
    }

    fun setProgressSubject(subject: Subject<Int, Int>?) {
        this.progressSubject = subject
    }

    fun setStatusCallback(f: ((Video) -> Unit)?) {
        statusCallback = f
    }

    companion object {
        const val QUEUE = 0
        const val LOAD_VIDEO = 1
        const val DOWNLOAD_IMAGE = 2
        const val READY = 3
        const val ERROR = 4
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/online/AnimeHttpSource.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/online/AnimeHttpSource.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/online/AnimeHttpSource.kt).

The implementation below defines `AnimeHttpSource`, `generateId`, `headersBuilder`, `toString`, `fetchPopularAnime`, `popularAnimeRequest`, `popularAnimeParse`, `fetchSearchAnime`, `searchAnimeRequest`, `searchAnimeParse` and 31 further declarations.

The source describes its contract as:

> A simple implementation for sources from a website.

```kotlin
package eu.kanade.tachiyomi.animesource.online

import eu.kanade.tachiyomi.animesource.AnimeCatalogueSource
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.animesource.model.AnimesPage
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.NetworkHelper
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.network.awaitSuccess
import eu.kanade.tachiyomi.network.newCachelessCallWithProgress
import eu.kanade.tachiyomi.util.lang.awaitSingle
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import rx.Observable
import uy.kohesive.injekt.injectLazy
import java.net.URI
import java.net.URISyntaxException
import java.security.MessageDigest

/**
 * A simple implementation for sources from a website.
 */
@Suppress("unused")
abstract class AnimeHttpSource : AnimeCatalogueSource {
    /**
     * Network service.
     */
    val network: NetworkHelper by injectLazy()

    /**
     * Base url of the website without the trailing slash, like: http://mysite.com
     */
    abstract val baseUrl: String

    /**
     * Version id used to generate the source id. If the site completely changes and urls are
     * incompatible, you may increase this value and it'll be considered as a new source.
     */
    open val versionId = 1

    /**
     * ID of the source. By default it uses a generated id using the first 16 characters (64 bits)
     * of the MD5 of the string `"${name.lowercase()}/$lang/$versionId"`.
     *
     * The ID is generated by the [generateId] function, which can be reused if needed
     * to generate outdated IDs for cases where the source name or language needs to
     * be changed but migrations can be avoided.
     *
     * Note: the generated ID sets the sign bit to `0`.
     */
    override val id by lazy { generateId(name, lang, versionId) }

    /**
     * Headers used for requests.
     */
    val headers: Headers by lazy { headersBuilder().build() }

    /**
     * Default network client for doing requests.
     */
    open val client: OkHttpClient
        get() = network.client

    /**
     * Generates a unique ID for the source based on the provided [name], [lang] and
     * [versionId]. It will use the first 16 characters (64 bits) of the MD5 of the string
     * `"${name.lowercase()}/$lang/$versionId"`.
     *
     * Note: the generated ID sets the sign bit to `0`.
     *
     * Can be used to generate outdated IDs, such as when the source name or language
     * needs to be changed but migrations can be avoided.
     *
     * @since extensions-lib 15
     * @param name [String] the name of the source
     * @param lang [String] the language of the source
     * @param versionId [Int] the version ID of the source
     * @return a unique ID for the source
     */
    @Suppress("MemberVisibilityCanBePrivate")
    protected fun generateId(
        name: String,
        lang: String,
        versionId: Int,
    ): Long {
        val key = "${name.lowercase()}/$lang/$versionId"
        val bytes = MessageDigest.getInstance("MD5").digest(key.toByteArray())
        return (0..7).map { bytes[it].toLong() and 0xff shl 8 * (7 - it) }.reduce(Long::or) and Long.MAX_VALUE
    }

    /**
     * Headers builder for requests. Implementations can override this method for custom headers.
     */
    protected open fun headersBuilder() =
        Headers.Builder().apply {
            add("User-Agent", network.defaultUserAgentProvider())
        }

    /**
     * Visible name of the source.
     */
    override fun toString() = "$name (${lang.uppercase()})"

    /**
     * Returns an observable containing a page with a list of anime. Normally it's not needed to
     * override this method.
     *
     * @param page the page number to retrieve.
     */
    @Deprecated(
        "Use the non-RxJava API instead",
        ReplaceWith("getPopularAnime"),
    )
    override fun fetchPopularAnime(page: Int): Observable<AnimesPage> =
        client
            .newCall(popularAnimeRequest(page))
            .asObservableSuccess()
            .map(::popularAnimeParse)

    /**
     * Returns the request for the popular anime given the page.
     *
     * @param page the page number to retrieve.
     */
    protected abstract fun popularAnimeRequest(page: Int): Request

    /**
     * Parses the response from the site and returns a [AnimesPage] object.
     *
     * @param response the response from the site.
     */
    protected abstract fun popularAnimeParse(response: Response): AnimesPage

    /**
     * Returns an observable containing a page with a list of anime. Normally it's not needed to
     * override this method.
     *
     * @param page the page number to retrieve.
     * @param query the search query.
     * @param filters the list of filters to apply.
     */
    @Deprecated(
        "Use the non-RxJava API instead",
        ReplaceWith("getSearchAnime"),
    )
    override fun fetchSearchAnime(
        page: Int,
        query: String,
        filters: AnimeFilterList,
    ): Observable<AnimesPage> =
        Observable
            .defer {
                try {
                    client.newCall(searchAnimeRequest(page, query, filters)).asObservableSuccess()
                } catch (e: NoClassDefFoundError) {
                    // RxJava doesn't handle Errors, which tends to happen during global searches
                    // if an old extension using non-existent classes is still around
                    throw RuntimeException(e)
                }
            }.map(::searchAnimeParse)

    /**
     * Returns the request for the search anime given the page.
     *
     * @param page the page number to retrieve.
     * @param query the search query.
     * @param filters the list of filters to apply.
     */
    protected abstract fun searchAnimeRequest(
        page: Int,
        query: String,
        filters: AnimeFilterList,
    ): Request

    /**
     * Parses the response from the site and returns a [AnimesPage] object.
     *
     * @param response the response from the site.
     */
    protected abstract fun searchAnimeParse(response: Response): AnimesPage

    /**
     * Returns an observable containing a page with a list of latest anime updates.
     *
     * @param page the page number to retrieve.
     */
    @Deprecated(
        "Use the non-RxJava API instead",
        ReplaceWith("getLatestUpdates"),
    )
    override fun fetchLatestUpdates(page: Int): Observable<AnimesPage> =
        client
            .newCall(latestUpdatesRequest(page))
            .asObservableSuccess()
            .map(::latestUpdatesParse)

    /**
     * Returns the request for latest anime given the page.
     *
     * @param page the page number to retrieve.
     */
    protected abstract fun latestUpdatesRequest(page: Int): Request

    /**
     * Parses the response from the site and returns a [AnimesPage] object.
     *
     * @param response the response from the site.
     */
    protected abstract fun latestUpdatesParse(response: Response): AnimesPage

    /**
     * Get the updated details for a anime.
     * Normally it's not needed to override this method.
     *
     * @param anime the anime to be updated.
     * @return the updated anime.
     */
    @Suppress("DEPRECATION")
    override suspend fun getAnimeDetails(anime: SAnime): SAnime = fetchAnimeDetails(anime).awaitSingle()

    @Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getAnimeDetails"))
    override fun fetchAnimeDetails(anime: SAnime): Observable<SAnime> =
        client
            .newCall(animeDetailsRequest(anime))
            .asObservableSuccess()
            .map { response ->
                animeDetailsParse(response).apply { initialized = true }
            }

    /**
     * Returns the request for the details of an anime. Override only if it's needed to change the
     * url, send different headers or request method like POST.
     *
     * @param anime the anime to be updated.
     */
    open fun animeDetailsRequest(anime: SAnime): Request = GET(baseUrl + anime.url, headers)

    /**
     * Parses the response from the site and returns the details of an anime.
     *
     * @param response the response from the site.
     */
    protected abstract fun animeDetailsParse(response: Response): SAnime

    /**
     * Get all the available episodes for an anime.
     * Normally it's not needed to override this method.
     *
     * @param anime the anime to update.
     * @return the chapters for the manga.
     * @throws LicensedEntryItemsException if a anime is licensed and therefore no episodes are available.
     */
    @Suppress("DEPRECATION")
    override suspend fun getEpisodeList(anime: SAnime): List<SEpisode> {
        if (anime.status == SAnime.LICENSED) {
            throw LicensedEntryItemsException()
        }

        return fetchEpisodeList(anime).awaitSingle()
    }

    @Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getEpisodeList"))
    override fun fetchEpisodeList(anime: SAnime): Observable<List<SEpisode>> =
        if (anime.status != SAnime.LICENSED) {
            client
                .newCall(episodeListRequest(anime))
                .asObservableSuccess()
                .map(::episodeListParse)
        } else {
            Observable.error(Exception(LicensedEntryItemsException()))
        }

    /**
     * Returns the request for updating the episode list. Override only if it's needed to override
     * the url, send different headers or request method like POST.
     *
     * @param anime the anime to look for episodes.
     */
    protected open fun episodeListRequest(anime: SAnime): Request = GET(baseUrl + anime.url, headers)

    /**
     * Parses the response from the site and returns a list of episodes.
     *
     * @param response the response from the site.
     */
    protected abstract fun episodeListParse(response: Response): List<SEpisode>

    /**
     * Parses the response from the site and returns a SEpisode Object.
     *
     * @param response the response from the site.
     */
    protected abstract fun episodeVideoParse(response: Response): SEpisode

    /**
     * Get the list of videos a episode has. Videos should be returned
     * in the expected order; the index is ignored.
     *
     * @param episode the episode.
     * @return the videos for the episode.
     */
    @Suppress("DEPRECATION")
    override suspend fun getVideoList(episode: SEpisode): List<Video> = fetchVideoList(episode).awaitSingle()

    @Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getVideoList"))
    override fun fetchVideoList(episode: SEpisode): Observable<List<Video>> =
        client
            .newCall(videoListRequest(episode))
            .asObservableSuccess()
            .map { response ->
                videoListParse(response).sort()
            }

    /**
     * Returns the request for getting the episode link. Override only if it's needed to override
     * the url, send different headers or request method like POST.
     *
     * @param episode the episode to look for links.
     */
    protected open fun videoListRequest(episode: SEpisode): Request = GET(baseUrl + episode.url, headers)

    /**
     * Parses the response from the site and returns a list of pages.
     *
     * @param response the response from the site.
     */
    protected abstract fun videoListParse(response: Response): List<Video>

    /**
     * Sorts the video list. Override this according to the user's preference.
     */
    protected open fun List<Video>.sort(): List<Video> = this

    /**
     * Returns an observable with the page containing the source url of the image. If there's any
     * error, it will return null instead of throwing an exception.
     *
     * @since extensions-lib 15
     * @param video the video whose source image has to be fetched.
     */
    @Suppress("DEPRECATION")
    open suspend fun getVideoUrl(video: Video): String = fetchVideoUrl(video).awaitSingle()

    @Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getVideoUrl"))
    open fun fetchVideoUrl(video: Video): Observable<String> =
        client
            .newCall(videoUrlRequest(video))
            .asObservableSuccess()
            .map(::videoUrlParse)

    /**
     * Returns the request for getting the url to the source image. Override only if it's needed to
     * override the url, send different headers or request method like POST.
     *
     * @param video the chapter whose page list has to be fetched
     */
    protected open fun videoUrlRequest(video: Video): Request = GET(video.url, headers)

    /**
     * Parses the response from the site and returns the absolute url to the source image.
     *
     * @param response the response from the site.
     */
    protected abstract fun videoUrlParse(response: Response): String

    /**
     * Returns the response of the source video.
     * Typically does not need to be overridden.
     *
     * @since extensions-lib 15
     * @param video the video whose source video has to be downloaded.
     */
    open suspend fun getVideo(video: Video): Response =
        client
            .newCachelessCallWithProgress(videoRequest(video), video)
            .awaitSuccess()

    /**
     * Returns the request for getting the source image. Override only if it's needed to override
     * the url, send different headers or request method like POST.
     *
     * @param video the video whose link has to be fetched
     */
    protected open fun videoRequest(
        video: Video,
        bytes: Long = 0L,
    ): Request {
        val headers = video.headers ?: headers
        val newHeaders =
            if (bytes > 0L) {
                headers.newBuilder().add("Range", "bytes=$bytes-").build()
            } else {
                headers
            }
        return GET(video.videoUrl ?: video.url, newHeaders)
    }

    /**
     * Assigns the url of the episode without the scheme and domain. It saves some redundancy from
     * database and the urls could still work after a domain change.
     *
     * @param url the full url to the episode.
     */
    fun SEpisode.setUrlWithoutDomain(url: String) {
        this.url = getUrlWithoutDomain(url)
    }

    /**
     * Assigns the url of the anime without the scheme and domain. It saves some redundancy from
     * database and the urls could still work after a domain change.
     *
     * @param url the full url to the anime.
     */
    fun SAnime.setUrlWithoutDomain(url: String) {
        this.url = getUrlWithoutDomain(url)
    }

    /**
     * Returns the url of the given string without the scheme and domain.
     *
     * @param orig the full url.
     */
    private fun getUrlWithoutDomain(orig: String): String =
        try {
            val uri = URI(orig)
            var out = uri.path
            if (uri.query != null) {
                out += "?" + uri.query
            }
            if (uri.fragment != null) {
                out += "#" + uri.fragment
            }
            out
        } catch (e: URISyntaxException) {
            orig
        }

    /**
     * Returns the url of the provided anime
     *
     * @since extensions-lib 14
     * @param anime the anime
     * @return url of the anime
     */
    open fun getAnimeUrl(anime: SAnime): String = animeDetailsRequest(anime).url.toString()

    /**
     * Returns the url of the provided episode
     *
     * @since extensions-lib 14
     * @param episode the episode
     * @return url of the episode
     */
    open fun getEpisodeUrl(episode: SEpisode): String = episode.url.toString()

    /**
     * Called before inserting a new episode into database. Use it if you need to override episode
     * fields, like the title or the episode number. Do not change anything to [anime].
     *
     * @param episode the episode to be added.
     * @param anime the anime of the episode.
     */
    open fun prepareNewEpisode(
        episode: SEpisode,
        anime: SAnime,
    ) {}

    /**
     * Returns the list of filters for the source.
     */
    override fun getFilterList() = AnimeFilterList()
}

class LicensedEntryItemsException : Exception("Licensed - No items to show")
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/online/ParsedAnimeHttpSource.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/online/ParsedAnimeHttpSource.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/online/ParsedAnimeHttpSource.kt).

The implementation below defines `ParsedAnimeHttpSource`, `popularAnimeParse`, `popularAnimeSelector`, `popularAnimeFromElement`, `popularAnimeNextPageSelector`, `searchAnimeParse`, `searchAnimeSelector`, `searchAnimeFromElement`, `searchAnimeNextPageSelector`, `latestUpdatesParse` and 11 further declarations.

The source describes its contract as:

> A simple implementation for sources from a website using Jsoup, an HTML parser.

```kotlin
package eu.kanade.tachiyomi.animesource.online

import eu.kanade.tachiyomi.animesource.model.AnimesPage
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element

/**
 * A simple implementation for sources from a website using Jsoup, an HTML parser.
 */
abstract class ParsedAnimeHttpSource : AnimeHttpSource() {
    /**
     * Parses the response from the site and returns a [AnimesPage] object.
     *
     * @param response the response from the site.
     */
    override fun popularAnimeParse(response: Response): AnimesPage {
        val document = response.asJsoup()

        val animes =
            document
                .select(popularAnimeSelector())
                .map(::popularAnimeFromElement)

        val hasNextPage =
            popularAnimeNextPageSelector()
                ?.let(document::selectFirst) != null

        return AnimesPage(animes, hasNextPage)
    }

    /**
     * Returns the Jsoup selector that returns a list of [Element] corresponding to each anime.
     */
    protected abstract fun popularAnimeSelector(): String

    /**
     * Returns a anime from the given [element]. Most sites only show the title and the url, it's
     * totally fine to fill only those two values.
     *
     * @param element an element obtained from [popularAnimeSelector].
     */
    protected abstract fun popularAnimeFromElement(element: Element): SAnime

    /**
     * Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
     * there's no next page.
     */
    protected abstract fun popularAnimeNextPageSelector(): String?

    /**
     * Parses the response from the site and returns a [AnimesPage] object.
     *
     * @param response the response from the site.
     */
    override fun searchAnimeParse(response: Response): AnimesPage {
        val document = response.asJsoup()

        val animes =
            document
                .select(searchAnimeSelector())
                .map(::searchAnimeFromElement)

        val hasNextPage =
            searchAnimeNextPageSelector()
                ?.let(document::selectFirst) != null

        return AnimesPage(animes, hasNextPage)
    }

    /**
     * Returns the Jsoup selector that returns a list of [Element] corresponding to each anime.
     */
    protected abstract fun searchAnimeSelector(): String

    /**
     * Returns a anime from the given [element]. Most sites only show the title and the url, it's
     * totally fine to fill only those two values.
     *
     * @param element an element obtained from [searchAnimeSelector].
     */
    protected abstract fun searchAnimeFromElement(element: Element): SAnime

    /**
     * Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
     * there's no next page.
     */
    protected abstract fun searchAnimeNextPageSelector(): String?

    /**
     * Parses the response from the site and returns a [AnimesPage] object.
     *
     * @param response the response from the site.
     */
    override fun latestUpdatesParse(response: Response): AnimesPage {
        val document = response.asJsoup()

        val animes =
            document
                .select(latestUpdatesSelector())
                .map(::latestUpdatesFromElement)

        val hasNextPage =
            latestUpdatesNextPageSelector()
                ?.let(document::selectFirst) != null

        return AnimesPage(animes, hasNextPage)
    }

    /**
     * Returns the Jsoup selector that returns a list of [Element] corresponding to each anime.
     */
    protected abstract fun latestUpdatesSelector(): String

    /**
     * Returns a anime from the given [element]. Most sites only show the title and the url, it's
     * totally fine to fill only those two values.
     *
     * @param element an element obtained from [latestUpdatesSelector].
     */
    protected abstract fun latestUpdatesFromElement(element: Element): SAnime

    /**
     * Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
     * there's no next page.
     */
    protected abstract fun latestUpdatesNextPageSelector(): String?

    /**
     * Parses the response from the site and returns the details of a anime.
     *
     * @param response the response from the site.
     */
    override fun animeDetailsParse(response: Response): SAnime = animeDetailsParse(response.asJsoup())

    /**
     * Returns the details of the anime from the given [document].
     *
     * @param document the parsed document.
     */
    protected abstract fun animeDetailsParse(document: Document): SAnime

    /**
     * Parses the response from the site and returns a list of episodes.
     *
     * @param response the response from the site.
     */
    override fun episodeListParse(response: Response): List<SEpisode> {
        val document = response.asJsoup()
        return document.select(episodeListSelector()).map(::episodeFromElement)
    }

    /**
     * Returns the Jsoup selector that returns a list of [Element] corresponding to each episode.
     */
    protected abstract fun episodeListSelector(): String

    /**
     * Returns a episode from the given element.
     *
     * @param element an element obtained from [episodeListSelector].
     */
    protected abstract fun episodeFromElement(element: Element): SEpisode

    /**
     * Parses the response from the site and returns the page list.
     *
     * @param response the response from the site.
     */
    override fun videoListParse(response: Response): List<Video> {
        val document = response.asJsoup()
        return document.select(videoListSelector()).map(::videoFromElement)
    }

    /**
     * Returns the Jsoup selector that returns a list of [Element] corresponding to each video.
     */
    protected abstract fun videoListSelector(): String

    /**
     * Returns a video from the given element.
     *
     * @param element an element obtained from [videoListSelector].
     */
    protected abstract fun videoFromElement(element: Element): Video

    /**
     * Parse the response from the site and returns the absolute url to the source video.
     *
     * @param response the response from the site.
     */
    override fun videoUrlParse(response: Response): String = videoUrlParse(response.asJsoup())

    /**
     * Returns the absolute url to the source image from the document.
     *
     * @param document the parsed document.
     */
    protected abstract fun videoUrlParse(document: Document): String
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/online/ResolvableAnimeSource.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/online/ResolvableAnimeSource.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/online/ResolvableAnimeSource.kt).

The implementation below defines `ResolvableAnimeSource`, `getUriType`, `getAnime`, `getEpisode`, `UriType`, `Anime`, `Episode`, `Unknown`.

The source describes its contract as:

> A source that may handle opening an SAnime or SEpisode for a given URI.

```kotlin
package eu.kanade.tachiyomi.animesource.online

import eu.kanade.tachiyomi.animesource.AnimeSource
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode

/**
 * A source that may handle opening an SAnime or SEpisode for a given URI.
 *
 * @since extensions-lib 14
 */
interface ResolvableAnimeSource : AnimeSource {
    /**
     * Returns what the given URI may open.
     * Returns [UriType.Unknown] if the source is not able to resolve the URI.
     *
     * @since extensions-lib 14
     */
    fun getUriType(uri: String): UriType

    /**
     * Called if [getUriType] is [UriType.Anime].
     * Returns the corresponding SAnime, if possible.
     *
     * @since extensions-lib 14
     */
    suspend fun getAnime(uri: String): SAnime?

    /**
     * Called if [getUriType] is [UriType.Episode].
     * Returns the corresponding SEpisode, if possible.
     *
     * @since extensions-lib 14
     */
    suspend fun getEpisode(uri: String): SEpisode?
}

sealed interface UriType {
    data object Anime : UriType

    data object Episode : UriType

    data object Unknown : UriType
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/MemoryCookieJar.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/MemoryCookieJar.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/MemoryCookieJar.kt).

The implementation below defines `MemoryCookieJar`, `loadForRequest`, `saveFromResponse`, `clear`, `addCookie`, `addAll`, `WrappedCookie`, `unwrap`, `isExpired`, `matches` and 3 further declarations.

```kotlin
package eu.kanade.tachiyomi.network

import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl

class MemoryCookieJar : CookieJar {
    private val cache = mutableSetOf<WrappedCookie>()

    @Synchronized
    override fun loadForRequest(url: HttpUrl): List<Cookie> {
        val cookiesToRemove = mutableSetOf<WrappedCookie>()
        val validCookies = mutableSetOf<WrappedCookie>()

        cache.forEach { cookie ->
            if (cookie.isExpired()) {
                cookiesToRemove.add(cookie)
            } else if (cookie.matches(url)) {
                validCookies.add(cookie)
            }
        }

        cache.removeAll(cookiesToRemove)

        return validCookies.toList().map(WrappedCookie::unwrap)
    }

    @Synchronized
    override fun saveFromResponse(
        url: HttpUrl,
        cookies: List<Cookie>,
    ) {
        val cookiesToAdd = cookies.map { WrappedCookie.wrap(it) }

        cache.removeAll(cookiesToAdd)
        cache.addAll(cookiesToAdd)
    }

    @Synchronized
    fun clear() {
        cache.clear()
    }

    @Synchronized
    fun addCookie(cookie: Cookie) {
        val wrapped = WrappedCookie.wrap(cookie)
        cache.remove(wrapped)
        cache.add(wrapped)
    }

    @Synchronized
    fun addAll(
        url: HttpUrl,
        cookies: List<Cookie>,
    ) {
        cookies.forEach { addCookie(it) }
    }
}

class WrappedCookie private constructor(
    val cookie: Cookie,
) {
    fun unwrap() = cookie

    fun isExpired() = cookie.expiresAt < System.currentTimeMillis()

    fun matches(url: HttpUrl) = cookie.matches(url)

    override fun equals(other: Any?): Boolean {
        if (other !is WrappedCookie) return false

        return other.cookie.name == cookie.name &&
            other.cookie.domain == cookie.domain &&
            other.cookie.path == cookie.path &&
            other.cookie.secure == cookie.secure &&
            other.cookie.hostOnly == cookie.hostOnly
    }

    override fun hashCode(): Int {
        var hash = 17
        hash = 31 * hash + cookie.name.hashCode()
        hash = 31 * hash + cookie.domain.hashCode()
        hash = 31 * hash + cookie.path.hashCode()
        hash = 31 * hash + if (cookie.secure) 0 else 1
        hash = 31 * hash + if (cookie.hostOnly) 0 else 1
        return hash
    }

    companion object {
        fun wrap(cookie: Cookie) = WrappedCookie(cookie)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/NetworkHelper.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/NetworkHelper.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/NetworkHelper.kt).

The implementation below defines `NetworkHelper`, `setUA`, `defaultUserAgentProvider`.

```kotlin
package eu.kanade.tachiyomi.network

import android.content.Context
import eu.kanade.tachiyomi.network.interceptor.CloudflareInterceptor
import eu.kanade.tachiyomi.network.interceptor.IgnoreGzipInterceptor
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.brotli.BrotliInterceptor
import okhttp3.logging.HttpLoggingInterceptor
import java.nio.file.Files
import java.util.concurrent.TimeUnit

class NetworkHelper(
    val context: Context,
) {
    val cookieJar = MemoryCookieJar()

    val client by lazy {
        val builder =
            OkHttpClient
                .Builder()
                .cookieJar(cookieJar)
                .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .addNetworkInterceptor(IgnoreGzipInterceptor())
                .addNetworkInterceptor(BrotliInterceptor)
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .callTimeout(2, TimeUnit.MINUTES)
                .cache(
                    Cache(
                        directory = Files.createTempDirectory("m_network_cache").toFile(),
                        maxSize = 5L * 1024 * 1024, // 5 MiB
                    ),
                )
        builder.build()
    }

    val cloudflareClient by lazy {
        client
            .newBuilder()
            .addInterceptor(CloudflareInterceptor())
            .build()
    }

    private var defaultUserAgent: String = System.getProperty("http.agent").orEmpty()

    fun setUA(ua: String) {
        defaultUserAgent = ua
    }

    fun defaultUserAgentProvider() = defaultUserAgent
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/OkHttpExtensions.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/OkHttpExtensions.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/OkHttpExtensions.kt).

The implementation below defines `Call.await`, `onResponse`, `onFailure`, `Call.awaitSuccess`, `OkHttpClient.newCachelessCallWithProgress`, `Call.asObservable`, `request`, `unsubscribe`, `isUnsubscribed`, `Call.asObservableSuccess` and 4 further declarations.

```kotlin
package eu.kanade.tachiyomi.network

import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.suspendCancellableCoroutine
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Cookie
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import rx.Observable
import rx.Producer
import rx.Subscription
import java.io.IOException
import java.net.HttpCookie
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.coroutines.resumeWithException

// Based on https://github.com/gildor/kotlin-coroutines-okhttp
@OptIn(ExperimentalCoroutinesApi::class)
private suspend fun Call.await(callStack: Array<StackTraceElement>): Response {
    return suspendCancellableCoroutine { continuation ->
        val callback =
            object : Callback {
                override fun onResponse(
                    call: Call,
                    response: Response,
                ) {
                    continuation.resume(response) { cause, value, context ->
                        value.body.close()
                    }
                }

                override fun onFailure(
                    call: Call,
                    e: IOException,
                ) {
                    // Don't bother with resuming the continuation if it is already cancelled.
                    if (continuation.isCancelled) return
                    val exception = IOException(e.message, e).apply { stackTrace = callStack }
                    continuation.resumeWithException(exception)
                }
            }

        enqueue(callback)

        continuation.invokeOnCancellation {
            try {
                cancel()
            } catch (ex: Throwable) {
                // Ignore cancel exception
            }
        }
    }
}

suspend fun Call.await(): Response {
    val callStack = Exception().stackTrace.run { copyOfRange(1, size) }
    return await(callStack)
}

/**
 * @since extensions-lib 15
 */
suspend fun Call.awaitSuccess(): Response {
    val callStack = Exception().stackTrace.run { copyOfRange(1, size) }
    val response = await(callStack)
    if (!response.isSuccessful) {
        response.close()
        throw HttpException(response.code).apply { stackTrace = callStack }
    }
    return response
}

@Suppress("unused_parameter", "UnusedParameter")
fun OkHttpClient.newCachelessCallWithProgress(
    request: Request,
    listener: ProgressListener,
): Call {
    val progressClient =
        newBuilder()
            .cache(null)
            .build()

    return progressClient.newCall(request)
}

fun Call.asObservable(): Observable<Response> {
    return Observable.unsafeCreate { subscriber ->
        // Since Call is a one-shot type, clone it for each new subscriber.
        val call = clone()

        // Wrap the call in a helper which handles both unsubscription and backpressure.
        val requestArbiter =
            object : AtomicBoolean(), Producer, Subscription {
                override fun request(n: Long) {
                    if (n == 0L || !compareAndSet(false, true)) return

                    try {
                        val response = call.execute()
                        if (!subscriber.isUnsubscribed) {
                            subscriber.onNext(response)
                            subscriber.onCompleted()
                        }
                    } catch (e: Exception) {
                        if (!subscriber.isUnsubscribed) {
                            subscriber.onError(e)
                        }
                    }
                }

                override fun unsubscribe() {
                    call.cancel()
                }

                override fun isUnsubscribed(): Boolean = call.isCanceled()
            }

        subscriber.add(requestArbiter)
        subscriber.setProducer(requestArbiter)
    }
}

fun Call.asObservableSuccess(): Observable<Response> =
    asObservable().doOnNext { response ->
        if (!response.isSuccessful) {
            response.close()
            throw HttpException(response.code)
        }
    }

fun OkHttpClient.newCallWithProgress(
    request: Request,
    listener: ProgressListener,
): Call {
    val progressClient =
        newBuilder()
            .build()

    return progressClient.newCall(request)
}

class HttpException(
    val code: Int,
) : IllegalStateException("HTTP error $code")

fun Cookie.toHttpCookie(url: HttpUrl): HttpCookie {
    val httpCookie = HttpCookie(name, value)
    httpCookie.domain = domain
    httpCookie.path = path
    httpCookie.secure = secure
    // httpCookie.httpOnly = httpOnly // private field
    if (expiresAt != Long.MAX_VALUE) {
        httpCookie.maxAge = (expiresAt - System.currentTimeMillis()) / 1000
    }
    return httpCookie
}

fun HttpCookie.toCookie(url: HttpUrl): Cookie {
    val builder =
        Cookie
            .Builder()
            .name(name)
            .value(value)
    if (domain != null) builder.domain(domain)
    if (path != null) builder.path(path)
    if (secure) builder.secure()
    // if (httpOnly) builder.httpOnly() // private field
    if (maxAge > 0) {
        builder.expiresAt(System.currentTimeMillis() + maxAge * 1000)
    }
    return builder.build()
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/ProgressListener.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/ProgressListener.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/ProgressListener.kt).

The implementation below defines `ProgressListener`, `update`.

```kotlin
package eu.kanade.tachiyomi.network

interface ProgressListener {
    fun update(
        bytesRead: Long,
        contentLength: Long,
        done: Boolean,
    )
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/Requests.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/Requests.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/Requests.kt).

The implementation below defines `GET`, `POST`.

```kotlin
@file:Suppress("ktlint:standard:function-naming")

package eu.kanade.tachiyomi.network

import okhttp3.CacheControl
import okhttp3.FormBody
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.Request
import okhttp3.RequestBody
import java.util.concurrent.TimeUnit.MINUTES

private val DEFAULT_CACHE_CONTROL = CacheControl.Builder().maxAge(10, MINUTES).build()
private val DEFAULT_HEADERS = Headers.Builder().build()
private val DEFAULT_BODY: RequestBody = FormBody.Builder().build()

fun GET(
    url: String,
    headers: Headers = DEFAULT_HEADERS,
    cache: CacheControl = DEFAULT_CACHE_CONTROL,
): Request =
    Request
        .Builder()
        .url(url)
        .headers(headers)
        .cacheControl(cache)
        .build()

/**
 * @since extensions-lib 1.4
 */
fun GET(
    url: HttpUrl,
    headers: Headers = DEFAULT_HEADERS,
    cache: CacheControl = DEFAULT_CACHE_CONTROL,
): Request =
    Request
        .Builder()
        .url(url)
        .headers(headers)
        .cacheControl(cache)
        .build()

fun POST(
    url: String,
    headers: Headers = DEFAULT_HEADERS,
    body: RequestBody = DEFAULT_BODY,
    cache: CacheControl = DEFAULT_CACHE_CONTROL,
): Request =
    Request
        .Builder()
        .url(url)
        .post(body)
        .headers(headers)
        .cacheControl(cache)
        .build()
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/CloudflareInterceptor.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/CloudflareInterceptor.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/CloudflareInterceptor.kt).

The implementation below defines `CloudflareInterceptor`, `intercept`.

```kotlin
package eu.kanade.tachiyomi.network.interceptor

import okhttp3.Interceptor
import okhttp3.Response

class CloudflareInterceptor : Interceptor {
    @Synchronized
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()
        return chain.proceed(originalRequest)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/IgnoreGzipInterceptor.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/IgnoreGzipInterceptor.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/IgnoreGzipInterceptor.kt).

The implementation below defines `IgnoreGzipInterceptor`, `intercept`.

The source describes its contract as:

> To use \[okhttp3.brotli.BrotliInterceptor\] as a network interceptor, add \[IgnoreGzipInterceptor\] right before it. This nullifies the transparent gzip of \[okhttp3.internal.http.BridgeInterceptor\] so gzip and Brotli are explicitly handled by the \[okhttp3.brotli.BrotliInterceptor\].

```kotlin
package eu.kanade.tachiyomi.network.interceptor

import okhttp3.Interceptor
import okhttp3.Response

/**
 * To use [okhttp3.brotli.BrotliInterceptor] as a network interceptor,
 * add [IgnoreGzipInterceptor] right before it.
 *
 * This nullifies the transparent gzip of [okhttp3.internal.http.BridgeInterceptor]
 * so gzip and Brotli are explicitly handled by the [okhttp3.brotli.BrotliInterceptor].
 */
class IgnoreGzipInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        if (request.header("Accept-Encoding") == "gzip") {
            request = request.newBuilder().removeHeader("Accept-Encoding").build()
        }
        return chain.proceed(request)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/RateLimitInterceptor.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/RateLimitInterceptor.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/RateLimitInterceptor.kt).

The implementation below defines `OkHttpClient.Builder.rateLimit`, `RateLimitInterceptor`, `intercept`.

The source describes its contract as:

> An OkHttp interceptor that handles rate limiting. Examples: permits = 5,  period = 1, unit = seconds  =\>  5 requests per second permits = 10, period = 2, unit = minutes  =\>  10 requests per 2 minutes

```kotlin
package eu.kanade.tachiyomi.network.interceptor

import android.os.SystemClock
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import java.util.concurrent.TimeUnit

/**
 * An OkHttp interceptor that handles rate limiting.
 *
 * Examples:
 *
 * permits = 5,  period = 1, unit = seconds  =>  5 requests per second
 * permits = 10, period = 2, unit = minutes  =>  10 requests per 2 minutes
 *
 * @since extension-lib 1.3
 *
 * @param permits {Int}   Number of requests allowed within a period of units.
 * @param period {Long}   The limiting duration. Defaults to 1.
 * @param unit {TimeUnit} The unit of time for the period. Defaults to seconds.
 */
fun OkHttpClient.Builder.rateLimit(
    permits: Int,
    period: Long = 1,
    unit: TimeUnit = TimeUnit.SECONDS,
) = addInterceptor(RateLimitInterceptor(permits, period, unit))

private class RateLimitInterceptor(
    private val permits: Int,
    period: Long,
    unit: TimeUnit,
) : Interceptor {
    private val requestQueue = ArrayList<Long>(permits)
    private val rateLimitMillis = unit.toMillis(period)

    override fun intercept(chain: Interceptor.Chain): Response {
        synchronized(requestQueue) {
            val now = SystemClock.elapsedRealtime()
            val waitTime =
                if (requestQueue.size < permits) {
                    0
                } else {
                    val oldestReq = requestQueue[0]
                    val newestReq = requestQueue[permits - 1]

                    if (newestReq - oldestReq > rateLimitMillis) {
                        0
                    } else {
                        oldestReq + rateLimitMillis - now // Remaining time
                    }
                }

            if (requestQueue.size == permits) {
                requestQueue.removeAt(0)
            }
            if (waitTime > 0) {
                requestQueue.add(now + waitTime)
                Thread.sleep(waitTime) // Sleep inside synchronized to pause queued requests
            } else {
                requestQueue.add(now)
            }
        }

        return chain.proceed(chain.request())
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/SpecificHostRateLimitInterceptor.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/SpecificHostRateLimitInterceptor.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/SpecificHostRateLimitInterceptor.kt).

The implementation below defines `OkHttpClient.Builder.rateLimitHost`, `SpecificHostRateLimitInterceptor`, `intercept`.

The source describes its contract as:

> An OkHttp interceptor that handles given url host's rate limiting. Examples: httpUrl = "api.manga.com".toHttpUrlOrNull(), permits = 5, period = 1, unit = seconds  =\>  5 requests per second to api.manga.com httpUrl = "imagecdn.manga.com".toHttpUrlOrNull(), permits = 10, period = 2, unit = minutes  =\>  10 requests per 2 minutes to imagecdn.manga.com

```kotlin
package eu.kanade.tachiyomi.network.interceptor

import android.os.SystemClock
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import java.util.concurrent.TimeUnit

/**
 * An OkHttp interceptor that handles given url host's rate limiting.
 *
 * Examples:
 *
 * httpUrl = "api.manga.com".toHttpUrlOrNull(), permits = 5, period = 1, unit = seconds  =>  5 requests per second to api.manga.com
 * httpUrl = "imagecdn.manga.com".toHttpUrlOrNull(), permits = 10, period = 2, unit = minutes  =>  10 requests per 2 minutes to imagecdn.manga.com
 *
 * @since extension-lib 1.3
 *
 * @param httpUrl {HttpUrl} The url host that this interceptor should handle. Will get url's host by using HttpUrl.host()
 * @param permits {Int}   Number of requests allowed within a period of units.
 * @param period {Long}   The limiting duration. Defaults to 1.
 * @param unit {TimeUnit} The unit of time for the period. Defaults to seconds.
 */
fun OkHttpClient.Builder.rateLimitHost(
    httpUrl: HttpUrl,
    permits: Int,
    period: Long = 1,
    unit: TimeUnit = TimeUnit.SECONDS,
) = addInterceptor(SpecificHostRateLimitInterceptor(httpUrl, permits, period, unit))

class SpecificHostRateLimitInterceptor(
    httpUrl: HttpUrl,
    private val permits: Int,
    period: Long,
    unit: TimeUnit,
) : Interceptor {
    private val requestQueue = ArrayList<Long>(permits)
    private val rateLimitMillis = unit.toMillis(period)
    private val host = httpUrl.host

    override fun intercept(chain: Interceptor.Chain): Response {
        if (chain.request().url.host != host) {
            return chain.proceed(chain.request())
        }
        synchronized(requestQueue) {
            val now = SystemClock.elapsedRealtime()
            val waitTime =
                if (requestQueue.size < permits) {
                    0
                } else {
                    val oldestReq = requestQueue[0]
                    val newestReq = requestQueue[permits - 1]

                    if (newestReq - oldestReq > rateLimitMillis) {
                        0
                    } else {
                        oldestReq + rateLimitMillis - now // Remaining time
                    }
                }

            if (requestQueue.size == permits) {
                requestQueue.removeAt(0)
            }
            if (waitTime > 0) {
                requestQueue.add(now + waitTime)
                Thread.sleep(waitTime) // Sleep inside synchronized to pause queued requests
            } else {
                requestQueue.add(now)
            }
        }

        return chain.proceed(chain.request())
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/CatalogueSource.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/CatalogueSource.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/CatalogueSource.kt).

The implementation below defines `CatalogueSource`, `getPopularManga`, `getSearchManga`, `getLatestUpdates`, `getFilterList`, `fetchPopularManga`, `fetchSearchManga`, `fetchLatestUpdates`.

The source describes its contract as:

> An ISO 639-1 compliant language code (two letters in lower case).

```kotlin
package eu.kanade.tachiyomi.source

import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.util.lang.awaitSingle
import rx.Observable

interface CatalogueSource : Source {
    /**
     * An ISO 639-1 compliant language code (two letters in lower case).
     */
    override val lang: String

    /**
     * Whether the source has support for latest updates.
     */
    val supportsLatest: Boolean

    /**
     * Get a page with a list of manga.
     *
     * @since extensions-lib 1.5
     * @param page the page number to retrieve.
     */
    @Suppress("DEPRECATION")
    suspend fun getPopularManga(page: Int): MangasPage = fetchPopularManga(page).awaitSingle()

    /**
     * Get a page with a list of manga.
     *
     * @since extensions-lib 1.5
     * @param page the page number to retrieve.
     * @param query the search query.
     * @param filters the list of filters to apply.
     */
    @Suppress("DEPRECATION")
    suspend fun getSearchManga(
        page: Int,
        query: String,
        filters: FilterList,
    ): MangasPage = fetchSearchManga(page, query, filters).awaitSingle()

    /**
     * Get a page with a list of latest manga updates.
     *
     * @since extensions-lib 1.5
     * @param page the page number to retrieve.
     */
    @Suppress("DEPRECATION")
    suspend fun getLatestUpdates(page: Int): MangasPage = fetchLatestUpdates(page).awaitSingle()

    /**
     * Returns the list of filters for the source.
     */
    fun getFilterList(): FilterList

    @Deprecated(
        "Use the non-RxJava API instead",
        ReplaceWith("getPopularManga"),
    )
    fun fetchPopularManga(page: Int): Observable<MangasPage> = throw IllegalStateException("Not used")

    @Deprecated(
        "Use the non-RxJava API instead",
        ReplaceWith("getSearchManga"),
    )
    fun fetchSearchManga(
        page: Int,
        query: String,
        filters: FilterList,
    ): Observable<MangasPage> = throw IllegalStateException("Not used")

    @Deprecated(
        "Use the non-RxJava API instead",
        ReplaceWith("getLatestUpdates"),
    )
    fun fetchLatestUpdates(page: Int): Observable<MangasPage> = throw IllegalStateException("Not used")
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/ConfigurableSource.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/ConfigurableSource.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/ConfigurableSource.kt).

The implementation below defines `ConfigurableSource`, `setupPreferenceScreen`.

```kotlin
package eu.kanade.tachiyomi.source

import androidx.preference.PreferenceScreen

interface ConfigurableSource : Source {
    fun setupPreferenceScreen(screen: PreferenceScreen)
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/LocalSource.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/LocalSource.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/LocalSource.kt).

The implementation below defines `LocalSource`, `fetchMangaDetails`, `fetchChapterList`, `fetchPageList`, `fetchPopularManga`, `fetchSearchManga`, `fetchLatestUpdates`, `getFilterList`.

```kotlin
package eu.kanade.tachiyomi.source

import android.content.Context
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import rx.Observable

class LocalSource(
    private val context: Context,
) : CatalogueSource {
    companion object {
        const val ID = 0L
    }

    override val id = ID
    override val name = "Local source"
    override val lang = ""
    override val supportsLatest = true

    override fun fetchMangaDetails(manga: SManga): Observable<SManga> {
        TODO("Not yet implemented")
    }

    override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> {
        TODO("Not yet implemented")
    }

    override fun fetchPageList(chapter: SChapter): Observable<List<Page>> {
        TODO("Not yet implemented")
    }

    override fun fetchPopularManga(page: Int): Observable<MangasPage> {
        TODO("Not yet implemented")
    }

    override fun fetchSearchManga(
        page: Int,
        query: String,
        filters: FilterList,
    ): Observable<MangasPage> {
        TODO("Not yet implemented")
    }

    override fun fetchLatestUpdates(page: Int): Observable<MangasPage> {
        TODO("Not yet implemented")
    }

    override fun getFilterList(): FilterList {
        TODO("Not yet implemented")
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/Source.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/Source.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/Source.kt).

The implementation below defines `Source`, `getMangaDetails`, `getChapterList`, `getPageList`, `fetchMangaDetails`, `fetchChapterList`, `fetchPageList`.

The source describes its contract as:

> A basic interface for creating a source. It could be an online source, a local source, etc.

```kotlin
package eu.kanade.tachiyomi.source

import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.util.lang.awaitSingle
import rx.Observable

/**
 * A basic interface for creating a source. It could be an online source, a local source, etc.
 */
interface Source {
    /**
     * ID for the source. Must be unique.
     */
    val id: Long

    /**
     * Name of the source.
     */
    val name: String

    val lang: String
        get() = ""

    /**
     * Get the updated details for a manga.
     *
     * @since extensions-lib 1.5
     * @param manga the manga to update.
     * @return the updated manga.
     */
    @Suppress("DEPRECATION")
    suspend fun getMangaDetails(manga: SManga): SManga = fetchMangaDetails(manga).awaitSingle()

    /**
     * Get all the available chapters for a manga.
     *
     * @since extensions-lib 1.5
     * @param manga the manga to update.
     * @return the chapters for the manga.
     */
    @Suppress("DEPRECATION")
    suspend fun getChapterList(manga: SManga): List<SChapter> = fetchChapterList(manga).awaitSingle()

    /**
     * Get the list of pages a chapter has. Pages should be returned
     * in the expected order; the index is ignored.
     *
     * @since extensions-lib 1.5
     * @param chapter the chapter.
     * @return the pages for the chapter.
     */
    @Suppress("DEPRECATION")
    suspend fun getPageList(chapter: SChapter): List<Page> = fetchPageList(chapter).awaitSingle()

    @Deprecated(
        "Use the non-RxJava API instead",
        ReplaceWith("getMangaDetails"),
    )
    fun fetchMangaDetails(manga: SManga): Observable<SManga> = throw IllegalStateException("Not used")

    @Deprecated(
        "Use the non-RxJava API instead",
        ReplaceWith("getChapterList"),
    )
    fun fetchChapterList(manga: SManga): Observable<List<SChapter>> = throw IllegalStateException("Not used")

    @Deprecated(
        "Use the non-RxJava API instead",
        ReplaceWith("getPageList"),
    )
    fun fetchPageList(chapter: SChapter): Observable<List<Page>> = throw IllegalStateException("Not used")
}

// fun Source.icon(): Drawable? = Injekt.get<ExtensionManager>().getAppIconForSource(this)
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/SourceFactory.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/SourceFactory.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/SourceFactory.kt).

The implementation below defines `SourceFactory`, `createSources`.

The source describes its contract as:

> A factory for creating sources at runtime.

```kotlin
package eu.kanade.tachiyomi.source

/**
 * A factory for creating sources at runtime.
 */
interface SourceFactory {
    /**
     * Create a new copy of the sources
     * @return The created sources
     */
    fun createSources(): List<Source>
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/SourceManager.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/SourceManager.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/SourceManager.kt).

The implementation below defines `SourceManager`, `get`, `getOrStub`, `getOnlineSources`, `getCatalogueSources`, `registerSource`, `unregisterSource`, `createInternalSources`, `fetchMangaDetails`, `fetchChapterList` and 3 further declarations.

```kotlin
package eu.kanade.tachiyomi.source

import android.content.Context
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import rx.Observable

open class SourceManager(
    private val context: Context,
) {
    private val sourcesMap = mutableMapOf<Long, Source>()

    private val stubSourcesMap = mutableMapOf<Long, StubSource>()

    init {
        createInternalSources().forEach { registerSource(it) }
    }

    open fun get(sourceKey: Long): Source? = sourcesMap[sourceKey]

    fun getOrStub(sourceKey: Long): Source =
        sourcesMap[sourceKey] ?: stubSourcesMap.getOrPut(sourceKey) {
            StubSource(sourceKey)
        }

    fun getOnlineSources() = sourcesMap.values.filterIsInstance<HttpSource>()

    fun getCatalogueSources() = sourcesMap.values.filterIsInstance<CatalogueSource>()

    internal fun registerSource(
        source: Source,
        overwrite: Boolean = false,
    ) {
        if (overwrite || !sourcesMap.containsKey(source.id)) {
            sourcesMap[source.id] = source
        }
        if (overwrite || !stubSourcesMap.containsKey(source.id)) {
            stubSourcesMap[source.id] = StubSource(source.id)
        }
    }

    internal fun unregisterSource(source: Source) {
        sourcesMap.remove(source.id)
    }

    private fun createInternalSources(): List<Source> =
        listOf(
//        LocalSource(context)
        )

    private inner class StubSource(
        override val id: Long,
    ) : Source {
        override val name: String
            get() = id.toString()

        override fun fetchMangaDetails(manga: SManga): Observable<SManga> = Observable.error(getSourceNotInstalledException())

        override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> = Observable.error(getSourceNotInstalledException())

        override fun fetchPageList(chapter: SChapter): Observable<List<Page>> = Observable.error(getSourceNotInstalledException())

        override fun toString(): String = name

        private fun getSourceNotInstalledException(): Exception = Exception("source not found")
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/UnmeteredSource.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/UnmeteredSource.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/UnmeteredSource.kt).

The implementation below defines `UnmeteredSource`.

The source describes its contract as:

> A source that explicitly doesn't require traffic considerations. This typically applies for self-hosted sources.

```kotlin
package eu.kanade.tachiyomi.source

/**
 * A source that explicitly doesn't require traffic considerations.
 *
 * This typically applies for self-hosted sources.
 */
interface UnmeteredSource
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/Filter.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/Filter.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/Filter.kt).

The implementation below defines `Filter`, `Header`, `Separator`, `Select`, `Text`, `CheckBox`, `TriState`, `isIgnored`, `isIncluded`, `isExcluded` and 5 further declarations.

```kotlin
package eu.kanade.tachiyomi.source.model

sealed class Filter<T>(
    val name: String,
    var state: T,
) {
    open class Header(
        name: String,
    ) : Filter<Any>(name, 0)

    open class Separator(
        name: String = "",
    ) : Filter<Any>(name, 0)

    abstract class Select<V>(
        name: String,
        val values: Array<V>,
        state: Int = 0,
    ) : Filter<Int>(name, state)

    abstract class Text(
        name: String,
        state: String = "",
    ) : Filter<String>(name, state)

    abstract class CheckBox(
        name: String,
        state: Boolean = false,
    ) : Filter<Boolean>(name, state)

    abstract class TriState(
        name: String,
        state: Int = STATE_IGNORE,
    ) : Filter<Int>(name, state) {
        fun isIgnored() = state == STATE_IGNORE

        fun isIncluded() = state == STATE_INCLUDE

        fun isExcluded() = state == STATE_EXCLUDE

        companion object {
            const val STATE_IGNORE = 0
            const val STATE_INCLUDE = 1
            const val STATE_EXCLUDE = 2
        }
    }

    abstract class Group<V>(
        name: String,
        state: List<V>,
    ) : Filter<List<V>>(name, state)

    abstract class Sort(
        name: String,
        val values: Array<String>,
        state: Selection? = null,
    ) : Filter<Sort.Selection?>(name, state) {
        data class Selection(
            val index: Int,
            val ascending: Boolean,
        )
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is Filter<*>) return false

        return name == other.name && state == other.state
    }

    override fun hashCode(): Int {
        var result = name.hashCode()
        result = 31 * result + (state?.hashCode() ?: 0)
        return result
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/FilterList.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/FilterList.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/FilterList.kt).

The implementation below defines `FilterList`.

```kotlin
package eu.kanade.tachiyomi.source.model

data class FilterList(
    val list: List<Filter<*>>,
) : List<Filter<*>> by list {
    constructor(vararg fs: Filter<*>) : this(if (fs.isNotEmpty()) fs.asList() else emptyList())
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/MangasPage.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/MangasPage.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/MangasPage.kt).

The implementation below defines `MangasPage`.

```kotlin
package eu.kanade.tachiyomi.source.model

data class MangasPage(
    val mangas: List<SManga>,
    val hasNextPage: Boolean,
)
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/Page.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/Page.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/Page.kt).

The implementation below defines `Page`, `update`, `setStatusSubject`, `setStatusCallback`.

```kotlin
package eu.kanade.tachiyomi.source.model

import android.net.Uri
import eu.kanade.tachiyomi.network.ProgressListener
import rx.subjects.Subject

open class Page(
    val index: Int,
    val url: String = "",
    var imageUrl: String? = null,
    @Transient var uri: Uri? = null, // Deprecated but can't be deleted due to extensions
) : ProgressListener {
    val number: Int
        get() = index + 1

    @Transient
    @Volatile
    var status: Int = 0
        set(value) {
            field = value
            statusSubject?.onNext(value)
            statusCallback?.invoke(this)
        }

    @Transient
    @Volatile
    var progress: Int = 0
        set(value) {
            field = value
            statusCallback?.invoke(this)
        }

    @Transient
    private var statusSubject: Subject<Int, Int>? = null

    @Transient
    private var statusCallback: ((Page) -> Unit)? = null

    override fun update(
        bytesRead: Long,
        contentLength: Long,
        done: Boolean,
    ) {
        progress =
            if (contentLength > 0) {
                (100 * bytesRead / contentLength).toInt()
            } else {
                -1
            }
    }

    fun setStatusSubject(subject: Subject<Int, Int>?) {
        this.statusSubject = subject
    }

    fun setStatusCallback(f: ((Page) -> Unit)?) {
        statusCallback = f
    }

    companion object {
        const val QUEUE = 0
        const val LOAD_PAGE = 1
        const val DOWNLOAD_IMAGE = 2
        const val READY = 3
        const val ERROR = 4
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SChapter.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SChapter.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SChapter.kt).

The implementation below defines `SChapter`, `copyFrom`, `create`.

```kotlin
@file:Suppress("ktlint:standard:property-naming")

package eu.kanade.tachiyomi.source.model

import java.io.Serializable

interface SChapter : Serializable {
    var url: String

    var name: String

    var date_upload: Long

    var chapter_number: Float

    var scanlator: String?

    fun copyFrom(other: SChapter) {
        name = other.name
        url = other.url
        date_upload = other.date_upload
        chapter_number = other.chapter_number
        scanlator = other.scanlator
    }

    companion object {
        fun create(): SChapter = SChapterImpl()
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SChapterImpl.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SChapterImpl.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SChapterImpl.kt).

The implementation below defines `SChapterImpl`.

```kotlin
@file:Suppress("ktlint:standard:property-naming")

package eu.kanade.tachiyomi.source.model

class SChapterImpl : SChapter {
    override lateinit var url: String

    override lateinit var name: String

    override var date_upload: Long = 0

    override var chapter_number: Float = -1f

    override var scanlator: String? = null
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SManga.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SManga.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SManga.kt).

The implementation below defines `SManga`, `copyFrom`, `create`.

```kotlin
@file:Suppress("ktlint:standard:property-naming")

package eu.kanade.tachiyomi.source.model

import java.io.Serializable

interface SManga : Serializable {
    var url: String

    var title: String

    var artist: String?

    var author: String?

    var description: String?

    var genre: String?

    var status: Int

    var thumbnail_url: String?

    var update_strategy: UpdateStrategy

    var initialized: Boolean

    fun copyFrom(other: SManga) {
        if (other.author != null) {
            author = other.author
        }

        if (other.artist != null) {
            artist = other.artist
        }

        if (other.description != null) {
            description = other.description
        }

        if (other.genre != null) {
            genre = other.genre
        }

        if (other.thumbnail_url != null) {
            thumbnail_url = other.thumbnail_url
        }

        status = other.status

        if (!initialized) {
            initialized = other.initialized
        }
    }

    companion object {
        const val UNKNOWN = 0
        const val ONGOING = 1
        const val COMPLETED = 2
        const val LICENSED = 3
        const val PUBLISHING_FINISHED = 4
        const val CANCELLED = 5
        const val ON_HIATUS = 6

        fun create(): SManga = SMangaImpl()
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SMangaImpl.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SMangaImpl.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SMangaImpl.kt).

The implementation below defines `SMangaImpl`.

```kotlin
@file:Suppress("ktlint:standard:property-naming")

package eu.kanade.tachiyomi.source.model

class SMangaImpl : SManga {
    override lateinit var url: String

    override lateinit var title: String

    override var artist: String? = null

    override var author: String? = null

    override var description: String? = null

    override var genre: String? = null

    override var status: Int = 0

    override var thumbnail_url: String? = null

    override var update_strategy: UpdateStrategy = UpdateStrategy.ALWAYS_UPDATE

    override var initialized: Boolean = false
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/UpdateStrategy.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/UpdateStrategy.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/UpdateStrategy.kt).

The implementation below defines `UpdateStrategy`.

```kotlin
package eu.kanade.tachiyomi.source.model

enum class UpdateStrategy {
    ALWAYS_UPDATE,
    ONLY_FETCH_ONCE,
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/online/HttpSource.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/online/HttpSource.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/online/HttpSource.kt).

The implementation below defines `HttpSource`, `headersBuilder`, `toString`, `fetchPopularManga`, `popularMangaRequest`, `popularMangaParse`, `fetchSearchManga`, `searchMangaRequest`, `searchMangaParse`, `fetchLatestUpdates` and 23 further declarations.

The source describes its contract as:

> A simple implementation for sources from a website.

```kotlin
package eu.kanade.tachiyomi.source.online

import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.NetworkHelper
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.network.newCallWithProgress
import eu.kanade.tachiyomi.source.CatalogueSource
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import rx.Observable
import uy.kohesive.injekt.injectLazy
import java.net.URI
import java.net.URISyntaxException
import java.security.MessageDigest

/**
 * A simple implementation for sources from a website.
 */
abstract class HttpSource : CatalogueSource {
    /**
     * Network service.
     */
    val network: NetworkHelper by injectLazy()

//    /**
//     * Preferences that a source may need.
//     */
//    val preferences: SharedPreferences by lazy {
//        Injekt.get<Application>().getSharedPreferences(source.getPreferenceKey(), Context.MODE_PRIVATE)
//    }

    /**
     * Base url of the website without the trailing slash, like: http://mysite.com
     */
    abstract val baseUrl: String

    /**
     * Version id used to generate the source id. If the site completely changes and urls are
     * incompatible, you may increase this value and it'll be considered as a new source.
     */
    open val versionId = 1

    /**
     * Id of the source. By default it uses a generated id using the first 16 characters (64 bits)
     * of the MD5 of the string: sourcename/language/versionId
     * Note the generated id sets the sign bit to 0.
     */
    override val id by lazy {
        val key = "${name.lowercase()}/$lang/$versionId"
        val bytes = MessageDigest.getInstance("MD5").digest(key.toByteArray())
        (0..7)
            .map { bytes[it].toLong() and 0xff shl 8 * (7 - it) }
            .reduce(Long::or) and Long.MAX_VALUE
    }

    /**
     * Headers used for requests.
     */
    val headers: Headers by lazy { headersBuilder().build() }

    /**
     * Default network client for doing requests.
     */
    open val client: OkHttpClient
        get() = network.client

    /**
     * Headers builder for requests. Implementations can override this method for custom headers.
     */
    protected open fun headersBuilder() =
        Headers.Builder().apply {
            add("User-Agent", network.defaultUserAgentProvider())
        }

    /**
     * Visible name of the source.
     */
    override fun toString() = "$name (${lang.uppercase()})"

    /**
     * Returns an observable containing a page with a list of manga. Normally it's not needed to
     * override this method.
     *
     * @param page the page number to retrieve.
     */
    override fun fetchPopularManga(page: Int): Observable<MangasPage> =
        client
            .newCall(popularMangaRequest(page))
            .asObservableSuccess()
            .map { response ->
                popularMangaParse(response)
            }

    /**
     * Returns the request for the popular manga given the page.
     *
     * @param page the page number to retrieve.
     */
    protected abstract fun popularMangaRequest(page: Int): Request

    /**
     * Parses the response from the site and returns a [MangasPage] object.
     *
     * @param response the response from the site.
     */
    protected abstract fun popularMangaParse(response: Response): MangasPage

    /**
     * Returns an observable containing a page with a list of manga. Normally it's not needed to
     * override this method.
     *
     * @param page the page number to retrieve.
     * @param query the search query.
     * @param filters the list of filters to apply.
     */
    override fun fetchSearchManga(
        page: Int,
        query: String,
        filters: FilterList,
    ): Observable<MangasPage> =
        client
            .newCall(searchMangaRequest(page, query, filters))
            .asObservableSuccess()
            .map { response ->
                searchMangaParse(response)
            }

    /**
     * Returns the request for the search manga given the page.
     *
     * @param page the page number to retrieve.
     * @param query the search query.
     * @param filters the list of filters to apply.
     */
    protected abstract fun searchMangaRequest(
        page: Int,
        query: String,
        filters: FilterList,
    ): Request

    /**
     * Parses the response from the site and returns a [MangasPage] object.
     *
     * @param response the response from the site.
     */
    protected abstract fun searchMangaParse(response: Response): MangasPage

    /**
     * Returns an observable containing a page with a list of latest manga updates.
     *
     * @param page the page number to retrieve.
     */
    override fun fetchLatestUpdates(page: Int): Observable<MangasPage> =
        client
            .newCall(latestUpdatesRequest(page))
            .asObservableSuccess()
            .map { response ->
                latestUpdatesParse(response)
            }

    /**
     * Returns the request for latest manga given the page.
     *
     * @param page the page number to retrieve.
     */
    protected abstract fun latestUpdatesRequest(page: Int): Request

    /**
     * Parses the response from the site and returns a [MangasPage] object.
     *
     * @param response the response from the site.
     */
    protected abstract fun latestUpdatesParse(response: Response): MangasPage

    /**
     * Returns an observable with the updated details for a manga. Normally it's not needed to
     * override this method.
     *
     * @param manga the manga to be updated.
     */
    override fun fetchMangaDetails(manga: SManga): Observable<SManga> =
        client
            .newCall(mangaDetailsRequest(manga))
            .asObservableSuccess()
            .map { response ->
                mangaDetailsParse(response).apply { initialized = true }
            }

    /**
     * Returns the request for the details of a manga. Override only if it's needed to change the
     * url, send different headers or request method like POST.
     *
     * @param manga the manga to be updated.
     */
    open fun mangaDetailsRequest(manga: SManga): Request = GET(baseUrl + manga.url, headers)

    /**
     * Parses the response from the site and returns the details of a manga.
     *
     * @param response the response from the site.
     */
    protected abstract fun mangaDetailsParse(response: Response): SManga

    /**
     * Returns an observable with the updated chapter list for a manga. Normally it's not needed to
     * override this method.  If a manga is licensed an empty chapter list observable is returned
     *
     * @param manga the manga to look for chapters.
     */
    override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> =
        if (manga.status != SManga.LICENSED) {
            client
                .newCall(chapterListRequest(manga))
                .asObservableSuccess()
                .map { response ->
                    chapterListParse(response)
                }
        } else {
            Observable.error(Exception("Licensed - No chapters to show"))
        }

    /**
     * Returns the request for updating the chapter list. Override only if it's needed to override
     * the url, send different headers or request method like POST.
     *
     * @param manga the manga to look for chapters.
     */
    protected open fun chapterListRequest(manga: SManga): Request = GET(baseUrl + manga.url, headers)

    /**
     * Parses the response from the site and returns a list of chapters.
     *
     * @param response the response from the site.
     */
    protected abstract fun chapterListParse(response: Response): List<SChapter>

    /**
     * Returns an observable with the page list for a chapter.
     *
     * @param chapter the chapter whose page list has to be fetched.
     */
    override fun fetchPageList(chapter: SChapter): Observable<List<Page>> =
        client
            .newCall(pageListRequest(chapter))
            .asObservableSuccess()
            .map { response ->
                pageListParse(response)
            }

    /**
     * Returns the request for getting the page list. Override only if it's needed to override the
     * url, send different headers or request method like POST.
     *
     * @param chapter the chapter whose page list has to be fetched.
     */
    protected open fun pageListRequest(chapter: SChapter): Request = GET(baseUrl + chapter.url, headers)

    /**
     * Parses the response from the site and returns a list of pages.
     *
     * @param response the response from the site.
     */
    protected abstract fun pageListParse(response: Response): List<Page>

    /**
     * Returns an observable with the page containing the source url of the image. If there's any
     * error, it will return null instead of throwing an exception.
     *
     * @param page the page whose source image has to be fetched.
     */
    open fun fetchImageUrl(page: Page): Observable<String> =
        client
            .newCall(imageUrlRequest(page))
            .asObservableSuccess()
            .map { imageUrlParse(it) }

    /**
     * Returns the request for getting the url to the source image. Override only if it's needed to
     * override the url, send different headers or request method like POST.
     *
     * @param page the chapter whose page list has to be fetched
     */
    protected open fun imageUrlRequest(page: Page): Request = GET(page.url, headers)

    /**
     * Parses the response from the site and returns the absolute url to the source image.
     *
     * @param response the response from the site.
     */
    protected abstract fun imageUrlParse(response: Response): String

    /**
     * Returns an observable with the response of the source image.
     *
     * @param page the page whose source image has to be downloaded.
     */
    fun fetchImage(page: Page): Observable<Response> =
        client
            .newCallWithProgress(imageRequest(page), page)
            .asObservableSuccess()

    /**
     * Returns the request for getting the source image. Override only if it's needed to override
     * the url, send different headers or request method like POST.
     *
     * @param page the chapter whose page list has to be fetched
     */
    open fun imageRequest(page: Page): Request = GET(page.imageUrl!!, headers)

    /**
     * Assigns the url of the chapter without the scheme and domain. It saves some redundancy from
     * database and the urls could still work after a domain change.
     *
     * @param url the full url to the chapter.
     */
    fun SChapter.setUrlWithoutDomain(url: String) {
        this.url = getUrlWithoutDomain(url)
    }

    /**
     * Assigns the url of the manga without the scheme and domain. It saves some redundancy from
     * database and the urls could still work after a domain change.
     *
     * @param url the full url to the manga.
     */
    fun SManga.setUrlWithoutDomain(url: String) {
        this.url = getUrlWithoutDomain(url)
    }

    /**
     * Returns the url of the given string without the scheme and domain.
     *
     * @param orig the full url.
     */
    private fun getUrlWithoutDomain(orig: String): String =
        try {
            val uri = URI(orig)
            var out = uri.path
            if (uri.query != null) {
                out += "?" + uri.query
            }
            if (uri.fragment != null) {
                out += "#" + uri.fragment
            }
            out
        } catch (e: URISyntaxException) {
            orig
        }

    /**
     * Returns the url of the provided manga
     *
     * @since extensions-lib 1.4
     * @param manga the manga
     * @return url of the manga
     */
    open fun getMangaUrl(manga: SManga): String = mangaDetailsRequest(manga).url.toString()

    /**
     * Returns the url of the provided chapter
     *
     * @since extensions-lib 1.4
     * @param chapter the chapter
     * @return url of the chapter
     */
    open fun getChapterUrl(chapter: SChapter): String = pageListRequest(chapter).url.toString()

    /**
     * Called before inserting a new chapter into database. Use it if you need to override chapter
     * fields, like the title or the chapter number. Do not change anything to [manga].
     *
     * @param chapter the chapter to be added.
     * @param manga the manga of the chapter.
     */
    open fun prepareNewChapter(
        chapter: SChapter,
        manga: SManga,
    ) {}

    /**
     * Returns the list of filters for the source.
     */
    override fun getFilterList() = FilterList()
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/online/HttpSourceFetcher.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/online/HttpSourceFetcher.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/online/HttpSourceFetcher.kt).

The implementation below defines `HttpSource.getImageUrl`, `HttpSource.fetchAllImageUrlsFromPageList`, `HttpSource.fetchRemainingImageUrlsFromPageList`.

```kotlin
package eu.kanade.tachiyomi.source.online

import eu.kanade.tachiyomi.source.model.Page
import rx.Observable

fun HttpSource.getImageUrl(page: Page): Observable<Page> {
    page.status = Page.LOAD_PAGE
    return fetchImageUrl(page)
        .doOnError { page.status = Page.ERROR }
        .onErrorReturn { null }
        .doOnNext { page.imageUrl = it }
        .map { page }
}

fun HttpSource.fetchAllImageUrlsFromPageList(pages: List<Page>): Observable<Page> =
    Observable
        .from(pages)
        .filter { !it.imageUrl.isNullOrEmpty() }
        .mergeWith(fetchRemainingImageUrlsFromPageList(pages))

fun HttpSource.fetchRemainingImageUrlsFromPageList(pages: List<Page>): Observable<Page> =
    Observable
        .from(pages)
        .filter { it.imageUrl.isNullOrEmpty() }
        .concatMap { getImageUrl(it) }
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/online/ParsedHttpSource.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/online/ParsedHttpSource.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/online/ParsedHttpSource.kt).

The implementation below defines `ParsedHttpSource`, `popularMangaParse`, `popularMangaSelector`, `popularMangaFromElement`, `popularMangaNextPageSelector`, `searchMangaParse`, `searchMangaSelector`, `searchMangaFromElement`, `searchMangaNextPageSelector`, `latestUpdatesParse` and 9 further declarations.

The source describes its contract as:

> A simple implementation for sources from a website using Jsoup, an HTML parser.

```kotlin
package eu.kanade.tachiyomi.source.online

import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element

/**
 * A simple implementation for sources from a website using Jsoup, an HTML parser.
 */
abstract class ParsedHttpSource : HttpSource() {
    /**
     * Parses the response from the site and returns a [MangasPage] object.
     *
     * @param response the response from the site.
     */
    override fun popularMangaParse(response: Response): MangasPage {
        val document = response.asJsoup()

        val mangas =
            document.select(popularMangaSelector()).map { element ->
                popularMangaFromElement(element)
            }

        val hasNextPage =
            popularMangaNextPageSelector()?.let { selector ->
                document.select(selector).first()
            } != null

        return MangasPage(mangas, hasNextPage)
    }

    /**
     * Returns the Jsoup selector that returns a list of [Element] corresponding to each manga.
     */
    protected abstract fun popularMangaSelector(): String

    /**
     * Returns a manga from the given [element]. Most sites only show the title and the url, it's
     * totally fine to fill only those two values.
     *
     * @param element an element obtained from [popularMangaSelector].
     */
    protected abstract fun popularMangaFromElement(element: Element): SManga

    /**
     * Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
     * there's no next page.
     */
    protected abstract fun popularMangaNextPageSelector(): String?

    /**
     * Parses the response from the site and returns a [MangasPage] object.
     *
     * @param response the response from the site.
     */
    override fun searchMangaParse(response: Response): MangasPage {
        val document = response.asJsoup()

        val mangas =
            document.select(searchMangaSelector()).map { element ->
                searchMangaFromElement(element)
            }

        val hasNextPage =
            searchMangaNextPageSelector()?.let { selector ->
                document.select(selector).first()
            } != null

        return MangasPage(mangas, hasNextPage)
    }

    /**
     * Returns the Jsoup selector that returns a list of [Element] corresponding to each manga.
     */
    protected abstract fun searchMangaSelector(): String

    /**
     * Returns a manga from the given [element]. Most sites only show the title and the url, it's
     * totally fine to fill only those two values.
     *
     * @param element an element obtained from [searchMangaSelector].
     */
    protected abstract fun searchMangaFromElement(element: Element): SManga

    /**
     * Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
     * there's no next page.
     */
    protected abstract fun searchMangaNextPageSelector(): String?

    /**
     * Parses the response from the site and returns a [MangasPage] object.
     *
     * @param response the response from the site.
     */
    override fun latestUpdatesParse(response: Response): MangasPage {
        val document = response.asJsoup()

        val mangas =
            document.select(latestUpdatesSelector()).map { element ->
                latestUpdatesFromElement(element)
            }

        val hasNextPage =
            latestUpdatesNextPageSelector()?.let { selector ->
                document.select(selector).first()
            } != null

        return MangasPage(mangas, hasNextPage)
    }

    /**
     * Returns the Jsoup selector that returns a list of [Element] corresponding to each manga.
     */
    protected abstract fun latestUpdatesSelector(): String

    /**
     * Returns a manga from the given [element]. Most sites only show the title and the url, it's
     * totally fine to fill only those two values.
     *
     * @param element an element obtained from [latestUpdatesSelector].
     */
    protected abstract fun latestUpdatesFromElement(element: Element): SManga

    /**
     * Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
     * there's no next page.
     */
    protected abstract fun latestUpdatesNextPageSelector(): String?

    /**
     * Parses the response from the site and returns the details of a manga.
     *
     * @param response the response from the site.
     */
    override fun mangaDetailsParse(response: Response): SManga = mangaDetailsParse(response.asJsoup())

    /**
     * Returns the details of the manga from the given [document].
     *
     * @param document the parsed document.
     */
    protected abstract fun mangaDetailsParse(document: Document): SManga

    /**
     * Parses the response from the site and returns a list of chapters.
     *
     * @param response the response from the site.
     */
    override fun chapterListParse(response: Response): List<SChapter> {
        val document = response.asJsoup()
        return document.select(chapterListSelector()).map { chapterFromElement(it) }
    }

    /**
     * Returns the Jsoup selector that returns a list of [Element] corresponding to each chapter.
     */
    protected abstract fun chapterListSelector(): String

    /**
     * Returns a chapter from the given element.
     *
     * @param element an element obtained from [chapterListSelector].
     */
    protected abstract fun chapterFromElement(element: Element): SChapter

    /**
     * Parses the response from the site and returns the page list.
     *
     * @param response the response from the site.
     */
    override fun pageListParse(response: Response): List<Page> = pageListParse(response.asJsoup())

    /**
     * Returns a page list from the given document.
     *
     * @param document the parsed document.
     */
    protected abstract fun pageListParse(document: Document): List<Page>

    /**
     * Parse the response from the site and returns the absolute url to the source image.
     *
     * @param response the response from the site.
     */
    override fun imageUrlParse(response: Response): String = imageUrlParse(response.asJsoup())

    /**
     * Returns the absolute url to the source image from the document.
     *
     * @param document the parsed document.
     */
    protected abstract fun imageUrlParse(document: Document): String
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/util/JsoupExtensions.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/util/JsoupExtensions.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/util/JsoupExtensions.kt).

The implementation below defines `Element.selectText`, `Element.selectInt`, `Element.attrOrText`, `Response.asJsoup`.

The source describes its contract as:

> Returns a Jsoup document for this response.

```kotlin
package eu.kanade.tachiyomi.util

import okhttp3.Response
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element

fun Element.selectText(
    css: String,
    defaultValue: String? = null,
): String? = select(css).first()?.text() ?: defaultValue

fun Element.selectInt(
    css: String,
    defaultValue: Int = 0,
): Int = select(css).first()?.text()?.toInt() ?: defaultValue

fun Element.attrOrText(css: String): String = if (css != "text") attr(css) else text()

/**
 * Returns a Jsoup document for this response.
 * @param html the body of the response. Use only if the body was read before calling this method.
 */
fun Response.asJsoup(html: String? = null): Document = Jsoup.parse(html ?: body.string(), request.url.toString())
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/util/lang/CoroutinesExtensions.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/util/lang/CoroutinesExtensions.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/util/lang/CoroutinesExtensions.kt).

The implementation below defines `Observable`, `onStart`, `onNext`, `onCompleted`, `onError`, `CancellableContinuation`, `withIOContext`.

```kotlin
package eu.kanade.tachiyomi.util.lang

import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import rx.Observable
import rx.Subscriber
import rx.Subscription
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

/*
 * Util functions for bridging RxJava and coroutines. Taken from TachiyomiEH/SY.
 */

suspend fun <T> Observable<T>.awaitSingle(): T = single().awaitOne()

@OptIn(InternalCoroutinesApi::class)
private suspend fun <T> Observable<T>.awaitOne(): T =
    suspendCancellableCoroutine { cont ->
        cont.unsubscribeOnCancellation(
            subscribe(
                object : Subscriber<T>() {
                    override fun onStart() {
                        request(1)
                    }

                    override fun onNext(t: T) {
                        cont.resume(t)
                    }

                    override fun onCompleted() {
                        if (cont.isActive) {
                            cont.resumeWithException(
                                IllegalStateException(
                                    "Should have invoked onNext",
                                ),
                            )
                        }
                    }

                    override fun onError(e: Throwable) {
                    /*
                     * Rx1 observable throws NoSuchElementException if cancellation happened before
                     * element emission. To mitigate this we try to atomically resume continuation with exception:
                     * if resume failed, then we know that continuation successfully cancelled itself
                     */
                        val token = cont.tryResumeWithException(e)
                        if (token != null) {
                            cont.completeResume(token)
                        }
                    }
                },
            ),
        )
    }

private fun <T> CancellableContinuation<T>.unsubscribeOnCancellation(sub: Subscription) = invokeOnCancellation { sub.unsubscribe() }

suspend fun <T> withIOContext(block: suspend CoroutineScope.() -> T) = withContext(Dispatchers.IO, block)
```
[chapter-file-end]: #

### Check your understanding

Compare one source method and its model type against the exact listing. Record the package, parameter types and return type that an APK will resolve.
[chapter-content-end]: #


## Step 3: implement Android loading and RPC

Implement `BridgeEnvironment`, `DalvikHandler`, loader, `MihonInvoker`, controller and request/response models. Discover/load extension classes, select source instances, invoke manga/anime operations and translate results consistently. Implement `AndroidExtensionServer` lifecycle around this host. Match the bridge's related-title, cast and season fields, not just basic listings.

Use contract tests and controlled fixture sources before loading a real external extension. Verify invalid source IDs/methods produce structured failures and startup/stop can repeat without duplicate server state.

[chapter-content-start]: #
### Follow the code

The Android host initializes its environment, discovers source classes, instantiates the selected extension and translates incoming RPC operations to manga/anime method calls. Read loader errors and source selection before adding UI integration. The invoker converts results back to the shared protocol, including relations, credits and seasons. Lifecycle control prevents repeated start/stop from leaving duplicate host state.

Write these files in this order:

- `vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/BridgeEnvironment.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/controller/DalvikHandler.kt`
- `vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/impl/MihonInvoker.kt`

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/BridgeEnvironment.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/BridgeEnvironment.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/BridgeEnvironment.kt).

The implementation below defines `MExtensionServerPlugin`, `ProfileBridgeApplication`, `getApplicationContext`, `getSharedPreferences`, `acquireBridgeEnvironment`, `releaseBridgeEnvironment`.

The source describes its contract as:

> Minimal host environment retained by the Mihon compatibility bridge.

```kotlin
package com.kodjodevf.m_extension_server

import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import androidx.preference.PreferenceManager
import eu.kanade.tachiyomi.AppModule
import eu.kanade.tachiyomi.network.NetworkHelper
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get

/** Minimal host environment retained by the Mihon compatibility bridge. */
class MExtensionServerPlugin internal constructor(
    val applicationContext: Context,
)

/**
 * The Application handed to extensions. Every SharedPreferences name (source_<id>, default
 * preferences) is prefixed with the owning profile's [preferencesPrefix]; "" keeps legacy names.
 */
private class ProfileBridgeApplication(base: Application) : Application() {
    @Volatile
    var preferencesPrefix = ""

    init {
        attachBaseContext(base)
    }

    override fun getApplicationContext(): Context = this

    override fun getSharedPreferences(name: String?, mode: Int): SharedPreferences =
        super.getSharedPreferences(name?.let { preferencesPrefix + it }, mode)
}

var instance: MExtensionServerPlugin? = null
    private set
var pm: PackageManager? = null
    private set
var preferenceManager: PreferenceManager? = null
    private set

private var bridgeApplication: ProfileBridgeApplication? = null
private var bridgeOwner: Any? = null

/**
 * Claims the process-wide bridge for [owner]. Extensions share one Injekt graph, so only one
 * profile may run the bridge at a time; switching profile clears the shared network state.
 */
@Synchronized
fun acquireBridgeEnvironment(owner: Any, context: Context, preferencesPrefix: String) {
    check(bridgeOwner == null || bridgeOwner === owner) {
        "The Mihon APK bridge is running for another profile; stop it there before starting it here"
    }
    val app = bridgeApplication ?: run {
        val base = context.applicationContext as? Application
            ?: throw IllegalArgumentException("Android bridge requires an Application context")
        ProfileBridgeApplication(base).also { created ->
            bridgeApplication = created
            instance = MExtensionServerPlugin(created)
            pm = created.packageManager
            preferenceManager = PreferenceManager(created)
            Injekt.importModule(AppModule(created))
        }
    }
    if (app.preferencesPrefix != preferencesPrefix) {
        app.preferencesPrefix = preferencesPrefix
        val network = Injekt.get<NetworkHelper>()
        network.cookieJar.clear()
        network.client.cache?.evictAll()
    }
    bridgeOwner = owner
}

@Synchronized
fun releaseBridgeEnvironment(owner: Any) {
    if (bridgeOwner === owner) bridgeOwner = null
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/controller/DalvikHandler.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/controller/DalvikHandler.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/controller/DalvikHandler.kt).

The implementation below defines `DalvikHandler`, `serve`.

```kotlin
package com.kodjodevf.m_extension_server.server.controller

import m_extension_server.impl.MExtensionServerLoader
import m_extension_server.impl.MihonInvoker
import m_extension_server.model.DataBody
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import eu.kanade.tachiyomi.network.HttpException
import eu.kanade.tachiyomi.animesource.online.AnimeHttpSource
import eu.kanade.tachiyomi.source.online.HttpSource
import fi.iki.elonen.NanoHTTPD
import okhttp3.Cookie
import okhttp3.HttpUrl
import java.io.File
import java.net.URI

class DalvikHandler {
    private val objectMapper = ObjectMapper().registerModule(KotlinModule.Builder().build())

    fun serve(session: NanoHTTPD.IHTTPSession): NanoHTTPD.Response {
        var tempApkFile: File? = null
        try {

            // Parse JSON body first to get extension data
            val body = mutableMapOf<String, String>()
            session.parseBody(body)
            val json = body["postData"] ?: throw IllegalArgumentException("No JSON body")

            // Deserialize DataBody
            val dataBody = objectMapper.readValue(json, DataBody::class.java)

            // Load extension and select the requested factory child. Multi-source
            // APKs (SourceFactory) expose several sources; the bridge context carries
            // the upstream Tachiyomi source ID, and the first source stays the
            // default for older clients that do not send one.
            val loadedExtension = MExtensionServerLoader.loadSourceFromBase64(dataBody.data)
            tempApkFile = loadedExtension.tempApkFile;
            val selectedSource = MihonInvoker.selectSource(loadedExtension.sources, dataBody)
            // Get domain from source
            val domain =
                selectedSource.let { source ->
                    try {
                        val baseUrl = source.javaClass.getMethod("getBaseUrl").invoke(source) as String
                        URI(baseUrl).host
                    } catch (e: Exception) {
                        null
                    }
                } ?: "localhost"

           // Intercept Cookie header and save to global cookie jar
           val cookies =
               (session.headers["cookie"] ?: session.headers["Cookie"])
                   ?.let { cookieHeader ->
                       cookieHeader.split(";").map { cookieStr ->
                           val trimmed = cookieStr.trim()
                           val parts = trimmed.split("=", limit = 2)
                           val name = parts[0].trim()
                           val value = parts[1].trim()
                           Cookie
                               .Builder()
                               .name(name)
                               .value(value)
                               .domain(domain.removePrefix("."))
                               .path("/")
                               .build()
                       }
                   }?.toList()
           val network =
               selectedSource.let { source ->
                   when (source) {
                       is HttpSource -> source.network
                       is AnimeHttpSource -> source.network
                       else -> null
                   }
               }
           if (cookies != null) {
               network?.cookieJar?.addAll(
                   HttpUrl
                       .Builder()
                       .scheme("http")
                       .host(domain.removePrefix("."))
                       .build(),
                   cookies,
               )
           }
           val ua = (session.headers["user-agent"] ?: session.headers["User-Agent"])
           if (ua != null) {
               network?.setUA(ua)
           }

            // Invoke method
            val result = MihonInvoker.invokeMethod(selectedSource, dataBody)

            // Serialize response
            val responseJson = objectMapper.writeValueAsString(result)

           return NanoHTTPD.newFixedLengthResponse(
                NanoHTTPD.Response.Status.OK,
                "application/json",
                responseJson,
            )
        } catch (e: Exception) {
            val status =
                when (e) {
                    is HttpException -> {
                        when (e.code) {
                            400 -> NanoHTTPD.Response.Status.BAD_REQUEST
                            401 -> NanoHTTPD.Response.Status.UNAUTHORIZED
                            403 -> NanoHTTPD.Response.Status.FORBIDDEN
                            404 -> NanoHTTPD.Response.Status.NOT_FOUND
                            429 -> NanoHTTPD.Response.Status.INTERNAL_ERROR
                            500 -> NanoHTTPD.Response.Status.INTERNAL_ERROR
                            else -> NanoHTTPD.Response.Status.INTERNAL_ERROR
                        }
                    }
                    else -> NanoHTTPD.Response.Status.INTERNAL_ERROR
                }
            val errorResponse =
                mapOf(
                    "error" to (e.message ?: "Unknown error"),
                    "code" to (if (e is HttpException) e.code else 500),
                )
            val errorJson = objectMapper.writeValueAsString(errorResponse)
           return NanoHTTPD.newFixedLengthResponse(
                status,
                "application/json",
                errorJson,
            )
        }finally {
            // Clean up APK file
            if (tempApkFile?.exists() ?: false ) {
                tempApkFile.delete()
            }
        }
    }


}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/impl/MihonInvoker.kt
### Write `vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/impl/MihonInvoker.kt`

Create this path in your reconstruction project. Source set: **androidMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/impl/MihonInvoker.kt).

The implementation below defines `MihonInvoker`, `selectSource`, `sourceId`, `invokeMethod`, `invokeGetRelatedAnimeList`, `invokeGetSeasonList`, `invokeHeadersManga`, `invokeFiltersManga`, `invokeSupportLatestManga`, `invokeGetPopularManga` and 20 further declarations.

The source describes its contract as:

> Selects the factory child requested through the bridge-context preference entry. Multi-source APKs (SourceFactory extensions) expose one source per language/site; without an explicit ID every call would route to the first child. Requests without a bridge context keep the historical first-source behavior.

```kotlin
package m_extension_server.impl

import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import androidx.core.content.edit
import androidx.preference.CheckBoxPreference
import androidx.preference.EditTextPreference
import androidx.preference.ListPreference
import androidx.preference.MultiSelectListPreference
import androidx.preference.PreferenceManager
import androidx.preference.PreferenceScreen
import androidx.preference.SwitchPreferenceCompat
import androidx.preference.size
import m_extension_server.model.AnimeData
import m_extension_server.model.AnimeResponse
import m_extension_server.model.ChapterData
import m_extension_server.model.DataBody
import m_extension_server.model.EpisodeData
import m_extension_server.model.JAnime
import m_extension_server.model.JFilterList
import m_extension_server.model.JManga
import m_extension_server.model.JPage
import m_extension_server.model.MangaData
import m_extension_server.model.MangaResponse
import m_extension_server.model.toJAnime
import m_extension_server.model.toJManga
import eu.kanade.tachiyomi.animesource.AnimeCatalogueSource
import eu.kanade.tachiyomi.animesource.AnimeSource
import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource
import eu.kanade.tachiyomi.animesource.model.AnimeFilter
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.animesource.online.AnimeHttpSource
import eu.kanade.tachiyomi.source.CatalogueSource
import eu.kanade.tachiyomi.source.ConfigurableSource
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import kotlinx.coroutines.runBlocking
import com.kodjodevf.m_extension_server.MExtensionServerPlugin
import com.kodjodevf.m_extension_server.instance
import com.kodjodevf.m_extension_server.preferenceManager

object MihonInvoker {
    private const val BRIDGE_CONTEXT_KEY = "__mangayomi_bridge_context__"

    /**
     * Selects the factory child requested through the bridge-context preference entry.
     * Multi-source APKs (SourceFactory extensions) expose one source per language/site;
     * without an explicit ID every call would route to the first child. Requests without
     * a bridge context keep the historical first-source behavior.
     */
    fun selectSource(
        loadedSources: List<Any>,
        data: DataBody,
    ): Any {
        if (loadedSources.isEmpty()) {
            throw IllegalArgumentException("No source found in extension")
        }
        val requestedSourceId =
            data.preferences
                ?.firstOrNull { it["key"] == BRIDGE_CONTEXT_KEY }
                ?.get("sourceId")
                ?.toString()
                ?: return loadedSources.first()
        return loadedSources.firstOrNull { sourceId(it) == requestedSourceId }
            ?: throw IllegalArgumentException("Source $requestedSourceId was not found in extension")
    }

    private fun sourceId(source: Any): String? =
        when (source) {
            is eu.kanade.tachiyomi.source.Source -> source.id.toString()
            is AnimeSource -> source.id.toString()
            else -> null
        }

    fun invokeMethod(
        source: Any,
        data: DataBody,
    ): Any {
        applyPreferences(data, source)

        return when (data.method) {
            "headersManga" -> invokeHeadersManga(source as CatalogueSource)
            "filtersManga" -> invokeFiltersManga(source as CatalogueSource)
            "supportLatestManga" -> invokeSupportLatestManga(source as CatalogueSource)
            "getPopularManga" -> invokeGetPopularManga(source as CatalogueSource, data.page ?: 1)
            "getLatestManga" -> invokeGetLatestManga(source as CatalogueSource, data.page ?: 1)
            "getSearchManga" -> invokeGetSearchManga(source as CatalogueSource, data.page ?: 1, data.search ?: "", data.filterList)
            "getDetailsManga" -> invokeGetDetailsManga(source as CatalogueSource, data.mangaData)
            "getChapterList" -> invokeGetChapterList(source as CatalogueSource, data.mangaData)
            "getPageList" -> invokeGetPageList(source as CatalogueSource, data.chapterData)
            "preferencesManga" -> invokePreferencesManga(source as CatalogueSource)
            "headersAnime" -> invokeHeadersAnime(source as AnimeCatalogueSource)
            "filtersAnime" -> invokeFiltersAnime(source as AnimeCatalogueSource)
            "supportLatestAnime" -> invokeSupportLatestAnime(source as AnimeCatalogueSource)
            "getPopularAnime" -> invokeGetPopularAnime(source as AnimeCatalogueSource, data.page ?: 1)
            "getLatestAnime" -> invokeGetLatestAnime(source as AnimeCatalogueSource, data.page ?: 1)
            "getSearchAnime" -> invokeGetSearchAnime(source as AnimeCatalogueSource, data.page ?: 1, data.search ?: "", data.filterList)
            "getDetailsAnime" -> invokeGetDetailsAnime(source as AnimeCatalogueSource, data.animeData)
            "getRelatedAnimeList" -> invokeGetRelatedAnimeList(source as AnimeSource, data.animeData)
            "getSeasonList" -> invokeGetSeasonList(source as AnimeSource, data.animeData)
            "getEpisodeList" -> invokeGetEpisodeList(source as AnimeCatalogueSource, data.animeData)
            "getVideoList" -> invokeGetVideoList(source as AnimeCatalogueSource, data.episodeData)
            "preferencesAnime" -> invokePreferencesAnime(source as AnimeCatalogueSource)
            else -> throw IllegalArgumentException("Unknown method: ${data.method}")
        }
    }

    internal fun invokeGetRelatedAnimeList(source: AnimeSource, animeData: AnimeData?): Map<String, Any> {
        requireNotNull(animeData) { "animeData is required for getRelatedAnimeList" }
        val supported = try { source.supportsRelatedAnime } catch (_: AbstractMethodError) { false }
        if (!supported) return mapOf("supported" to false, "groups" to emptyList<Any>())
        val anime = SAnime.create().apply { url = animeData.url.orEmpty(); title = animeData.title.orEmpty() }
        val relations = runBlocking { source.getRelatedAnimeList(anime) }
        require(relations.size <= 50 && relations.sumOf { it.animes.size.toLong() } <= 1_000L) { "Too many related entries" }
        return mapOf("supported" to true, "groups" to relations.map { relation ->
            mapOf("name" to relation.name, "animes" to relation.animes.map { it.toJAnime() })
        })
    }

    /** Older APKs lack `getSeasonList`; they never report Seasons, and an empty list is the safe answer. */
    internal fun invokeGetSeasonList(source: AnimeSource, animeData: AnimeData?): List<JAnime> {
        requireNotNull(animeData) { "animeData is required for getSeasonList" }
        val anime = SAnime.create().apply { url = animeData.url.orEmpty(); title = animeData.title.orEmpty() }
        val seasons = try { runBlocking { source.getSeasonList(anime) } } catch (_: AbstractMethodError) { emptyList() }
        require(seasons.size <= 500) { "Too many seasons" }
        return seasons.map { it.toJAnime() }
    }

    private fun invokeHeadersManga(source: CatalogueSource): List<String> =
        if (source is HttpSource) {
            val headers =
                source.headers.toMultimap().flatMap { (name, values) ->
                    values.flatMap { value ->
                        listOf(name.replaceFirstChar { it.uppercase() }, value)
                    }
                }
            headers
        } else {
            emptyList()
        }

    private fun invokeFiltersManga(source: CatalogueSource): FilterList {
        val filterList = source.getFilterList()
        return filterList
    }

    private fun invokeSupportLatestManga(source: CatalogueSource): Boolean = source.supportsLatest

    private fun invokeGetPopularManga(
        source: CatalogueSource,
        page: Int,
    ): MangaResponse =
        runBlocking {
            val mangasPage = source.getPopularManga(page)
            MangaResponse(
                mangas = mangasPage.mangas.map { it.toJManga() },
                hasNextPage = mangasPage.hasNextPage,
            )
        }

    private fun invokeGetLatestManga(
        source: CatalogueSource,
        page: Int,
    ): MangaResponse =
        runBlocking {
            val mangasPage = source.getLatestUpdates(page)
            MangaResponse(
                mangas = mangasPage.mangas.map { it.toJManga() },
                hasNextPage = mangasPage.hasNextPage,
            )
        }

    private fun invokeGetSearchManga(
        source: CatalogueSource,
        page: Int,
        search: String,
        filterList: List<JFilterList>?,
    ): MangaResponse =
        runBlocking {
            val convertedFilters = filterList?.let { convertFilterList(source.getFilterList(), it) } ?: source.getFilterList()
            val mangasPage = source.getSearchManga(page, search, convertedFilters)
            MangaResponse(
                mangas = mangasPage.mangas.map { it.toJManga() },
                hasNextPage = mangasPage.hasNextPage,
            )
        }

    private fun invokeGetDetailsManga(
        source: CatalogueSource,
        mangaData: MangaData?,
    ): JManga {
        if (mangaData == null) {
            throw IllegalArgumentException("mangaData is required for getDetailsManga")
        }

        if (source !is HttpSource) {
            throw IllegalArgumentException("Source must be HttpSource for getDetailsManga")
        }

        val sManga =
            SManga.create().apply {
                url = mangaData.url ?: ""
                title = mangaData.title ?: ""
                artist = mangaData.artist
                author = mangaData.author
                description = mangaData.description
                genre = mangaData.genre
                status = mangaData.status ?: 0
                thumbnail_url = mangaData.thumbnail_url
                initialized = mangaData.initialized ?: false
            }

        return runBlocking {
            val detailedManga = source.getMangaDetails(sManga)
            detailedManga.toJManga()
        }
    }

    private fun invokeGetChapterList(
        source: CatalogueSource,
        mangaData: MangaData?,
    ): List<SChapter> {
        if (mangaData == null) {
            throw IllegalArgumentException("mangaData is required for getChapterList")
        }

        if (source !is HttpSource) {
            throw IllegalArgumentException("Source must be HttpSource for getChapterList")
        }

        val sManga =
            SManga.create().apply {
                url = mangaData.url ?: ""
                title = mangaData.title ?: ""
                artist = mangaData.artist
                author = mangaData.author
                description = mangaData.description
                genre = mangaData.genre
                status = mangaData.status ?: 0
                thumbnail_url = mangaData.thumbnail_url
                initialized = mangaData.initialized ?: false
            }

        return runBlocking {
            val chapters = source.getChapterList(sManga)
            chapters
        }
    }

    private fun invokeGetPageList(
        source: CatalogueSource,
        chapterData: ChapterData?,
    ): List<JPage> {
        if (chapterData == null) {
            throw IllegalArgumentException("chapterData is required for getPageList")
        }

        if (source !is HttpSource) {
            throw IllegalArgumentException("Source must be HttpSource for getPageList")
        }

        val sChapter =
            SChapter.create().apply {
                url = chapterData.url ?: ""
                name = chapterData.name ?: ""
                date_upload = chapterData.date_upload ?: 0L
                chapter_number = chapterData.chapter_number ?: 0f
                scanlator = chapterData.scanlator
            }

        return runBlocking {
            val pages = source.getPageList(sChapter)
            pages.map { page ->
                JPage(
                    index = page.index,
                    url = page.url,
                    imageUrl = source.imageRequest(page).url.toString(),
                )
            }
        }
    }

    private fun invokeHeadersAnime(source: AnimeCatalogueSource): List<String> =
        if (source is AnimeHttpSource) {
            val headers =
                source.headers.toMultimap().flatMap { (name, values) ->
                    values.flatMap { value ->
                        listOf(name.replaceFirstChar { it.uppercase() }, value)
                    }
                }
            headers
        } else {
            emptyList()
        }

    private fun invokeFiltersAnime(source: AnimeCatalogueSource): AnimeFilterList {
        val filterList = source.getFilterList()
        return filterList
    }

    private fun invokeSupportLatestAnime(source: AnimeCatalogueSource): Boolean = source.supportsLatest

    private fun invokeGetPopularAnime(
        source: AnimeCatalogueSource,
        page: Int,
    ): AnimeResponse =
        runBlocking {
            val animesPage = source.getPopularAnime(page)
            AnimeResponse(
                animes = animesPage.animes.map { it.toJAnime() },
                hasNextPage = animesPage.hasNextPage,
            )
        }

    private fun invokeGetLatestAnime(
        source: AnimeCatalogueSource,
        page: Int,
    ): AnimeResponse =
        runBlocking {
            val animesPage = source.getLatestUpdates(page)
            AnimeResponse(
                animes = animesPage.animes.map { it.toJAnime() },
                hasNextPage = animesPage.hasNextPage,
            )
        }

    private fun invokeGetSearchAnime(
        source: AnimeCatalogueSource,
        page: Int,
        search: String,
        filterList: List<JFilterList>?,
    ): AnimeResponse =
        runBlocking {
            val convertedFilters = filterList?.let { convertAnimeFilterList(source.getFilterList(), it) } ?: source.getFilterList()
            val animePage = source.getSearchAnime(page, search, convertedFilters)
            AnimeResponse(
                animes = animePage.animes.map { it.toJAnime() },
                hasNextPage = animePage.hasNextPage,
            )
        }

    private fun invokeGetDetailsAnime(
        source: AnimeCatalogueSource,
        animeData: AnimeData?,
    ): JAnime {
        if (animeData == null) {
            throw IllegalArgumentException("animeData is required for getDetailsAnime")
        }

        if (source !is AnimeHttpSource) {
            throw IllegalArgumentException("Source must be AnimeHttpSource for getDetailsAnime")
        }

        val sAnime =
            SAnime.create().apply {
                url = animeData.url ?: ""
                title = animeData.title ?: ""
                artist = animeData.artist
                author = animeData.author
                description = animeData.description
                genre = animeData.genre
                status = animeData.status ?: 0
                thumbnail_url = animeData.thumbnail_url
                initialized = animeData.initialized ?: false
            }

        return runBlocking {
            val detailedAnime = source.getAnimeDetails(sAnime)
            detailedAnime.toJAnime()
        }
    }

    private fun invokeGetEpisodeList(
        source: AnimeCatalogueSource,
        animeData: AnimeData?,
    ): List<SEpisode> {
        if (animeData == null) {
            throw IllegalArgumentException("animeData is required for getEpisodeList")
        }

        if (source !is AnimeHttpSource) {
            throw IllegalArgumentException("Source must be AnimeHttpSource for getEpisodeList")
        }

        val sAnime =
            SAnime.create().apply {
                url = animeData.url ?: ""
                title = animeData.title ?: ""
                artist = animeData.artist
                author = animeData.author
                description = animeData.description
                genre = animeData.genre
                status = animeData.status ?: 0
                thumbnail_url = animeData.thumbnail_url
                initialized = animeData.initialized ?: false
            }

        return runBlocking {
            val episodes = source.getEpisodeList(sAnime)
            episodes
        }
    }

    private fun invokeGetVideoList(
        source: AnimeCatalogueSource,
        episodeData: EpisodeData?,
    ): List<Video> {
        if (episodeData == null) {
            throw IllegalArgumentException("episodeData is required for getVideoList")
        }

        if (source !is AnimeHttpSource) {
            throw IllegalArgumentException("Source must be AnimeHttpSource for getVideoList")
        }

        val sEpisode =
            SEpisode.create().apply {
                url = episodeData.url ?: ""
                name = episodeData.name ?: ""
                date_upload = episodeData.date_upload ?: 0L
                episode_number = episodeData.episode_number ?: 0f
                scanlator = episodeData.scanlator
            }

        return runBlocking {
            val videos = source.getVideoList(sEpisode)
            videos
        }
    }

    private fun invokePreferencesAnime(source: AnimeCatalogueSource): MutableList<Map<String, Any>> {
        val preferences = mutableListOf<Map<String, Any>>()
        if (source !is ConfigurableAnimeSource) {
            return preferences
        }

        val preferenceManager: PreferenceManager? = preferenceManager
        val instance: MExtensionServerPlugin? = instance
        val screen = preferenceManager!!.createPreferenceScreen(instance!!.applicationContext!!)
        (source as ConfigurableSource).setupPreferenceScreen(screen)
        processPreferences(screen, preferences)

        return preferences
    }

    private fun invokePreferencesManga(source: CatalogueSource): MutableList<Map<String, Any>> {
        val preferences = mutableListOf<Map<String, Any>>()
        if (source !is ConfigurableSource) {
            return preferences
        }
        val preferenceManager: PreferenceManager? = preferenceManager
        val instance: MExtensionServerPlugin? = instance
        val screen = preferenceManager!!.createPreferenceScreen(instance!!.applicationContext!!)
        (source as ConfigurableSource).setupPreferenceScreen(screen)
        processPreferences(screen, preferences)

        return preferences
    }

    private fun processPreferences(
        screen: PreferenceScreen,
        preferences: MutableList<Map<String, Any>>,
    ) {
        for (i in 0 until screen.size) {
            val preference = screen.getPreference(i)
            when (preference) {
                is CheckBoxPreference -> {
                    preferences.add(
                        mapOf(
                            "key" to preference.key,
                            "checkBoxPreference" to
                                mapOf(
                                    "title" to preference.title,
                                    "summary" to (preference.summary ?: ""),
                                    "value" to preference.isChecked,
                                ),
                        ),
                    )
                }
                is SwitchPreferenceCompat -> {
                    preferences.add(
                        mapOf(
                            "key" to preference.key,
                            "switchPreferenceCompat" to
                                mapOf(
                                    "title" to preference.title,
                                    "summary" to (preference.summary ?: ""),
                                    "value" to preference.isChecked,
                                ),
                        ),
                    )
                }
                is EditTextPreference -> {
                    preferences.add(
                        mapOf(
                            "key" to preference.key,
                            "editTextPreference" to
                                mapOf(
                                    "title" to preference.title,
                                    "summary" to (preference.summary ?: ""),
                                    "value" to preference.text,
                                    "text" to preference.text,
                                    "dialogMessage" to preference.getDialogMessage(),
                                    "dialogTitle" to preference.getDialogTitle(),
                                ),
                        ),
                    )
                }
                is ListPreference -> {
                    preferences.add(
                        mapOf(
                            "key" to preference.key,
                            "listPreference" to
                                mapOf(
                                    "title" to preference.title,
                                    "summary" to (preference.summary ?: ""),
                                    "valueIndex" to preference.entryValues.indexOf(preference.value),
                                    "entries" to preference.entries,
                                    "entryValues" to preference.entryValues,
                                ),
                        ),
                    )
                }
                is MultiSelectListPreference -> {
                    preferences.add(
                        mapOf(
                            "key" to preference.key,
                            "multiSelectListPreference" to
                                mapOf(
                                    "title" to preference.title,
                                    "summary" to (preference.summary ?: ""),
                                    "values" to preference.values,
                                    "entries" to preference.entries,
                                    "entryValues" to preference.entryValues,
                                ),
                        ),
                    )
                }
            }
        }
    }

    private fun applyPreferences(
        data: DataBody,
        source: Any,
    ) {
        val preferences = data.preferences ?: return
        val sourceId =
            when (source) {
                is CatalogueSource -> source.id
                is AnimeSource -> source.id
                else -> throw IllegalArgumentException("Unknown source type: ${source.javaClass}")
            }
        val context: Context = instance!!.applicationContext!!
        val prefs = context.getSharedPreferences("source_$sourceId", 0x0000)
        prefs.edit {
            for (prefMap in preferences) {
                val key = prefMap["key"] as? String ?: continue
                when {
                    prefMap.containsKey("checkBoxPreference") -> {
                        val checkBox = prefMap["checkBoxPreference"] as? Map<*, *>
                        val value = checkBox?.get("value") as? Boolean
                        if (value != null) {
                            putBoolean(key, value)
                        }
                    }

                    prefMap.containsKey("switchPreferenceCompat") -> {
                        val switch = prefMap["switchPreferenceCompat"] as? Map<*, *>
                        val value = switch?.get("value") as? Boolean
                        if (value != null) {
                            putBoolean(key, value)
                        }
                    }

                    prefMap.containsKey("editTextPreference") -> {
                        val editText = prefMap["editTextPreference"] as? Map<*, *>
                        val value = editText?.get("value") as? String
                        if (value != null) {
                            putString(key, value)
                        }
                    }

                    prefMap.containsKey("listPreference") -> {
                        val list = prefMap["listPreference"] as? Map<*, *>
                        val valueIndex = list?.get("valueIndex") as? Int
                        val entryValues = list?.get("entryValues") as? List<String>
                        if (valueIndex != null && entryValues != null && valueIndex in entryValues.indices) {
                            putString(key, entryValues[valueIndex])
                        }
                    }

                    prefMap.containsKey("multiSelectListPreference") -> {
                        val multiList = prefMap["multiSelectListPreference"] as? Map<*, *>
                        val values = multiList?.get("values") as? List<String>
                        if (values != null) {
                            putStringSet(key, values.toSet())
                        }
                    }
                }
            }
        }
    }
    private fun convertFilterList(
        originalFilters: FilterList,
        jFilters: List<JFilterList>,
    ): FilterList {
        // Apply the filter values from jFilters to the original filters
        val convertedFilters =
            originalFilters.map { filter ->
                when (filter) {
                    is Filter.Select<*> -> {
                        val jFilter = jFilters.find { it.name == filter.name }
                        if (jFilter != null) {
                            val state = jFilter.stateInt
                            if (state != null) {
                                filter.state = state
                            }
                        }
                        filter
                    }
                    is Filter.CheckBox -> {
                        val jFilter = jFilters.find { it.name == filter.name }
                        if (jFilter != null &&
                            jFilter.stateList != null &&
                            jFilter.stateList.isNotEmpty() &&
                            jFilter.stateList[0].stateBoolean is Boolean
                        ) {
                            filter.state = jFilter.stateList[0].stateBoolean as Boolean
                        }
                        filter
                    }
                    is Filter.TriState -> {
                        val jFilter = jFilters.find { it.name == filter.name }
                        if (jFilter != null && jFilter.stateInt is Int) {
                            filter.state = jFilter.stateInt
                        }
                        filter
                    }
                    is Filter.Text -> {
                        val jFilter = jFilters.find { it.name == filter.name }
                        if (jFilter != null && jFilter.stateString is String) {
                            filter.state = jFilter.stateString
                        }
                        filter
                    }
                    is Filter.Group<*> -> {
                        val groupFilter = filter as Filter.Group<Filter<*>>
                        val jGroup = jFilters.find { it.name == groupFilter.name }
                        if (jGroup != null) {
                            val subJFilters = jGroup.stateList
                            for (state in groupFilter.state) {
                                val jSubFilter = subJFilters?.find { it.name == state.name }
                                val dataGroup = jSubFilter
                                if (dataGroup == null) {
                                    continue
                                }
                                if (state is Filter.CheckBox) {
                                    val checkBox = state
                                    checkBox.state = dataGroup.stateBoolean ?: false
                                }
                                if (state is Filter.TriState) {
                                    val checkBox = state
                                    checkBox.state = dataGroup.stateInt ?: 0
                                }
                                if (state is Filter.Select<*>) {
                                    val select = state
                                    select.state = dataGroup.stateInt ?: 0
                                }
                                if (state is Filter.Text) {
                                    val text = state
                                    text.state = dataGroup.name ?: ""
                                }
                            }
                        }
                        filter
                    }
                    is Filter.Sort -> {
                        val jSort = jFilters.find { it.name == filter.name }
                        if (jSort != null) {
                            val dataSort = jSort.stateSort
                            if (dataSort != null && dataSort.index != null && dataSort.ascending != null) {
                                filter.state = Filter.Sort.Selection(dataSort.index, dataSort.ascending)
                            }
                        }
                        filter
                    }
                    else -> filter
                }
            }
        return FilterList(convertedFilters)
    }

    private fun convertAnimeFilterList(
        originalFilters: AnimeFilterList,
        jFilters: List<JFilterList>,
    ): AnimeFilterList {
        // Apply the filter values from jFilters to the original filters
        val convertedFilters =
            originalFilters.map { filter ->
                when (filter) {
                    is AnimeFilter.Select<*> -> {
                        val jFilter = jFilters.find { it.name == filter.name }
                        if (jFilter != null) {
                            val state = jFilter.stateInt as? Int
                            if (state != null) {
                                filter.state = state
                            }
                        }
                        filter
                    }
                    is AnimeFilter.CheckBox -> {
                        val jFilter = jFilters.find { it.name == filter.name }
                        if (jFilter != null &&
                            jFilter.stateList != null &&
                            jFilter.stateList.isNotEmpty() &&
                            jFilter.stateList[0].stateBoolean is Boolean
                        ) {
                            filter.state = jFilter.stateList[0].stateBoolean as Boolean
                        }
                        filter
                    }
                    is AnimeFilter.TriState -> {
                        val jFilter = jFilters.find { it.name == filter.name }
                        if (jFilter != null && jFilter.stateInt is Int) {
                            filter.state = jFilter.stateInt as Int
                        }
                        filter
                    }
                    is AnimeFilter.Text -> {
                        val jFilter = jFilters.find { it.name == filter.name }
                        if (jFilter != null && jFilter.stateString is String) {
                            filter.state = jFilter.stateString
                        }
                        filter
                    }
                    is AnimeFilter.Group<*> -> {
                        val groupFilter = filter as AnimeFilter.Group<AnimeFilter<*>>
                        val jGroup = jFilters.find { it.name == groupFilter.name }
                        if (jGroup != null) {
                            val subJFilters = jGroup.stateList
                            for (state in groupFilter.state) {
                                val jSubFilter = subJFilters?.find { it.name == state.name }
                                val dataGroup = jSubFilter
                                if (dataGroup == null) {
                                    continue
                                }
                                if (state is AnimeFilter.CheckBox) {
                                    val checkBox = state
                                    checkBox.state = dataGroup.stateBoolean ?: false
                                }
                                if (state is AnimeFilter.TriState) {
                                    val checkBox = state
                                    checkBox.state = dataGroup.stateInt ?: 0
                                }
                                if (state is AnimeFilter.Select<*>) {
                                    val select = state
                                    select.state = dataGroup.stateInt ?: 0
                                }
                                if (state is AnimeFilter.Text) {
                                    val text = state
                                    text.state = dataGroup.name ?: ""
                                }
                            }
                        }
                        filter
                    }
                    is AnimeFilter.Sort -> {
                        val jSort = jFilters.find { it.name == filter.name }
                        if (jSort != null) {
                            val dataSort = jSort.stateSort
                            if (dataSort != null && dataSort.index != null && dataSort.ascending != null) {
                                filter.state =
                                    AnimeFilter.Sort
                                        .Selection(dataSort.index, dataSort.ascending)
                            }
                        }
                        filter
                    }
                    else -> filter
                }
            }
        return AnimeFilterList(convertedFilters)
    }
}
```
[chapter-file-end]: #

### Check your understanding

Use a controlled source factory with two source IDs. Request each ID and an invalid one, then verify structured results and failure rather than a process crash.
[chapter-content-end]: #


## Step 4: implement desktop server process management

Rebuild `DesktopExtensionServerInstaller`: select the host bundle, download/extract with bounds/path validation, detect installed JVM/JAR paths and return an installation record. Keep downloaded runtime binaries separate from per-profile mutable server data. Rebuild `DesktopExtensionServer` to launch the selected JVM/JAR with argument arrays, observe startup/exit, serialize start/stop and reap the process.

The server JAR/JVM distribution is an external artifact. Its implementation is not contained in these 92 tracked submodule files. Your reconstruction must obtain the pinned compatible artifact or separately reimplement that external server to the app-facing protocol.

[chapter-content-start]: #
### Follow the code

The installer resolves a host-specific bundle and validates/extracts it to a controlled location. The running server has a separate mutable data directory from the downloaded runtime. Launch with an argument array, observe startup and unexpected exit, and serialize stop/start. Stop must reap the process before releasing its ownership record. The JVM/server payload is external to these Kotlin files.

Write these files in this order:

- `vendor/yokan-ext/src/desktopMain/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServer.kt`
- `vendor/yokan-ext/src/desktopMain/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServerInstaller.kt`

[chapter-file-start]: #vendor/yokan-ext/src/desktopMain/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServer.kt
### Write `vendor/yokan-ext/src/desktopMain/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServer.kt`

Create this path in your reconstruction project. Source set: **desktopMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/desktopMain/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServer.kt).

The implementation below defines `DesktopExtensionServer`, `start`, `stop`, `stopLocked`, `resolveJavaExecutable`, `javaBinaryName`, `fail`, `desktopExtensionServerCommand`.

The source describes its contract as:

> \[dataDir\] confines the server JVM's home, temp and working directories (the server keeps source preferences and caches there); null keeps the inherited legacy locations.

```kotlin
package eu.friedcutlet.yokan.ext

import java.io.File
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext

/**
 * [dataDir] confines the server JVM's home, temp and working directories (the server keeps
 * source preferences and caches there); null keeps the inherited legacy locations.
 */
class DesktopExtensionServer(private val dataDir: File? = null) : ExtensionServer {
    private val lock = Mutex()
    private val mutableStatus = MutableStateFlow(ExtensionServerStatus.Stopped)
    private var process: Process? = null
    private var activeConfig: ExtensionServerConfig? = null

    override val status: StateFlow<ExtensionServerStatus> = mutableStatus

    override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus = lock.withLock {
        val running = process?.isAlive == true
        if (running && activeConfig == config) return mutableStatus.value
        stopLocked()

        val jar = config.serverJarPath?.takeIf { it.isNotBlank() }?.let(::File)
            ?: throw fail("MISSING_JAR", "An extension server JAR is required on desktop")
        if (!jar.isFile) throw fail("MISSING_JAR", "Extension server JAR does not exist: ${jar.path}")
        val java = resolveJavaExecutable(config.jvmPath)
        mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Starting, config.port, "Starting local extension server")

        val launched = withContext(Dispatchers.IO) {
            runCatching {
                dataDir?.let { File(it, "tmp").mkdirs() }
                ProcessBuilder(desktopExtensionServerCommand(java, jar, config.port, dataDir))
                    .directory(dataDir)
                    .redirectInput(ProcessBuilder.Redirect.PIPE)
                    .redirectOutput(ProcessBuilder.Redirect.DISCARD)
                    .redirectError(ProcessBuilder.Redirect.DISCARD)
                    .start()
            }
        }.getOrElse { error ->
            throw fail("START_ERROR", "Failed to launch extension server with $java: ${error.message.orEmpty()}", error)
        }
        process = launched
        activeConfig = config
        mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Running, config.port, "Server started on port ${config.port}")
        launched.onExit().thenRun {
            if (process === launched) {
                process = null
                activeConfig = null
                mutableStatus.value = ExtensionServerStatus.Stopped.copy(message = "Extension server exited")
            }
        }
        mutableStatus.value
    }

    override suspend fun stop(): ExtensionServerStatus = lock.withLock { stopLocked() }

    private suspend fun stopLocked(): ExtensionServerStatus {
        val current = process
        if (current == null || !current.isAlive) {
            process = null
            activeConfig = null
            return ExtensionServerStatus.Stopped.also { mutableStatus.value = it }
        }
        mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Stopping, activeConfig?.port, "Stopping extension server")
        withContext(Dispatchers.IO) {
            current.destroy()
            if (!current.waitFor(5, TimeUnit.SECONDS)) {
                current.destroyForcibly()
                current.waitFor(5, TimeUnit.SECONDS)
            }
        }
        process = null
        activeConfig = null
        return ExtensionServerStatus.Stopped.copy(message = "Server stopped").also { mutableStatus.value = it }
    }

    internal fun resolveJavaExecutable(rawPath: String?): String {
        val explicit = rawPath?.trim()?.takeIf { it.isNotEmpty() }
        if (explicit != null) {
            val path = File(explicit)
            val executable = if (path.isDirectory) File(path, "bin/${javaBinaryName()}") else path
            if (!executable.isFile) throw fail("MISSING_JAVA", "Java executable does not exist: ${executable.path}")
            return executable.absolutePath
        }
        val javaHome = System.getenv("JAVA_HOME")?.takeIf { it.isNotBlank() }
        if (javaHome != null) {
            val executable = File(javaHome, "bin/${javaBinaryName()}")
            if (executable.isFile) return executable.absolutePath
        }
        return javaBinaryName()
    }

    private fun javaBinaryName(): String = if (System.getProperty("os.name").contains("win", ignoreCase = true)) "java.exe" else "java"

    private fun fail(code: String, message: String, cause: Throwable? = null): ExtensionServerException {
        mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Failed, activeConfig?.port, message)
        return ExtensionServerException(code, message, cause)
    }
}

internal fun desktopExtensionServerCommand(java: String, jar: File, port: Int, dataDir: File?): List<String> =
    listOfNotNull(
        java,
        dataDir?.let { "-Duser.home=${it.absolutePath}" },
        dataDir?.let { "-Djava.io.tmpdir=${File(it, "tmp").absolutePath}" },
        "-jar",
        jar.absolutePath,
        port.toString(),
    )
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/desktopMain/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServerInstaller.kt
### Write `vendor/yokan-ext/src/desktopMain/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServerInstaller.kt`

Create this path in your reconstruction project. Source set: **desktopMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/desktopMain/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServerInstaller.kt).

The implementation below defines `DesktopExtensionServerInstaller`, `discoverLatest`, `installLatest`, `install`, `installedBundle`, `detectBundle`, `download`, `verifySha256`, `extractZip`, `resolveBundle` and 3 further declarations.

```kotlin
package eu.friedcutlet.yokan.ext

import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.nio.file.attribute.PosixFilePermission
import java.security.MessageDigest
import java.time.Duration
import java.util.zip.ZipInputStream
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class DesktopExtensionServerInstaller(
    private val installRoot: Path,
    private val httpClient: HttpClient = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(30))
        .followRedirects(HttpClient.Redirect.NORMAL)
        .build(),
) {
    suspend fun discoverLatest(): ExtensionServerRelease = withContext(Dispatchers.IO) {
        val request = HttpRequest.newBuilder(URI.create(ExtensionServerLatestReleaseUrl))
            .header("Accept", "application/vnd.github+json")
            .header("User-Agent", "Yokan")
            .GET()
            .build()
        val response = httpClient.send(request, HttpResponse.BodyHandlers.ofString())
        if (response.statusCode() !in 200..299) {
            throw ExtensionServerException(
                "RELEASE_HTTP_ERROR",
                "GitHub release request failed with HTTP ${response.statusCode()}",
            )
        }
        parseExtensionServerRelease(response.body())
    }

    suspend fun installLatest(
        onProgress: (downloadedBytes: Long, totalBytes: Long) -> Unit = { _, _ -> },
    ): InstalledExtensionServerBundle {
        val release = discoverLatest()
        return install(release, release.selectBundle(currentDesktopHost()), onProgress)
    }

    suspend fun install(
        release: ExtensionServerRelease,
        asset: ExtensionServerReleaseAsset,
        onProgress: (downloadedBytes: Long, totalBytes: Long) -> Unit = { _, _ -> },
    ): InstalledExtensionServerBundle = withContext(Dispatchers.IO) {
        require(asset.name.endsWith(".zip", ignoreCase = true)) { "Only ZIP bundles are supported" }
        Files.createDirectories(installRoot)
        val archive = Files.createTempFile(installRoot, ".download-", ".zip")
        val staging = Files.createTempDirectory(installRoot, ".install-")
        val finalDirectory = installRoot.resolve(release.version)
        try {
            download(asset, archive, onProgress)
            verifySha256(archive, asset.sha256)
            extractZip(archive, staging)
            val bundle = resolveBundle(staging, release.version)
            makeJavaExecutable(bundle.jvmPath)
            deleteRecursively(finalDirectory)
            try {
                Files.move(staging, finalDirectory, StandardCopyOption.ATOMIC_MOVE)
            } catch (_: Exception) {
                Files.move(staging, finalDirectory)
            }
            resolveBundle(finalDirectory, release.version)
        } finally {
            Files.deleteIfExists(archive)
            deleteRecursively(staging)
        }
    }

    fun installedBundle(version: String): InstalledExtensionServerBundle? {
        val directory = installRoot.resolve(version)
        if (!Files.isDirectory(directory)) return null
        return runCatching { resolveBundle(directory, version) }.getOrNull()
    }

    fun detectBundle(directory: Path): InstalledExtensionServerBundle {
        require(Files.isDirectory(directory)) { "Selected extension server location is not a directory: $directory" }
        return resolveBundle(directory, directory.fileName?.toString().orEmpty().ifBlank { "manual" })
            .also { makeJavaExecutable(it.jvmPath) }
    }

    private fun download(
        asset: ExtensionServerReleaseAsset,
        target: Path,
        onProgress: (Long, Long) -> Unit,
    ) {
        val request = HttpRequest.newBuilder(URI.create(asset.downloadUrl))
            .header("Accept", "application/octet-stream")
            .header("User-Agent", "Yokan")
            .GET()
            .build()
        val response = httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream())
        if (response.statusCode() !in 200..299) {
            response.body().close()
            throw ExtensionServerException("DOWNLOAD_HTTP_ERROR", "Bundle download failed with HTTP ${response.statusCode()}")
        }
        val expected = response.headers().firstValueAsLong("content-length").orElse(asset.size)
        response.body().use { source ->
            BufferedInputStream(source).use { input ->
                BufferedOutputStream(Files.newOutputStream(target)).use { output ->
                    val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
                    var downloaded = 0L
                    while (true) {
                        val count = input.read(buffer)
                        if (count < 0) break
                        output.write(buffer, 0, count)
                        downloaded += count
                        onProgress(downloaded, expected)
                    }
                }
            }
        }
    }

    private fun verifySha256(path: Path, expected: String?) {
        if (expected == null) throw ExtensionServerException("MISSING_DIGEST", "Release asset has no SHA-256 digest")
        val digest = MessageDigest.getInstance("SHA-256")
        Files.newInputStream(path).use { input ->
            val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
            while (true) {
                val count = input.read(buffer)
                if (count < 0) break
                digest.update(buffer, 0, count)
            }
        }
        val actual = digest.digest().joinToString("") { byte -> "%02x".format(byte) }
        if (!actual.equals(expected, ignoreCase = true)) {
            throw ExtensionServerException("DIGEST_MISMATCH", "Bundle SHA-256 mismatch: expected $expected, received $actual")
        }
    }

    private fun extractZip(archive: Path, destination: Path) {
        ZipInputStream(BufferedInputStream(Files.newInputStream(archive))).use { zip ->
            while (true) {
                val entry = zip.nextEntry ?: break
                val target = destination.resolve(entry.name).normalize()
                if (!target.startsWith(destination)) {
                    throw ExtensionServerException("UNSAFE_ARCHIVE", "Bundle contains a path outside its install directory")
                }
                if (entry.isDirectory) {
                    Files.createDirectories(target)
                } else {
                    Files.createDirectories(target.parent)
                    BufferedOutputStream(Files.newOutputStream(target)).use { output -> zip.copyTo(output) }
                }
                zip.closeEntry()
            }
        }
    }

    private fun resolveBundle(root: Path, version: String): InstalledExtensionServerBundle {
        val allFiles = Files.walk(root).use { paths -> paths.filter(Files::isRegularFile).toList() }
        val jar = allFiles.firstOrNull { path ->
            val name = path.fileName.toString()
            name.endsWith(".jar", ignoreCase = true) && name.contains("ExtensionServer", ignoreCase = true)
        } ?: throw ExtensionServerException("MISSING_JAR", "Downloaded bundle contains no extension server JAR")
        val javaName = if (currentDesktopHost().os == ExtensionServerHostOs.Windows) "java.exe" else "java"
        val java = allFiles.firstOrNull { path ->
            path.fileName.toString().equals(javaName, ignoreCase = true) && path.parent?.fileName?.toString() == "bin"
        } ?: throw ExtensionServerException("MISSING_JAVA", "Downloaded bundle contains no Java executable")
        return InstalledExtensionServerBundle(version, root.toAbsolutePath().toString(), java.toAbsolutePath().toString(), jar.toAbsolutePath().toString())
    }

    private fun makeJavaExecutable(path: String) {
        val java = Path.of(path)
        runCatching {
            val permissions = Files.getPosixFilePermissions(java).toMutableSet()
            permissions += PosixFilePermission.OWNER_EXECUTE
            Files.setPosixFilePermissions(java, permissions)
        }.getOrElse { java.toFile().setExecutable(true, true) }
    }

    private fun deleteRecursively(path: Path) {
        if (!Files.exists(path)) return
        Files.walk(path).use { paths ->
            paths.sorted(Comparator.reverseOrder()).forEach(Files::deleteIfExists)
        }
    }
}


fun currentDesktopHost(): ExtensionServerHost {
    val osName = System.getProperty("os.name").lowercase()
    val os = when {
        "win" in osName -> ExtensionServerHostOs.Windows
        "mac" in osName || "darwin" in osName -> ExtensionServerHostOs.MacOs
        "linux" in osName -> ExtensionServerHostOs.Linux
        else -> throw ExtensionServerException("UNSUPPORTED_PLATFORM", "Unsupported desktop OS: $osName")
    }
    val archName = System.getProperty("os.arch").lowercase()
    val arch = when (archName) {
        "x86_64", "amd64" -> ExtensionServerHostArch.X64
        "aarch64", "arm64" -> ExtensionServerHostArch.Arm64
        else -> throw ExtensionServerException("UNSUPPORTED_PLATFORM", "Unsupported desktop architecture: $archName")
    }
    return ExtensionServerHost(os, arch)
}
```
[chapter-file-end]: #

### Check your understanding

Cancel during download, extraction and process startup. Check that partial artifacts and owned child processes are cleaned without deleting a prior usable installation.
[chapter-content-end]: #


## Step 5: implement the iOS bridge

Recreate `JvmBridge.h/.def` and vendored JNI headers, iOS installer and server adapter. Connect them to the main Xcode host's embedded runtime bridge rather than assuming iOS can spawn the desktop JVM process. The app host prepares the Zero interpreter/runtime and server payload, invokes native entry points and handles pause/resume. Chapter 23 covers that host half.

Preserve simulator/device capability differences and the common API for Wasm; shared models compiling in a browser do not imply a browser can run Android bytecode locally.

[chapter-content-start]: #
### Follow the code

The iOS adapter connects to host-provided runtime entry points rather than attempting desktop process creation. Recreate cinterop headers and exact native signatures, then the installer and server wrapper. The Swift/Objective-C++ host half arrives in chapter 23. Preserve simulator/device capability differences and failure status so unsupported execution does not appear as a successfully running server.

Write these files in this order:

- `vendor/yokan-ext/src/iosMain/kotlin/eu/friedcutlet/yokan/ext/IosExtensionServer.kt`
- `vendor/yokan-ext/src/iosMain/kotlin/eu/friedcutlet/yokan/ext/IosExtensionServerInstaller.kt`
- `vendor/yokan-ext/src/nativeInterop/cinterop/JvmBridge.def`
- `vendor/yokan-ext/src/nativeInterop/cinterop/JvmBridge.h`
- `vendor/yokan-ext/src/nativeInterop/cinterop/jni.h`
- `vendor/yokan-ext/src/nativeInterop/cinterop/jni_md.h`

[chapter-file-start]: #vendor/yokan-ext/src/iosMain/kotlin/eu/friedcutlet/yokan/ext/IosExtensionServer.kt
### Write `vendor/yokan-ext/src/iosMain/kotlin/eu/friedcutlet/yokan/ext/IosExtensionServer.kt`

Create this path in your reconstruction project. Source set: **iosMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/iosMain/kotlin/eu/friedcutlet/yokan/ext/IosExtensionServer.kt).

The implementation below defines `IosExtensionServer`, `start`, `stop`, `resolveJavaHome`, `findLibrary`, `requireFile`, `fileExists`, `normalizePath`.

The source describes its contract as:

> Embedded iOS runner. The signed OpenJDK runtime is loaded in-process. JNI permits one JVM per process lifetime, so a running or exited JVM cannot be replaced.

```kotlin
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)

package eu.friedcutlet.yokan.ext

import eu.friedcutlet.yokan.ext.jvmbridge.yokan_jvm_launch_main
import eu.friedcutlet.yokan.ext.jvmbridge.yokan_jvm_has_jit_permission

import kotlinx.cinterop.ByteVar
import kotlinx.cinterop.allocArray
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.toKString
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import platform.Foundation.NSBundle
import platform.Foundation.NSFileManager
import platform.Foundation.NSHomeDirectory
import platform.Foundation.NSTemporaryDirectory
import platform.UIKit.UIDevice
import platform.darwin.dispatch_async
import platform.darwin.dispatch_get_global_queue
import platform.posix.chdir
import platform.posix.setenv

/**
 * Embedded iOS runner. The signed OpenJDK runtime is loaded in-process.
 * JNI permits one JVM per process lifetime, so a running or exited JVM cannot be replaced.
 */
class IosExtensionServer : ExtensionServer {

    override val status: StateFlow<ExtensionServerStatus> = sharedStatus

    override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus = lock.withLock {
        when (val current = sharedStatus.value.phase) {
            ExtensionServerPhase.Running -> {
                if (sharedStatus.value.port == config.port) return sharedStatus.value
                throw ExtensionServerException(
                    "ALREADY_RUNNING",
                    "The embedded iOS JVM is already running on port ${sharedStatus.value.port}; relaunch Yokan to change it",
                )
            }
            ExtensionServerPhase.Stopped -> if (jvmWasStarted) {
                throw ExtensionServerException("JVM_EXITED", "The embedded iOS JVM already exited; relaunch Yokan to start it again")
            }
            ExtensionServerPhase.Starting, ExtensionServerPhase.Stopping -> {
                throw ExtensionServerException("BUSY", "The embedded iOS JVM is changing state")
            }
            ExtensionServerPhase.Failed -> if (jvmWasStarted) {
                throw ExtensionServerException("JVM_EXITED", "The embedded iOS JVM cannot be restarted; relaunch Yokan")
            }
        }

        val jar = normalizePath(config.serverJarPath)
            ?: throw ExtensionServerException("MISSING_JAR", "An extension server JAR is required on iOS")
        requireFile(jar, "MISSING_JAR", "Extension server JAR")
        val javaHome = resolveJavaHome(normalizePath(config.jvmPath))
        val jvmPath = findLibrary(javaHome, "libjvm.dylib")
            ?: throw ExtensionServerException("MISSING_JAVA", "The signed iOS runtime has no libjvm.dylib: $javaHome")
        if (yokan_jvm_has_jit_permission() == 0) {
            throw ExtensionServerException(
                "JIT_UNAVAILABLE",
                "Enable JIT for Yokan with SideStore, AltStore, or StikDebug before starting the embedded server. " +
                    "On iOS 26 or later, keep the debugger attached.",
            )
        }
        val useMirroredCodeCache = UIDevice.currentDevice.systemVersion.substringBefore('.').toIntOrNull()?.let { it >= 26 } == true
        val mainClassName = "mextensionserver.MainKt"
        val temporaryDirectory = NSTemporaryDirectory()
        val userHome = NSHomeDirectory()

        setenv("JAVA_HOME", javaHome, 1)
        chdir(NSHomeDirectory())
        jvmWasStarted = true
        sharedStatus.value = ExtensionServerStatus(ExtensionServerPhase.Starting, config.port, "Launching embedded iOS JVM")
        dispatch_async(dispatch_get_global_queue(0, 0u)) {
            var errorMessage = ""
            val code = memScoped {
                val errorBuffer = allocArray<ByteVar>(ErrorBufferSize)
                yokan_jvm_launch_main(
                    jvm_path = jvmPath,
                    jar_path = jar,
                    main_class_name = mainClassName,
                    port = config.port.toString(),
                    temporary_directory = temporaryDirectory,
                    user_home = userHome,
                    use_mirrored_code_cache = if (useMirroredCodeCache) 1 else 0,
                    error_buffer = errorBuffer,
                    error_capacity = ErrorBufferSize.toULong(),
                ).also { result ->
                    if (result != 0) errorMessage = errorBuffer.toKString()
                }
            }
            sharedStatus.value = ExtensionServerStatus(
                if (code == 0) ExtensionServerPhase.Stopped else ExtensionServerPhase.Failed,
                message = if (code == 0) {
                    "Embedded iOS JVM exited"
                } else {
                    errorMessage.ifBlank { "Embedded iOS JVM failed with code $code" }
                },
            )
        }
        ExtensionServerStatus(ExtensionServerPhase.Running, config.port, "Embedded iOS JVM started on port ${config.port}")
            .also { sharedStatus.value = it }
    }

    override suspend fun stop(): ExtensionServerStatus = lock.withLock {
        if (sharedStatus.value.phase == ExtensionServerPhase.Running) {
            throw ExtensionServerException(
                "STOP_UNSUPPORTED",
                "The embedded iOS JVM cannot stop without terminating Yokan",
            )
        }
        sharedStatus.value
    }

    private fun resolveJavaHome(explicit: String?): String {
        val candidates = buildList {
            explicit?.let {
                add(if (it.endsWith("/bin/java")) it.removeSuffix("/bin/java") else it)
            }
            NSBundle.mainBundle.resourcePath?.let { add("$it/java_runtimes/java-21-openjdk") }
        }
        return candidates.firstOrNull { findLibrary(it, "libjvm.dylib") != null }
            ?: throw ExtensionServerException(
                "MISSING_JAVA",
                "No signed iOS OpenJDK runtime found; checked ${candidates.joinToString()}",
            )
    }

    private fun findLibrary(home: String, name: String): String? {
        val relativePaths = listOf(
            "lib/$name",
            "lib/server/$name",
            "lib/zero/$name",
            "lib/client/$name",
            "lib/minimal/$name",
            "lib/jli/$name",
            "jre/lib/jli/$name",
            "jre/lib/server/$name",
        )
        return relativePaths.asSequence().map { "$home/$it" }.firstOrNull(::fileExists)
    }

    private fun requireFile(path: String, code: String, label: String) {
        if (!fileExists(path)) throw ExtensionServerException(code, "$label does not exist: $path")
    }

    private fun fileExists(path: String): Boolean = NSFileManager.defaultManager.fileExistsAtPath(path)

    private fun normalizePath(path: String?): String? = path?.trim()?.trim('"', '\'')?.removePrefix("file://")?.takeIf(String::isNotEmpty)

    private companion object {
        val lock = Mutex()
        val sharedStatus = MutableStateFlow(ExtensionServerStatus.Stopped)
        var jvmWasStarted = false
        const val ErrorBufferSize = 1_024
    }
}

```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/iosMain/kotlin/eu/friedcutlet/yokan/ext/IosExtensionServerInstaller.kt
### Write `vendor/yokan-ext/src/iosMain/kotlin/eu/friedcutlet/yokan/ext/IosExtensionServerInstaller.kt`

Create this path in your reconstruction project. Source set: **iosMain**. [Exact file download](../reference/source/vendor/yokan-ext/src/iosMain/kotlin/eu/friedcutlet/yokan/ext/IosExtensionServerInstaller.kt).

The implementation below defines `IosExtensionServerInstaller`, `install`, `importJar`, `download`, `resolveBundle`, `copy`, `createForTesting`, `versionFromPath`, `verifyIosExtensionServerArchiveSha256`, `extractIosExtensionServerJar`.

The source describes its contract as:

> Installs only the architecture-independent server JAR; iOS JVM binaries stay build-provisioned.

```kotlin
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)

package eu.friedcutlet.yokan.ext

import io.ktor.client.HttpClient
import io.ktor.client.engine.darwin.Darwin
import io.ktor.client.request.prepareGet
import io.ktor.client.statement.bodyAsChannel
import io.ktor.http.isSuccess
import io.ktor.utils.io.readAvailable
import okio.Buffer
import okio.FileSystem
import okio.HashingSource
import okio.Path
import okio.Path.Companion.toPath
import okio.buffer
import okio.openZip
import platform.Foundation.NSURL

/** Installs only the architecture-independent server JAR; iOS JVM binaries stay build-provisioned. */
class IosExtensionServerInstaller private constructor(
    installRoot: String,
    private val bundledJvmPath: String,
    private val fileSystem: FileSystem,
    private val archiveDownloader: (suspend (ExtensionServerReleaseAsset, Path, (Long, Long) -> Unit) -> Unit)?,
    private val trustedDigest: (ExtensionServerRelease, ExtensionServerReleaseAsset) -> String,
) {
    constructor(
        installRoot: String,
        bundledJvmPath: String,
    ) : this(
        installRoot = installRoot,
        bundledJvmPath = bundledJvmPath,
        fileSystem = FileSystem.SYSTEM,
        archiveDownloader = null,
        trustedDigest = { release, asset -> release.trustedSha256(asset) },
    )

    private val installRoot = installRoot.toPath(normalize = true)

    suspend fun install(
        release: ExtensionServerRelease,
        asset: ExtensionServerReleaseAsset,
        onProgress: (downloadedBytes: Long, totalBytes: Long) -> Unit = { _, _ -> },
    ): InstalledExtensionServerBundle {
        if (!asset.name.endsWith(".zip", ignoreCase = true)) {
            throw ExtensionServerException("UNSUPPORTED_ARCHIVE", "Only ZIP bundles are supported")
        }
        val expectedDigest = trustedDigest(release, asset)
        fileSystem.createDirectories(installRoot)
        val archive = installRoot / ".download-${release.version}.zip"
        val staging = installRoot / ".install-${release.version}"
        val destination = installRoot / release.version
        try {
            fileSystem.delete(archive, mustExist = false)
            fileSystem.deleteRecursively(staging, mustExist = false)
            download(asset, archive, onProgress)
            verifyIosExtensionServerArchiveSha256(fileSystem, archive, expectedDigest)
            fileSystem.createDirectories(staging)
            extractIosExtensionServerJar(fileSystem, archive, staging)
            fileSystem.deleteRecursively(destination, mustExist = false)
            fileSystem.atomicMove(staging, destination)
            return resolveBundle(destination, release.version)
        } finally {
            fileSystem.delete(archive, mustExist = false)
            fileSystem.deleteRecursively(staging, mustExist = false)
        }
    }

    fun importJar(sourcePath: String): InstalledExtensionServerBundle {
        val source = sourcePath.removePrefix("file://").toPath(normalize = true)
        if (source.name.substringAfterLast('.', "").lowercase() != "jar" || fileSystem.metadataOrNull(source) == null) {
            throw ExtensionServerException("MISSING_JAR", "Selected extension server JAR does not exist: $source")
        }
        val destinationDirectory = installRoot / "manual"
        val destination = destinationDirectory / source.name
        val staging = destinationDirectory / ".${source.name}.import"
        fileSystem.createDirectories(destinationDirectory)
        fileSystem.delete(staging, mustExist = false)
        try {
            copy(source, staging)
            fileSystem.delete(destination, mustExist = false)
            fileSystem.atomicMove(staging, destination)
        } finally {
            fileSystem.delete(staging, mustExist = false)
        }
        return InstalledExtensionServerBundle(
            version = versionFromPath(destination),
            rootPath = destinationDirectory.toString(),
            jvmPath = bundledJvmPath,
            serverJarPath = destination.toString(),
        )
    }

    private suspend fun download(
        asset: ExtensionServerReleaseAsset,
        target: Path,
        onProgress: (Long, Long) -> Unit,
    ) {
        archiveDownloader?.let { downloader ->
            downloader(asset, target, onProgress)
            return
        }
        NSURL.URLWithString(asset.downloadUrl)
            ?: throw ExtensionServerException("INVALID_DOWNLOAD_URL", "Invalid bundle URL: ${asset.downloadUrl}")
        val client = HttpClient(Darwin)
        try {
            client.prepareGet(asset.downloadUrl).execute { response ->
                if (!response.status.isSuccess()) {
                    throw ExtensionServerException(
                        "DOWNLOAD_HTTP_ERROR",
                        "Bundle download failed with HTTP ${response.status.value}",
                    )
                }
                val channel = response.bodyAsChannel()
                val expected = response.headers["Content-Length"]?.toLongOrNull() ?: asset.size
                val output = fileSystem.sink(target).buffer()
                val buffer = ByteArray(8_192)
                var downloaded = 0L
                try {
                    while (true) {
                        val count = channel.readAvailable(buffer)
                        if (count < 0) break
                        if (count == 0) continue
                        output.write(buffer, 0, count)
                        downloaded += count
                        onProgress(downloaded, expected)
                    }
                } finally {
                    output.close()
                }
            }
        } finally {
            client.close()
        }
    }


    private fun resolveBundle(directory: Path, version: String): InstalledExtensionServerBundle {
        val jar = fileSystem.listRecursively(directory)
            .firstOrNull { path ->
                val name = path.name.lowercase()
                name.endsWith(".jar") && "extensionserver" in name && fileSystem.metadata(path).isRegularFile
            }
            ?: throw ExtensionServerException("BUNDLE_INVALID", "Installed bundle has no extension server JAR")
        return InstalledExtensionServerBundle(
            version = version,
            rootPath = directory.toString(),
            jvmPath = bundledJvmPath,
            serverJarPath = jar.toString(),
        )
    }

    private fun copy(source: Path, destination: Path) = copy(fileSystem, source, destination)

    private fun copy(sourceFileSystem: FileSystem, source: Path, destination: Path) {
        val input = sourceFileSystem.source(source).buffer()
        val output = fileSystem.sink(destination).buffer()
        try {
            output.writeAll(input)
        } finally {
            output.close()
            input.close()
        }
    }

    companion object {
        internal fun createForTesting(
            installRoot: String,
            bundledJvmPath: String,
            fileSystem: FileSystem,
            archiveDownloader: suspend (ExtensionServerReleaseAsset, Path, (Long, Long) -> Unit) -> Unit,
            trustedDigest: (ExtensionServerRelease, ExtensionServerReleaseAsset) -> String,
        ): IosExtensionServerInstaller = IosExtensionServerInstaller(
            installRoot = installRoot,
            bundledJvmPath = bundledJvmPath,
            fileSystem = fileSystem,
            archiveDownloader = archiveDownloader,
            trustedDigest = trustedDigest,
        )
    }

    private fun versionFromPath(path: Path): String =
        Regex("""v?(\d+\.\d+\.\d+)""").find(path.name)?.groupValues?.getOrNull(1) ?: "manual"
}

internal fun verifyIosExtensionServerArchiveSha256(
    fileSystem: FileSystem,
    path: Path,
    expected: String?,
) {
    if (expected == null) {
        throw ExtensionServerException("MISSING_DIGEST", "Release asset has no trusted SHA-256 digest")
    }
    val hashingSource = HashingSource.sha256(fileSystem.source(path))
    val buffer = Buffer()
    try {
        while (hashingSource.read(buffer, 8_192) != -1L) buffer.clear()
    } finally {
        hashingSource.close()
    }
    val actual = hashingSource.hash.hex()
    if (!actual.equals(expected, ignoreCase = true)) {
        throw ExtensionServerException(
            "CHECKSUM_MISMATCH",
            "Bundle checksum mismatch: expected $expected, received $actual",
        )
    }
}

internal fun extractIosExtensionServerJar(
    fileSystem: FileSystem,
    archive: Path,
    destination: Path,
): Path {
    val zip = fileSystem.openZip(archive)
    val jar = zip.listRecursively("/".toPath())
        .firstOrNull { path ->
            val name = path.name.lowercase()
            name.endsWith(".jar") && "extensionserver" in name && zip.metadata(path).isRegularFile
        }
        ?: throw ExtensionServerException("BUNDLE_INVALID", "Downloaded bundle has no extension server JAR")
    val extracted = destination / jar.name
    val input = zip.source(jar).buffer()
    val output = fileSystem.sink(extracted).buffer()
    try {
        output.writeAll(input)
    } finally {
        output.close()
        input.close()
    }
    return extracted
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/nativeInterop/cinterop/JvmBridge.def
### Write `vendor/yokan-ext/src/nativeInterop/cinterop/JvmBridge.def`

Create this path in your reconstruction project. Source set: **nativeInterop**. [Exact file download](../reference/source/vendor/yokan-ext/src/nativeInterop/cinterop/JvmBridge.def).

```text
headers = JvmBridge.h
package = eu.friedcutlet.yokan.ext.jvmbridge
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/nativeInterop/cinterop/JvmBridge.h
### Write `vendor/yokan-ext/src/nativeInterop/cinterop/JvmBridge.h`

Create this path in your reconstruction project. Source set: **nativeInterop**. [Exact file download](../reference/source/vendor/yokan-ext/src/nativeInterop/cinterop/JvmBridge.h).

```cpp
#ifndef YOKAN_JVM_BRIDGE_H
#define YOKAN_JVM_BRIDGE_H

#include <dlfcn.h>
#include <TargetConditionals.h>
#include <jni.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

#define YOKAN_CS_OPS_STATUS 0
#define YOKAN_CS_DEBUGGED 0x10000000

extern int csops(pid_t pid, unsigned int ops, void *useraddr, size_t usersize);

static inline int32_t yokan_jvm_has_jit_permission(void) {
#if TARGET_OS_SIMULATOR
    return 1;
#else
    uint32_t flags = 0;
    return csops(getpid(), YOKAN_CS_OPS_STATUS, &flags, sizeof(flags)) == 0 &&
        (flags & YOKAN_CS_DEBUGGED) != 0;
#endif
}

static inline void yokan_jvm_set_error(char *buffer, size_t capacity, const char *message) {
    if (buffer != NULL && capacity > 0) {
        snprintf(buffer, capacity, "%s", message != NULL ? message : "Unknown embedded JVM error");
    }
}

static inline char *yokan_jvm_property(const char *name, const char *value) {
    const size_t size = strlen(name) + strlen(value) + 3;
    char *property = (char *)malloc(size);
    if (property != NULL) {
        snprintf(property, size, "-D%s=%s", name, value);
    }
    return property;
}

static inline void yokan_jvm_set_pending_exception(
    JNIEnv *env,
    char *buffer,
    size_t capacity,
    const char *fallback
) {
    if (!(*env)->ExceptionCheck(env)) {
        yokan_jvm_set_error(buffer, capacity, fallback);
        return;
    }

    jthrowable throwable = (*env)->ExceptionOccurred(env);
    (*env)->ExceptionClear(env);
    jclass throwable_class = throwable == NULL ? NULL :
        (jclass)(*env)->GetObjectClass(env, throwable);
    jmethodID to_string = throwable_class == NULL ? NULL :
        (*env)->GetMethodID(env, throwable_class, "toString", "()Ljava/lang/String;");
    jstring description = to_string == NULL ? NULL :
        (jstring)(*env)->CallObjectMethod(env, throwable, to_string);
    if ((*env)->ExceptionCheck(env)) {
        (*env)->ExceptionClear(env);
        description = NULL;
    }

    int wrote_description = 0;
    if (description != NULL) {
        const char *utf = (*env)->GetStringUTFChars(env, description, NULL);
        if (utf != NULL) {
            yokan_jvm_set_error(buffer, capacity, utf);
            wrote_description = 1;
            (*env)->ReleaseStringUTFChars(env, description, utf);
        }
    }
    if ((*env)->ExceptionCheck(env)) {
        (*env)->ExceptionClear(env);
    }
    if (!wrote_description) {
        yokan_jvm_set_error(buffer, capacity, fallback);
    }
    if (description != NULL) (*env)->DeleteLocalRef(env, description);
    if (throwable_class != NULL) (*env)->DeleteLocalRef(env, throwable_class);
    if (throwable != NULL) (*env)->DeleteLocalRef(env, throwable);
}

static inline jclass yokan_jvm_load_class(
    JNIEnv *env,
    const char *jar_path,
    const char *class_name
) {
    jclass file_class = (*env)->FindClass(env, "java/io/File");
    jmethodID file_constructor = file_class == NULL ? NULL :
        (*env)->GetMethodID(env, file_class, "<init>", "(Ljava/lang/String;)V");
    jstring path = file_constructor == NULL ? NULL : (*env)->NewStringUTF(env, jar_path);
    jobject file = path == NULL ? NULL :
        (*env)->NewObject(env, file_class, file_constructor, path);
    jmethodID to_uri = file == NULL ? NULL :
        (*env)->GetMethodID(env, file_class, "toURI", "()Ljava/net/URI;");
    jobject uri = to_uri == NULL ? NULL : (*env)->CallObjectMethod(env, file, to_uri);

    jclass uri_class = uri == NULL ? NULL : (*env)->FindClass(env, "java/net/URI");
    jmethodID to_url = uri_class == NULL ? NULL :
        (*env)->GetMethodID(env, uri_class, "toURL", "()Ljava/net/URL;");
    jobject url = to_url == NULL ? NULL : (*env)->CallObjectMethod(env, uri, to_url);
    jclass url_class = url == NULL ? NULL : (*env)->FindClass(env, "java/net/URL");
    jobjectArray urls = url_class == NULL ? NULL :
        (*env)->NewObjectArray(env, 1, url_class, url);

    jclass loader_class = urls == NULL ? NULL :
        (*env)->FindClass(env, "java/net/URLClassLoader");
    jmethodID new_loader = loader_class == NULL ? NULL :
        (*env)->GetStaticMethodID(
            env,
            loader_class,
            "newInstance",
            "([Ljava/net/URL;)Ljava/net/URLClassLoader;"
        );
    jobject loader = new_loader == NULL ? NULL :
        (*env)->CallStaticObjectMethod(env, loader_class, new_loader, urls);

    jclass thread_class = loader == NULL ? NULL : (*env)->FindClass(env, "java/lang/Thread");
    jmethodID current_thread = thread_class == NULL ? NULL :
        (*env)->GetStaticMethodID(env, thread_class, "currentThread", "()Ljava/lang/Thread;");
    jobject thread = current_thread == NULL ? NULL :
        (*env)->CallStaticObjectMethod(env, thread_class, current_thread);
    jmethodID set_context_loader = thread == NULL ? NULL :
        (*env)->GetMethodID(
            env,
            thread_class,
            "setContextClassLoader",
            "(Ljava/lang/ClassLoader;)V"
        );
    if (set_context_loader == NULL) {
        return NULL;
    }
    (*env)->CallVoidMethod(env, thread, set_context_loader, loader);

    jclass class_loader_class = (*env)->FindClass(env, "java/lang/ClassLoader");
    jmethodID load_class = class_loader_class == NULL ? NULL :
        (*env)->GetMethodID(
            env,
            class_loader_class,
            "loadClass",
            "(Ljava/lang/String;)Ljava/lang/Class;"
        );
    jstring requested_class = load_class == NULL ? NULL :
        (*env)->NewStringUTF(env, class_name);
    jobject loaded_class = requested_class == NULL ? NULL :
        (*env)->CallObjectMethod(env, loader, load_class, requested_class);
    return (jclass)loaded_class;
}

/*
 * Starts OpenJDK through the JNI invocation API and calls a static
 * main(String[]) method. JLI_Launch cannot be used inside an iOS host app:
 * Apple's libjli startup path resolves the process-wide `main` symbol and
 * would invoke the SwiftUI application entry point a second time.
 */
static inline int32_t yokan_jvm_launch_main(
    const char *jvm_path,
    const char *jar_path,
    const char *main_class_name,
    const char *port,
    const char *temporary_directory,
    const char *user_home,
    int32_t use_mirrored_code_cache,
    char *error_buffer,
    size_t error_capacity
) {
    void *handle = dlopen(jvm_path, RTLD_NOW | RTLD_GLOBAL);
    if (handle == NULL) {
        yokan_jvm_set_error(error_buffer, error_capacity, dlerror());
        return 1;
    }

    typedef jint (*CreateJavaVm)(JavaVM **, void **, void *);
    CreateJavaVm create_vm = (CreateJavaVm)dlsym(handle, "JNI_CreateJavaVM");
    if (create_vm == NULL) {
        yokan_jvm_set_error(error_buffer, error_capacity, "libjvm.dylib does not export JNI_CreateJavaVM");
        return 2;
    }

    char *class_path = yokan_jvm_property("java.class.path", jar_path);
    char *tmp_dir = yokan_jvm_property("java.io.tmpdir", temporary_directory);
    char *home = yokan_jvm_property("user.home", user_home);
    if (class_path == NULL || tmp_dir == NULL || home == NULL) {
        free(class_path);
        free(tmp_dir);
        free(home);
        yokan_jvm_set_error(error_buffer, error_capacity, "Could not allocate embedded JVM options");
        return 3;
    }

    JavaVMOption options[12];
    jint option_count = 0;
    options[option_count++] = (JavaVMOption) { .optionString = "-Xint", .extraInfo = NULL };
    options[option_count++] = (JavaVMOption) { .optionString = "-Xms32m", .extraInfo = NULL };
    options[option_count++] = (JavaVMOption) { .optionString = "-Xmx512m", .extraInfo = NULL };
    /*
     * HotSpot's compressed class space requires an extended virtual address
     * range that ordinary sideloaded iOS processes do not receive.
     */
    options[option_count++] = (JavaVMOption) { .optionString = "-XX:-UseCompressedClassPointers", .extraInfo = NULL };
    options[option_count++] = (JavaVMOption) { .optionString = "-XX:+UnlockExperimentalVMOptions", .extraInfo = NULL };
    if (use_mirrored_code_cache) {
        options[option_count++] = (JavaVMOption) { .optionString = "-XX:+MirrorMappedCodeCache", .extraInfo = NULL };
    }
    options[option_count++] = (JavaVMOption) { .optionString = "-Xrs", .extraInfo = NULL };
    options[option_count++] = (JavaVMOption) { .optionString = "-XX:-UsePerfData", .extraInfo = NULL };
    options[option_count++] = (JavaVMOption) { .optionString = "-Djava.awt.headless=true", .extraInfo = NULL };
    options[option_count++] = (JavaVMOption) { .optionString = class_path, .extraInfo = NULL };
    options[option_count++] = (JavaVMOption) { .optionString = tmp_dir, .extraInfo = NULL };
    options[option_count++] = (JavaVMOption) { .optionString = home, .extraInfo = NULL };
    JavaVMInitArgs init_args = {
        .version = JNI_VERSION_1_8,
        .nOptions = option_count,
        .options = options,
        .ignoreUnrecognized = JNI_FALSE,
    };
    JavaVM *vm = NULL;
    JNIEnv *env = NULL;
    const jint create_result = create_vm(&vm, (void **)&env, &init_args);
    free(class_path);
    free(tmp_dir);
    free(home);
    if (create_result != JNI_OK || vm == NULL || env == NULL) {
        char message[128];
        snprintf(message, sizeof(message), "JNI_CreateJavaVM failed with code %d", create_result);
        yokan_jvm_set_error(error_buffer, error_capacity, message);
        return 4;
    }

    jclass main_class = yokan_jvm_load_class(env, jar_path, main_class_name);
    if (main_class == NULL) {
        yokan_jvm_set_pending_exception(
            env,
            error_buffer,
            error_capacity,
            "Extension server main class was not found"
        );
        return 5;
    }
    jmethodID main_method = (*env)->GetStaticMethodID(env, main_class, "main", "([Ljava/lang/String;)V");
    if (main_method == NULL) {
        yokan_jvm_set_pending_exception(
            env,
            error_buffer,
            error_capacity,
            "Extension server main(String[]) method was not found"
        );
        return 6;
    }
    jclass string_class = (*env)->FindClass(env, "java/lang/String");
    jobjectArray arguments = string_class == NULL ? NULL : (*env)->NewObjectArray(env, 1, string_class, NULL);
    jstring port_argument = arguments == NULL ? NULL : (*env)->NewStringUTF(env, port);
    if (arguments == NULL || port_argument == NULL || (*env)->ExceptionCheck(env)) {
        yokan_jvm_set_pending_exception(
            env,
            error_buffer,
            error_capacity,
            "Could not create extension server arguments"
        );
        return 7;
    }
    (*env)->SetObjectArrayElement(env, arguments, 0, port_argument);
    if ((*env)->ExceptionCheck(env)) {
        yokan_jvm_set_pending_exception(
            env,
            error_buffer,
            error_capacity,
            "Could not populate extension server arguments"
        );
        return 7;
    }
    jvalue call_arguments[1];
    call_arguments[0].l = arguments;
    (*env)->CallStaticVoidMethodA(env, main_class, main_method, call_arguments);
    if ((*env)->ExceptionCheck(env)) {
        yokan_jvm_set_pending_exception(
            env,
            error_buffer,
            error_capacity,
            "Extension server main method failed"
        );
        return 8;
    }
    return 0;
}

#endif
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/nativeInterop/cinterop/jni.h
### Write `vendor/yokan-ext/src/nativeInterop/cinterop/jni.h`

Create this path in your reconstruction project. Source set: **nativeInterop**. [Exact file download](../reference/source/vendor/yokan-ext/src/nativeInterop/cinterop/jni.h).

The implementation below defines `_jobject`, `_jclass`, `_jthrowable`, `_jstring`, `_jarray`, `_jbooleanArray`, `_jbyteArray`, `_jcharArray`, `_jshortArray`, `_jintArray` and 4 further declarations.

```cpp
/*
 * Copyright (c) 1996, 2023, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * We used part of Netscape's Java Runtime Interface (JRI) as the starting
 * point of our design and implementation.
 */

/******************************************************************************
 * Java Runtime Interface
 * Copyright (c) 1996 Netscape Communications Corporation. All rights reserved.
 *****************************************************************************/

#ifndef _JAVASOFT_JNI_H_
#define _JAVASOFT_JNI_H_

#include <stdio.h>
#include <stdarg.h>

/* jni_md.h contains the machine-dependent typedefs for jbyte, jint
   and jlong */

#include "jni_md.h"

#ifdef __cplusplus
extern "C" {
#endif

/*
 * JNI Types
 */

#ifndef JNI_TYPES_ALREADY_DEFINED_IN_JNI_MD_H

typedef unsigned char   jboolean;
typedef unsigned short  jchar;
typedef short           jshort;
typedef float           jfloat;
typedef double          jdouble;

typedef jint            jsize;

#ifdef __cplusplus

class _jobject {};
class _jclass : public _jobject {};
class _jthrowable : public _jobject {};
class _jstring : public _jobject {};
class _jarray : public _jobject {};
class _jbooleanArray : public _jarray {};
class _jbyteArray : public _jarray {};
class _jcharArray : public _jarray {};
class _jshortArray : public _jarray {};
class _jintArray : public _jarray {};
class _jlongArray : public _jarray {};
class _jfloatArray : public _jarray {};
class _jdoubleArray : public _jarray {};
class _jobjectArray : public _jarray {};

typedef _jobject *jobject;
typedef _jclass *jclass;
typedef _jthrowable *jthrowable;
typedef _jstring *jstring;
typedef _jarray *jarray;
typedef _jbooleanArray *jbooleanArray;
typedef _jbyteArray *jbyteArray;
typedef _jcharArray *jcharArray;
typedef _jshortArray *jshortArray;
typedef _jintArray *jintArray;
typedef _jlongArray *jlongArray;
typedef _jfloatArray *jfloatArray;
typedef _jdoubleArray *jdoubleArray;
typedef _jobjectArray *jobjectArray;

#else

struct _jobject;

typedef struct _jobject *jobject;
typedef jobject jclass;
typedef jobject jthrowable;
typedef jobject jstring;
typedef jobject jarray;
typedef jarray jbooleanArray;
typedef jarray jbyteArray;
typedef jarray jcharArray;
typedef jarray jshortArray;
typedef jarray jintArray;
typedef jarray jlongArray;
typedef jarray jfloatArray;
typedef jarray jdoubleArray;
typedef jarray jobjectArray;

#endif

typedef jobject jweak;

typedef union jvalue {
    jboolean z;
    jbyte    b;
    jchar    c;
    jshort   s;
    jint     i;
    jlong    j;
    jfloat   f;
    jdouble  d;
    jobject  l;
} jvalue;

struct _jfieldID;
typedef struct _jfieldID *jfieldID;

struct _jmethodID;
typedef struct _jmethodID *jmethodID;

/* Return values from jobjectRefType */
typedef enum _jobjectType {
     JNIInvalidRefType    = 0,
     JNILocalRefType      = 1,
     JNIGlobalRefType     = 2,
     JNIWeakGlobalRefType = 3
} jobjectRefType;


#endif /* JNI_TYPES_ALREADY_DEFINED_IN_JNI_MD_H */

/*
 * jboolean constants
 */

#define JNI_FALSE 0
#define JNI_TRUE 1

/*
 * possible return values for JNI functions.
 */

#define JNI_OK           0                 /* success */
#define JNI_ERR          (-1)              /* unknown error */
#define JNI_EDETACHED    (-2)              /* thread detached from the VM */
#define JNI_EVERSION     (-3)              /* JNI version error */
#define JNI_ENOMEM       (-4)              /* not enough memory */
#define JNI_EEXIST       (-5)              /* VM already created */
#define JNI_EINVAL       (-6)              /* invalid arguments */

/*
 * used in ReleaseScalarArrayElements
 */

#define JNI_COMMIT 1
#define JNI_ABORT 2

/*
 * used in RegisterNatives to describe native method name, signature,
 * and function pointer.
 */

typedef struct {
    char *name;
    char *signature;
    void *fnPtr;
} JNINativeMethod;

/*
 * JNI Native Method Interface.
 */

struct JNINativeInterface_;

struct JNIEnv_;

#ifdef __cplusplus
typedef JNIEnv_ JNIEnv;
#else
typedef const struct JNINativeInterface_ *JNIEnv;
#endif

/*
 * JNI Invocation Interface.
 */

struct JNIInvokeInterface_;

struct JavaVM_;

#ifdef __cplusplus
typedef JavaVM_ JavaVM;
#else
typedef const struct JNIInvokeInterface_ *JavaVM;
#endif

struct JNINativeInterface_ {
    void *reserved0;
    void *reserved1;
    void *reserved2;

    void *reserved3;
    jint (JNICALL *GetVersion)(JNIEnv *env);

    jclass (JNICALL *DefineClass)
      (JNIEnv *env, const char *name, jobject loader, const jbyte *buf,
       jsize len);
    jclass (JNICALL *FindClass)
      (JNIEnv *env, const char *name);

    jmethodID (JNICALL *FromReflectedMethod)
      (JNIEnv *env, jobject method);
    jfieldID (JNICALL *FromReflectedField)
      (JNIEnv *env, jobject field);

    jobject (JNICALL *ToReflectedMethod)
      (JNIEnv *env, jclass cls, jmethodID methodID, jboolean isStatic);

    jclass (JNICALL *GetSuperclass)
      (JNIEnv *env, jclass sub);
    jboolean (JNICALL *IsAssignableFrom)
      (JNIEnv *env, jclass sub, jclass sup);

    jobject (JNICALL *ToReflectedField)
      (JNIEnv *env, jclass cls, jfieldID fieldID, jboolean isStatic);

    jint (JNICALL *Throw)
      (JNIEnv *env, jthrowable obj);
    jint (JNICALL *ThrowNew)
      (JNIEnv *env, jclass clazz, const char *msg);
    jthrowable (JNICALL *ExceptionOccurred)
      (JNIEnv *env);
    void (JNICALL *ExceptionDescribe)
      (JNIEnv *env);
    void (JNICALL *ExceptionClear)
      (JNIEnv *env);
    void (JNICALL *FatalError)
      (JNIEnv *env, const char *msg);

    jint (JNICALL *PushLocalFrame)
      (JNIEnv *env, jint capacity);
    jobject (JNICALL *PopLocalFrame)
      (JNIEnv *env, jobject result);

    jobject (JNICALL *NewGlobalRef)
      (JNIEnv *env, jobject lobj);
    void (JNICALL *DeleteGlobalRef)
      (JNIEnv *env, jobject gref);
    void (JNICALL *DeleteLocalRef)
      (JNIEnv *env, jobject obj);
    jboolean (JNICALL *IsSameObject)
      (JNIEnv *env, jobject obj1, jobject obj2);
    jobject (JNICALL *NewLocalRef)
      (JNIEnv *env, jobject ref);
    jint (JNICALL *EnsureLocalCapacity)
      (JNIEnv *env, jint capacity);

    jobject (JNICALL *AllocObject)
      (JNIEnv *env, jclass clazz);
    jobject (JNICALL *NewObject)
      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
    jobject (JNICALL *NewObjectV)
      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
    jobject (JNICALL *NewObjectA)
      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);

    jclass (JNICALL *GetObjectClass)
      (JNIEnv *env, jobject obj);
    jboolean (JNICALL *IsInstanceOf)
      (JNIEnv *env, jobject obj, jclass clazz);

    jmethodID (JNICALL *GetMethodID)
      (JNIEnv *env, jclass clazz, const char *name, const char *sig);

    jobject (JNICALL *CallObjectMethod)
      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
    jobject (JNICALL *CallObjectMethodV)
      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
    jobject (JNICALL *CallObjectMethodA)
      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);

    jboolean (JNICALL *CallBooleanMethod)
      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
    jboolean (JNICALL *CallBooleanMethodV)
      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
    jboolean (JNICALL *CallBooleanMethodA)
      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);

    jbyte (JNICALL *CallByteMethod)
      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
    jbyte (JNICALL *CallByteMethodV)
      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
    jbyte (JNICALL *CallByteMethodA)
      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);

    jchar (JNICALL *CallCharMethod)
      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
    jchar (JNICALL *CallCharMethodV)
      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
    jchar (JNICALL *CallCharMethodA)
      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);

    jshort (JNICALL *CallShortMethod)
      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
    jshort (JNICALL *CallShortMethodV)
      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
    jshort (JNICALL *CallShortMethodA)
      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);

    jint (JNICALL *CallIntMethod)
      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
    jint (JNICALL *CallIntMethodV)
      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
    jint (JNICALL *CallIntMethodA)
      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);

    jlong (JNICALL *CallLongMethod)
      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
    jlong (JNICALL *CallLongMethodV)
      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
    jlong (JNICALL *CallLongMethodA)
      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);

    jfloat (JNICALL *CallFloatMethod)
      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
    jfloat (JNICALL *CallFloatMethodV)
      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
    jfloat (JNICALL *CallFloatMethodA)
      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);

    jdouble (JNICALL *CallDoubleMethod)
      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
    jdouble (JNICALL *CallDoubleMethodV)
      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
    jdouble (JNICALL *CallDoubleMethodA)
      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);

    void (JNICALL *CallVoidMethod)
      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
    void (JNICALL *CallVoidMethodV)
      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
    void (JNICALL *CallVoidMethodA)
      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);

    jobject (JNICALL *CallNonvirtualObjectMethod)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
    jobject (JNICALL *CallNonvirtualObjectMethodV)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       va_list args);
    jobject (JNICALL *CallNonvirtualObjectMethodA)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       const jvalue * args);

    jboolean (JNICALL *CallNonvirtualBooleanMethod)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
    jboolean (JNICALL *CallNonvirtualBooleanMethodV)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       va_list args);
    jboolean (JNICALL *CallNonvirtualBooleanMethodA)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       const jvalue * args);

    jbyte (JNICALL *CallNonvirtualByteMethod)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
    jbyte (JNICALL *CallNonvirtualByteMethodV)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       va_list args);
    jbyte (JNICALL *CallNonvirtualByteMethodA)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       const jvalue *args);

    jchar (JNICALL *CallNonvirtualCharMethod)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
    jchar (JNICALL *CallNonvirtualCharMethodV)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       va_list args);
    jchar (JNICALL *CallNonvirtualCharMethodA)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       const jvalue *args);

    jshort (JNICALL *CallNonvirtualShortMethod)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
    jshort (JNICALL *CallNonvirtualShortMethodV)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       va_list args);
    jshort (JNICALL *CallNonvirtualShortMethodA)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       const jvalue *args);

    jint (JNICALL *CallNonvirtualIntMethod)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
    jint (JNICALL *CallNonvirtualIntMethodV)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       va_list args);
    jint (JNICALL *CallNonvirtualIntMethodA)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       const jvalue *args);

    jlong (JNICALL *CallNonvirtualLongMethod)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
    jlong (JNICALL *CallNonvirtualLongMethodV)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       va_list args);
    jlong (JNICALL *CallNonvirtualLongMethodA)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       const jvalue *args);

    jfloat (JNICALL *CallNonvirtualFloatMethod)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
    jfloat (JNICALL *CallNonvirtualFloatMethodV)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       va_list args);
    jfloat (JNICALL *CallNonvirtualFloatMethodA)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       const jvalue *args);

    jdouble (JNICALL *CallNonvirtualDoubleMethod)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
    jdouble (JNICALL *CallNonvirtualDoubleMethodV)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       va_list args);
    jdouble (JNICALL *CallNonvirtualDoubleMethodA)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       const jvalue *args);

    void (JNICALL *CallNonvirtualVoidMethod)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
    void (JNICALL *CallNonvirtualVoidMethodV)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       va_list args);
    void (JNICALL *CallNonvirtualVoidMethodA)
      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
       const jvalue * args);

    jfieldID (JNICALL *GetFieldID)
      (JNIEnv *env, jclass clazz, const char *name, const char *sig);

    jobject (JNICALL *GetObjectField)
      (JNIEnv *env, jobject obj, jfieldID fieldID);
    jboolean (JNICALL *GetBooleanField)
      (JNIEnv *env, jobject obj, jfieldID fieldID);
    jbyte (JNICALL *GetByteField)
      (JNIEnv *env, jobject obj, jfieldID fieldID);
    jchar (JNICALL *GetCharField)
      (JNIEnv *env, jobject obj, jfieldID fieldID);
    jshort (JNICALL *GetShortField)
      (JNIEnv *env, jobject obj, jfieldID fieldID);
    jint (JNICALL *GetIntField)
      (JNIEnv *env, jobject obj, jfieldID fieldID);
    jlong (JNICALL *GetLongField)
      (JNIEnv *env, jobject obj, jfieldID fieldID);
    jfloat (JNICALL *GetFloatField)
      (JNIEnv *env, jobject obj, jfieldID fieldID);
    jdouble (JNICALL *GetDoubleField)
      (JNIEnv *env, jobject obj, jfieldID fieldID);

    void (JNICALL *SetObjectField)
      (JNIEnv *env, jobject obj, jfieldID fieldID, jobject val);
    void (JNICALL *SetBooleanField)
      (JNIEnv *env, jobject obj, jfieldID fieldID, jboolean val);
    void (JNICALL *SetByteField)
      (JNIEnv *env, jobject obj, jfieldID fieldID, jbyte val);
    void (JNICALL *SetCharField)
      (JNIEnv *env, jobject obj, jfieldID fieldID, jchar val);
    void (JNICALL *SetShortField)
      (JNIEnv *env, jobject obj, jfieldID fieldID, jshort val);
    void (JNICALL *SetIntField)
      (JNIEnv *env, jobject obj, jfieldID fieldID, jint val);
    void (JNICALL *SetLongField)
      (JNIEnv *env, jobject obj, jfieldID fieldID, jlong val);
    void (JNICALL *SetFloatField)
      (JNIEnv *env, jobject obj, jfieldID fieldID, jfloat val);
    void (JNICALL *SetDoubleField)
      (JNIEnv *env, jobject obj, jfieldID fieldID, jdouble val);

    jmethodID (JNICALL *GetStaticMethodID)
      (JNIEnv *env, jclass clazz, const char *name, const char *sig);

    jobject (JNICALL *CallStaticObjectMethod)
      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
    jobject (JNICALL *CallStaticObjectMethodV)
      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
    jobject (JNICALL *CallStaticObjectMethodA)
      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);

    jboolean (JNICALL *CallStaticBooleanMethod)
      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
    jboolean (JNICALL *CallStaticBooleanMethodV)
      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
    jboolean (JNICALL *CallStaticBooleanMethodA)
      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);

    jbyte (JNICALL *CallStaticByteMethod)
      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
    jbyte (JNICALL *CallStaticByteMethodV)
      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
    jbyte (JNICALL *CallStaticByteMethodA)
      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);

    jchar (JNICALL *CallStaticCharMethod)
      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
    jchar (JNICALL *CallStaticCharMethodV)
      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
    jchar (JNICALL *CallStaticCharMethodA)
      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);

    jshort (JNICALL *CallStaticShortMethod)
      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
    jshort (JNICALL *CallStaticShortMethodV)
      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
    jshort (JNICALL *CallStaticShortMethodA)
      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);

    jint (JNICALL *CallStaticIntMethod)
      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
    jint (JNICALL *CallStaticIntMethodV)
      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
    jint (JNICALL *CallStaticIntMethodA)
      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);

    jlong (JNICALL *CallStaticLongMethod)
      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
    jlong (JNICALL *CallStaticLongMethodV)
      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
    jlong (JNICALL *CallStaticLongMethodA)
      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);

    jfloat (JNICALL *CallStaticFloatMethod)
      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
    jfloat (JNICALL *CallStaticFloatMethodV)
      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
    jfloat (JNICALL *CallStaticFloatMethodA)
      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);

    jdouble (JNICALL *CallStaticDoubleMethod)
      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
    jdouble (JNICALL *CallStaticDoubleMethodV)
      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
    jdouble (JNICALL *CallStaticDoubleMethodA)
      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);

    void (JNICALL *CallStaticVoidMethod)
      (JNIEnv *env, jclass cls, jmethodID methodID, ...);
    void (JNICALL *CallStaticVoidMethodV)
      (JNIEnv *env, jclass cls, jmethodID methodID, va_list args);
    void (JNICALL *CallStaticVoidMethodA)
      (JNIEnv *env, jclass cls, jmethodID methodID, const jvalue * args);

    jfieldID (JNICALL *GetStaticFieldID)
      (JNIEnv *env, jclass clazz, const char *name, const char *sig);
    jobject (JNICALL *GetStaticObjectField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID);
    jboolean (JNICALL *GetStaticBooleanField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID);
    jbyte (JNICALL *GetStaticByteField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID);
    jchar (JNICALL *GetStaticCharField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID);
    jshort (JNICALL *GetStaticShortField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID);
    jint (JNICALL *GetStaticIntField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID);
    jlong (JNICALL *GetStaticLongField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID);
    jfloat (JNICALL *GetStaticFloatField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID);
    jdouble (JNICALL *GetStaticDoubleField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID);

    void (JNICALL *SetStaticObjectField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID, jobject value);
    void (JNICALL *SetStaticBooleanField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID, jboolean value);
    void (JNICALL *SetStaticByteField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID, jbyte value);
    void (JNICALL *SetStaticCharField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID, jchar value);
    void (JNICALL *SetStaticShortField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID, jshort value);
    void (JNICALL *SetStaticIntField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID, jint value);
    void (JNICALL *SetStaticLongField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID, jlong value);
    void (JNICALL *SetStaticFloatField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID, jfloat value);
    void (JNICALL *SetStaticDoubleField)
      (JNIEnv *env, jclass clazz, jfieldID fieldID, jdouble value);

    jstring (JNICALL *NewString)
      (JNIEnv *env, const jchar *unicode, jsize len);
    jsize (JNICALL *GetStringLength)
      (JNIEnv *env, jstring str);
    const jchar *(JNICALL *GetStringChars)
      (JNIEnv *env, jstring str, jboolean *isCopy);
    void (JNICALL *ReleaseStringChars)
      (JNIEnv *env, jstring str, const jchar *chars);

    jstring (JNICALL *NewStringUTF)
      (JNIEnv *env, const char *utf);
    jsize (JNICALL *GetStringUTFLength)
      (JNIEnv *env, jstring str);
    const char* (JNICALL *GetStringUTFChars)
      (JNIEnv *env, jstring str, jboolean *isCopy);
    void (JNICALL *ReleaseStringUTFChars)
      (JNIEnv *env, jstring str, const char* chars);


    jsize (JNICALL *GetArrayLength)
      (JNIEnv *env, jarray array);

    jobjectArray (JNICALL *NewObjectArray)
      (JNIEnv *env, jsize len, jclass clazz, jobject init);
    jobject (JNICALL *GetObjectArrayElement)
      (JNIEnv *env, jobjectArray array, jsize index);
    void (JNICALL *SetObjectArrayElement)
      (JNIEnv *env, jobjectArray array, jsize index, jobject val);

    jbooleanArray (JNICALL *NewBooleanArray)
      (JNIEnv *env, jsize len);
    jbyteArray (JNICALL *NewByteArray)
      (JNIEnv *env, jsize len);
    jcharArray (JNICALL *NewCharArray)
      (JNIEnv *env, jsize len);
    jshortArray (JNICALL *NewShortArray)
      (JNIEnv *env, jsize len);
    jintArray (JNICALL *NewIntArray)
      (JNIEnv *env, jsize len);
    jlongArray (JNICALL *NewLongArray)
      (JNIEnv *env, jsize len);
    jfloatArray (JNICALL *NewFloatArray)
      (JNIEnv *env, jsize len);
    jdoubleArray (JNICALL *NewDoubleArray)
      (JNIEnv *env, jsize len);

    jboolean * (JNICALL *GetBooleanArrayElements)
      (JNIEnv *env, jbooleanArray array, jboolean *isCopy);
    jbyte * (JNICALL *GetByteArrayElements)
      (JNIEnv *env, jbyteArray array, jboolean *isCopy);
    jchar * (JNICALL *GetCharArrayElements)
      (JNIEnv *env, jcharArray array, jboolean *isCopy);
    jshort * (JNICALL *GetShortArrayElements)
      (JNIEnv *env, jshortArray array, jboolean *isCopy);
    jint * (JNICALL *GetIntArrayElements)
      (JNIEnv *env, jintArray array, jboolean *isCopy);
    jlong * (JNICALL *GetLongArrayElements)
      (JNIEnv *env, jlongArray array, jboolean *isCopy);
    jfloat * (JNICALL *GetFloatArrayElements)
      (JNIEnv *env, jfloatArray array, jboolean *isCopy);
    jdouble * (JNICALL *GetDoubleArrayElements)
      (JNIEnv *env, jdoubleArray array, jboolean *isCopy);

    void (JNICALL *ReleaseBooleanArrayElements)
      (JNIEnv *env, jbooleanArray array, jboolean *elems, jint mode);
    void (JNICALL *ReleaseByteArrayElements)
      (JNIEnv *env, jbyteArray array, jbyte *elems, jint mode);
    void (JNICALL *ReleaseCharArrayElements)
      (JNIEnv *env, jcharArray array, jchar *elems, jint mode);
    void (JNICALL *ReleaseShortArrayElements)
      (JNIEnv *env, jshortArray array, jshort *elems, jint mode);
    void (JNICALL *ReleaseIntArrayElements)
      (JNIEnv *env, jintArray array, jint *elems, jint mode);
    void (JNICALL *ReleaseLongArrayElements)
      (JNIEnv *env, jlongArray array, jlong *elems, jint mode);
    void (JNICALL *ReleaseFloatArrayElements)
      (JNIEnv *env, jfloatArray array, jfloat *elems, jint mode);
    void (JNICALL *ReleaseDoubleArrayElements)
      (JNIEnv *env, jdoubleArray array, jdouble *elems, jint mode);

    void (JNICALL *GetBooleanArrayRegion)
      (JNIEnv *env, jbooleanArray array, jsize start, jsize l, jboolean *buf);
    void (JNICALL *GetByteArrayRegion)
      (JNIEnv *env, jbyteArray array, jsize start, jsize len, jbyte *buf);
    void (JNICALL *GetCharArrayRegion)
      (JNIEnv *env, jcharArray array, jsize start, jsize len, jchar *buf);
    void (JNICALL *GetShortArrayRegion)
      (JNIEnv *env, jshortArray array, jsize start, jsize len, jshort *buf);
    void (JNICALL *GetIntArrayRegion)
      (JNIEnv *env, jintArray array, jsize start, jsize len, jint *buf);
    void (JNICALL *GetLongArrayRegion)
      (JNIEnv *env, jlongArray array, jsize start, jsize len, jlong *buf);
    void (JNICALL *GetFloatArrayRegion)
      (JNIEnv *env, jfloatArray array, jsize start, jsize len, jfloat *buf);
    void (JNICALL *GetDoubleArrayRegion)
      (JNIEnv *env, jdoubleArray array, jsize start, jsize len, jdouble *buf);

    void (JNICALL *SetBooleanArrayRegion)
      (JNIEnv *env, jbooleanArray array, jsize start, jsize l, const jboolean *buf);
    void (JNICALL *SetByteArrayRegion)
      (JNIEnv *env, jbyteArray array, jsize start, jsize len, const jbyte *buf);
    void (JNICALL *SetCharArrayRegion)
      (JNIEnv *env, jcharArray array, jsize start, jsize len, const jchar *buf);
    void (JNICALL *SetShortArrayRegion)
      (JNIEnv *env, jshortArray array, jsize start, jsize len, const jshort *buf);
    void (JNICALL *SetIntArrayRegion)
      (JNIEnv *env, jintArray array, jsize start, jsize len, const jint *buf);
    void (JNICALL *SetLongArrayRegion)
      (JNIEnv *env, jlongArray array, jsize start, jsize len, const jlong *buf);
    void (JNICALL *SetFloatArrayRegion)
      (JNIEnv *env, jfloatArray array, jsize start, jsize len, const jfloat *buf);
    void (JNICALL *SetDoubleArrayRegion)
      (JNIEnv *env, jdoubleArray array, jsize start, jsize len, const jdouble *buf);

    jint (JNICALL *RegisterNatives)
      (JNIEnv *env, jclass clazz, const JNINativeMethod *methods,
       jint nMethods);
    jint (JNICALL *UnregisterNatives)
      (JNIEnv *env, jclass clazz);

    jint (JNICALL *MonitorEnter)
      (JNIEnv *env, jobject obj);
    jint (JNICALL *MonitorExit)
      (JNIEnv *env, jobject obj);

    jint (JNICALL *GetJavaVM)
      (JNIEnv *env, JavaVM **vm);

    void (JNICALL *GetStringRegion)
      (JNIEnv *env, jstring str, jsize start, jsize len, jchar *buf);
    void (JNICALL *GetStringUTFRegion)
      (JNIEnv *env, jstring str, jsize start, jsize len, char *buf);

    void * (JNICALL *GetPrimitiveArrayCritical)
      (JNIEnv *env, jarray array, jboolean *isCopy);
    void (JNICALL *ReleasePrimitiveArrayCritical)
      (JNIEnv *env, jarray array, void *carray, jint mode);

    const jchar * (JNICALL *GetStringCritical)
      (JNIEnv *env, jstring string, jboolean *isCopy);
    void (JNICALL *ReleaseStringCritical)
      (JNIEnv *env, jstring string, const jchar *cstring);

    jweak (JNICALL *NewWeakGlobalRef)
       (JNIEnv *env, jobject obj);
    void (JNICALL *DeleteWeakGlobalRef)
       (JNIEnv *env, jweak ref);

    jboolean (JNICALL *ExceptionCheck)
       (JNIEnv *env);

    jobject (JNICALL *NewDirectByteBuffer)
       (JNIEnv* env, void* address, jlong capacity);
    void* (JNICALL *GetDirectBufferAddress)
       (JNIEnv* env, jobject buf);
    jlong (JNICALL *GetDirectBufferCapacity)
       (JNIEnv* env, jobject buf);

    /* New JNI 1.6 Features */

    jobjectRefType (JNICALL *GetObjectRefType)
        (JNIEnv* env, jobject obj);

    /* Module Features */

    jobject (JNICALL *GetModule)
       (JNIEnv* env, jclass clazz);

    /* Virtual threads */

    jboolean (JNICALL *IsVirtualThread)
       (JNIEnv* env, jobject obj);
};

/*
 * We use inlined functions for C++ so that programmers can write:
 *
 *    env->FindClass("java/lang/String")
 *
 * in C++ rather than:
 *
 *    (*env)->FindClass(env, "java/lang/String")
 *
 * in C.
 */

struct JNIEnv_ {
    const struct JNINativeInterface_ *functions;
#ifdef __cplusplus

    jint GetVersion() {
        return functions->GetVersion(this);
    }
    jclass DefineClass(const char *name, jobject loader, const jbyte *buf,
                       jsize len) {
        return functions->DefineClass(this, name, loader, buf, len);
    }
    jclass FindClass(const char *name) {
        return functions->FindClass(this, name);
    }
    jmethodID FromReflectedMethod(jobject method) {
        return functions->FromReflectedMethod(this,method);
    }
    jfieldID FromReflectedField(jobject field) {
        return functions->FromReflectedField(this,field);
    }

    jobject ToReflectedMethod(jclass cls, jmethodID methodID, jboolean isStatic) {
        return functions->ToReflectedMethod(this, cls, methodID, isStatic);
    }

    jclass GetSuperclass(jclass sub) {
        return functions->GetSuperclass(this, sub);
    }
    jboolean IsAssignableFrom(jclass sub, jclass sup) {
        return functions->IsAssignableFrom(this, sub, sup);
    }

    jobject ToReflectedField(jclass cls, jfieldID fieldID, jboolean isStatic) {
        return functions->ToReflectedField(this,cls,fieldID,isStatic);
    }

    jint Throw(jthrowable obj) {
        return functions->Throw(this, obj);
    }
    jint ThrowNew(jclass clazz, const char *msg) {
        return functions->ThrowNew(this, clazz, msg);
    }
    jthrowable ExceptionOccurred() {
        return functions->ExceptionOccurred(this);
    }
    void ExceptionDescribe() {
        functions->ExceptionDescribe(this);
    }
    void ExceptionClear() {
        functions->ExceptionClear(this);
    }
    void FatalError(const char *msg) {
        functions->FatalError(this, msg);
    }

    jint PushLocalFrame(jint capacity) {
        return functions->PushLocalFrame(this,capacity);
    }
    jobject PopLocalFrame(jobject result) {
        return functions->PopLocalFrame(this,result);
    }

    jobject NewGlobalRef(jobject lobj) {
        return functions->NewGlobalRef(this,lobj);
    }
    void DeleteGlobalRef(jobject gref) {
        functions->DeleteGlobalRef(this,gref);
    }
    void DeleteLocalRef(jobject obj) {
        functions->DeleteLocalRef(this, obj);
    }

    jboolean IsSameObject(jobject obj1, jobject obj2) {
        return functions->IsSameObject(this,obj1,obj2);
    }

    jobject NewLocalRef(jobject ref) {
        return functions->NewLocalRef(this,ref);
    }
    jint EnsureLocalCapacity(jint capacity) {
        return functions->EnsureLocalCapacity(this,capacity);
    }

    jobject AllocObject(jclass clazz) {
        return functions->AllocObject(this,clazz);
    }
    jobject NewObject(jclass clazz, jmethodID methodID, ...) {
        va_list args;
        jobject result;
        va_start(args, methodID);
        result = functions->NewObjectV(this,clazz,methodID,args);
        va_end(args);
        return result;
    }
    jobject NewObjectV(jclass clazz, jmethodID methodID,
                       va_list args) {
        return functions->NewObjectV(this,clazz,methodID,args);
    }
    jobject NewObjectA(jclass clazz, jmethodID methodID,
                       const jvalue *args) {
        return functions->NewObjectA(this,clazz,methodID,args);
    }

    jclass GetObjectClass(jobject obj) {
        return functions->GetObjectClass(this,obj);
    }
    jboolean IsInstanceOf(jobject obj, jclass clazz) {
        return functions->IsInstanceOf(this,obj,clazz);
    }

    jmethodID GetMethodID(jclass clazz, const char *name,
                          const char *sig) {
        return functions->GetMethodID(this,clazz,name,sig);
    }

    jobject CallObjectMethod(jobject obj, jmethodID methodID, ...) {
        va_list args;
        jobject result;
        va_start(args,methodID);
        result = functions->CallObjectMethodV(this,obj,methodID,args);
        va_end(args);
        return result;
    }
    jobject CallObjectMethodV(jobject obj, jmethodID methodID,
                        va_list args) {
        return functions->CallObjectMethodV(this,obj,methodID,args);
    }
    jobject CallObjectMethodA(jobject obj, jmethodID methodID,
                        const jvalue * args) {
        return functions->CallObjectMethodA(this,obj,methodID,args);
    }

    jboolean CallBooleanMethod(jobject obj,
                               jmethodID methodID, ...) {
        va_list args;
        jboolean result;
        va_start(args,methodID);
        result = functions->CallBooleanMethodV(this,obj,methodID,args);
        va_end(args);
        return result;
    }
    jboolean CallBooleanMethodV(jobject obj, jmethodID methodID,
                                va_list args) {
        return functions->CallBooleanMethodV(this,obj,methodID,args);
    }
    jboolean CallBooleanMethodA(jobject obj, jmethodID methodID,
                                const jvalue * args) {
        return functions->CallBooleanMethodA(this,obj,methodID, args);
    }

    jbyte CallByteMethod(jobject obj, jmethodID methodID, ...) {
        va_list args;
        jbyte result;
        va_start(args,methodID);
        result = functions->CallByteMethodV(this,obj,methodID,args);
        va_end(args);
        return result;
    }
    jbyte CallByteMethodV(jobject obj, jmethodID methodID,
                          va_list args) {
        return functions->CallByteMethodV(this,obj,methodID,args);
    }
    jbyte CallByteMethodA(jobject obj, jmethodID methodID,
                          const jvalue * args) {
        return functions->CallByteMethodA(this,obj,methodID,args);
    }

    jchar CallCharMethod(jobject obj, jmethodID methodID, ...) {
        va_list args;
        jchar result;
        va_start(args,methodID);
        result = functions->CallCharMethodV(this,obj,methodID,args);
        va_end(args);
        return result;
    }
    jchar CallCharMethodV(jobject obj, jmethodID methodID,
                          va_list args) {
        return functions->CallCharMethodV(this,obj,methodID,args);
    }
    jchar CallCharMethodA(jobject obj, jmethodID methodID,
                          const jvalue * args) {
        return functions->CallCharMethodA(this,obj,methodID,args);
    }

    jshort CallShortMethod(jobject obj, jmethodID methodID, ...) {
        va_list args;
        jshort result;
        va_start(args,methodID);
        result = functions->CallShortMethodV(this,obj,methodID,args);
        va_end(args);
        return result;
    }
    jshort CallShortMethodV(jobject obj, jmethodID methodID,
                            va_list args) {
        return functions->CallShortMethodV(this,obj,methodID,args);
    }
    jshort CallShortMethodA(jobject obj, jmethodID methodID,
                            const jvalue * args) {
        return functions->CallShortMethodA(this,obj,methodID,args);
    }

    jint CallIntMethod(jobject obj, jmethodID methodID, ...) {
        va_list args;
        jint result;
        va_start(args,methodID);
        result = functions->CallIntMethodV(this,obj,methodID,args);
        va_end(args);
        return result;
    }
    jint CallIntMethodV(jobject obj, jmethodID methodID,
                        va_list args) {
        return functions->CallIntMethodV(this,obj,methodID,args);
    }
    jint CallIntMethodA(jobject obj, jmethodID methodID,
                        const jvalue * args) {
        return functions->CallIntMethodA(this,obj,methodID,args);
    }

    jlong CallLongMethod(jobject obj, jmethodID methodID, ...) {
        va_list args;
        jlong result;
        va_start(args,methodID);
        result = functions->CallLongMethodV(this,obj,methodID,args);
        va_end(args);
        return result;
    }
    jlong CallLongMethodV(jobject obj, jmethodID methodID,
                          va_list args) {
        return functions->CallLongMethodV(this,obj,methodID,args);
    }
    jlong CallLongMethodA(jobject obj, jmethodID methodID,
                          const jvalue * args) {
        return functions->CallLongMethodA(this,obj,methodID,args);
    }

    jfloat CallFloatMethod(jobject obj, jmethodID methodID, ...) {
        va_list args;
        jfloat result;
        va_start(args,methodID);
        result = functions->CallFloatMethodV(this,obj,methodID,args);
        va_end(args);
        return result;
    }
    jfloat CallFloatMethodV(jobject obj, jmethodID methodID,
                            va_list args) {
        return functions->CallFloatMethodV(this,obj,methodID,args);
    }
    jfloat CallFloatMethodA(jobject obj, jmethodID methodID,
                            const jvalue * args) {
        return functions->CallFloatMethodA(this,obj,methodID,args);
    }

    jdouble CallDoubleMethod(jobject obj, jmethodID methodID, ...) {
        va_list args;
        jdouble result;
        va_start(args,methodID);
        result = functions->CallDoubleMethodV(this,obj,methodID,args);
        va_end(args);
        return result;
    }
    jdouble CallDoubleMethodV(jobject obj, jmethodID methodID,
                        va_list args) {
        return functions->CallDoubleMethodV(this,obj,methodID,args);
    }
    jdouble CallDoubleMethodA(jobject obj, jmethodID methodID,
                        const jvalue * args) {
        return functions->CallDoubleMethodA(this,obj,methodID,args);
    }

    void CallVoidMethod(jobject obj, jmethodID methodID, ...) {
        va_list args;
        va_start(args,methodID);
        functions->CallVoidMethodV(this,obj,methodID,args);
        va_end(args);
    }
    void CallVoidMethodV(jobject obj, jmethodID methodID,
                         va_list args) {
        functions->CallVoidMethodV(this,obj,methodID,args);
    }
    void CallVoidMethodA(jobject obj, jmethodID methodID,
                         const jvalue * args) {
        functions->CallVoidMethodA(this,obj,methodID,args);
    }

    jobject CallNonvirtualObjectMethod(jobject obj, jclass clazz,
                                       jmethodID methodID, ...) {
        va_list args;
        jobject result;
        va_start(args,methodID);
        result = functions->CallNonvirtualObjectMethodV(this,obj,clazz,
                                                        methodID,args);
        va_end(args);
        return result;
    }
    jobject CallNonvirtualObjectMethodV(jobject obj, jclass clazz,
                                        jmethodID methodID, va_list args) {
        return functions->CallNonvirtualObjectMethodV(this,obj,clazz,
                                                      methodID,args);
    }
    jobject CallNonvirtualObjectMethodA(jobject obj, jclass clazz,
                                        jmethodID methodID, const jvalue * args) {
        return functions->CallNonvirtualObjectMethodA(this,obj,clazz,
                                                      methodID,args);
    }

    jboolean CallNonvirtualBooleanMethod(jobject obj, jclass clazz,
                                         jmethodID methodID, ...) {
        va_list args;
        jboolean result;
        va_start(args,methodID);
        result = functions->CallNonvirtualBooleanMethodV(this,obj,clazz,
                                                         methodID,args);
        va_end(args);
        return result;
    }
    jboolean CallNonvirtualBooleanMethodV(jobject obj, jclass clazz,
                                          jmethodID methodID, va_list args) {
        return functions->CallNonvirtualBooleanMethodV(this,obj,clazz,
                                                       methodID,args);
    }
    jboolean CallNonvirtualBooleanMethodA(jobject obj, jclass clazz,
                                          jmethodID methodID, const jvalue * args) {
        return functions->CallNonvirtualBooleanMethodA(this,obj,clazz,
                                                       methodID, args);
    }

    jbyte CallNonvirtualByteMethod(jobject obj, jclass clazz,
                                   jmethodID methodID, ...) {
        va_list args;
        jbyte result;
        va_start(args,methodID);
        result = functions->CallNonvirtualByteMethodV(this,obj,clazz,
                                                      methodID,args);
        va_end(args);
        return result;
    }
    jbyte CallNonvirtualByteMethodV(jobject obj, jclass clazz,
                                    jmethodID methodID, va_list args) {
        return functions->CallNonvirtualByteMethodV(this,obj,clazz,
                                                    methodID,args);
    }
    jbyte CallNonvirtualByteMethodA(jobject obj, jclass clazz,
                                    jmethodID methodID, const jvalue * args) {
        return functions->CallNonvirtualByteMethodA(this,obj,clazz,
                                                    methodID,args);
    }

    jchar CallNonvirtualCharMethod(jobject obj, jclass clazz,
                                   jmethodID methodID, ...) {
        va_list args;
        jchar result;
        va_start(args,methodID);
        result = functions->CallNonvirtualCharMethodV(this,obj,clazz,
                                                      methodID,args);
        va_end(args);
        return result;
    }
    jchar CallNonvirtualCharMethodV(jobject obj, jclass clazz,
                                    jmethodID methodID, va_list args) {
        return functions->CallNonvirtualCharMethodV(this,obj,clazz,
                                                    methodID,args);
    }
    jchar CallNonvirtualCharMethodA(jobject obj, jclass clazz,
                                    jmethodID methodID, const jvalue * args) {
        return functions->CallNonvirtualCharMethodA(this,obj,clazz,
                                                    methodID,args);
    }

    jshort CallNonvirtualShortMethod(jobject obj, jclass clazz,
                                     jmethodID methodID, ...) {
        va_list args;
        jshort result;
        va_start(args,methodID);
        result = functions->CallNonvirtualShortMethodV(this,obj,clazz,
                                                       methodID,args);
        va_end(args);
        return result;
    }
    jshort CallNonvirtualShortMethodV(jobject obj, jclass clazz,
                                      jmethodID methodID, va_list args) {
        return functions->CallNonvirtualShortMethodV(this,obj,clazz,
                                                     methodID,args);
    }
    jshort CallNonvirtualShortMethodA(jobject obj, jclass clazz,
                                      jmethodID methodID, const jvalue * args) {
        return functions->CallNonvirtualShortMethodA(this,obj,clazz,
                                                     methodID,args);
    }

    jint CallNonvirtualIntMethod(jobject obj, jclass clazz,
                                 jmethodID methodID, ...) {
        va_list args;
        jint result;
        va_start(args,methodID);
        result = functions->CallNonvirtualIntMethodV(this,obj,clazz,
                                                     methodID,args);
        va_end(args);
        return result;
    }
    jint CallNonvirtualIntMethodV(jobject obj, jclass clazz,
                                  jmethodID methodID, va_list args) {
        return functions->CallNonvirtualIntMethodV(this,obj,clazz,
                                                   methodID,args);
    }
    jint CallNonvirtualIntMethodA(jobject obj, jclass clazz,
                                  jmethodID methodID, const jvalue * args) {
        return functions->CallNonvirtualIntMethodA(this,obj,clazz,
                                                   methodID,args);
    }

    jlong CallNonvirtualLongMethod(jobject obj, jclass clazz,
                                   jmethodID methodID, ...) {
        va_list args;
        jlong result;
        va_start(args,methodID);
        result = functions->CallNonvirtualLongMethodV(this,obj,clazz,
                                                      methodID,args);
        va_end(args);
        return result;
    }
    jlong CallNonvirtualLongMethodV(jobject obj, jclass clazz,
                                    jmethodID methodID, va_list args) {
        return functions->CallNonvirtualLongMethodV(this,obj,clazz,
                                                    methodID,args);
    }
    jlong CallNonvirtualLongMethodA(jobject obj, jclass clazz,
                                    jmethodID methodID, const jvalue * args) {
        return functions->CallNonvirtualLongMethodA(this,obj,clazz,
                                                    methodID,args);
    }

    jfloat CallNonvirtualFloatMethod(jobject obj, jclass clazz,
                                     jmethodID methodID, ...) {
        va_list args;
        jfloat result;
        va_start(args,methodID);
        result = functions->CallNonvirtualFloatMethodV(this,obj,clazz,
                                                       methodID,args);
        va_end(args);
        return result;
    }
    jfloat CallNonvirtualFloatMethodV(jobject obj, jclass clazz,
                                      jmethodID methodID,
                                      va_list args) {
        return functions->CallNonvirtualFloatMethodV(this,obj,clazz,
                                                     methodID,args);
    }
    jfloat CallNonvirtualFloatMethodA(jobject obj, jclass clazz,
                                      jmethodID methodID,
                                      const jvalue * args) {
        return functions->CallNonvirtualFloatMethodA(this,obj,clazz,
                                                     methodID,args);
    }

    jdouble CallNonvirtualDoubleMethod(jobject obj, jclass clazz,
                                       jmethodID methodID, ...) {
        va_list args;
        jdouble result;
        va_start(args,methodID);
        result = functions->CallNonvirtualDoubleMethodV(this,obj,clazz,
                                                        methodID,args);
        va_end(args);
        return result;
    }
    jdouble CallNonvirtualDoubleMethodV(jobject obj, jclass clazz,
                                        jmethodID methodID,
                                        va_list args) {
        return functions->CallNonvirtualDoubleMethodV(this,obj,clazz,
                                                      methodID,args);
    }
    jdouble CallNonvirtualDoubleMethodA(jobject obj, jclass clazz,
                                        jmethodID methodID,
                                        const jvalue * args) {
        return functions->CallNonvirtualDoubleMethodA(this,obj,clazz,
                                                      methodID,args);
    }

    void CallNonvirtualVoidMethod(jobject obj, jclass clazz,
                                  jmethodID methodID, ...) {
        va_list args;
        va_start(args,methodID);
        functions->CallNonvirtualVoidMethodV(this,obj,clazz,methodID,args);
        va_end(args);
    }
    void CallNonvirtualVoidMethodV(jobject obj, jclass clazz,
                                   jmethodID methodID,
                                   va_list args) {
        functions->CallNonvirtualVoidMethodV(this,obj,clazz,methodID,args);
    }
    void CallNonvirtualVoidMethodA(jobject obj, jclass clazz,
                                   jmethodID methodID,
                                   const jvalue * args) {
        functions->CallNonvirtualVoidMethodA(this,obj,clazz,methodID,args);
    }

    jfieldID GetFieldID(jclass clazz, const char *name,
                        const char *sig) {
        return functions->GetFieldID(this,clazz,name,sig);
    }

    jobject GetObjectField(jobject obj, jfieldID fieldID) {
        return functions->GetObjectField(this,obj,fieldID);
    }
    jboolean GetBooleanField(jobject obj, jfieldID fieldID) {
        return functions->GetBooleanField(this,obj,fieldID);
    }
    jbyte GetByteField(jobject obj, jfieldID fieldID) {
        return functions->GetByteField(this,obj,fieldID);
    }
    jchar GetCharField(jobject obj, jfieldID fieldID) {
        return functions->GetCharField(this,obj,fieldID);
    }
    jshort GetShortField(jobject obj, jfieldID fieldID) {
        return functions->GetShortField(this,obj,fieldID);
    }
    jint GetIntField(jobject obj, jfieldID fieldID) {
        return functions->GetIntField(this,obj,fieldID);
    }
    jlong GetLongField(jobject obj, jfieldID fieldID) {
        return functions->GetLongField(this,obj,fieldID);
    }
    jfloat GetFloatField(jobject obj, jfieldID fieldID) {
        return functions->GetFloatField(this,obj,fieldID);
    }
    jdouble GetDoubleField(jobject obj, jfieldID fieldID) {
        return functions->GetDoubleField(this,obj,fieldID);
    }

    void SetObjectField(jobject obj, jfieldID fieldID, jobject val) {
        functions->SetObjectField(this,obj,fieldID,val);
    }
    void SetBooleanField(jobject obj, jfieldID fieldID,
                         jboolean val) {
        functions->SetBooleanField(this,obj,fieldID,val);
    }
    void SetByteField(jobject obj, jfieldID fieldID,
                      jbyte val) {
        functions->SetByteField(this,obj,fieldID,val);
    }
    void SetCharField(jobject obj, jfieldID fieldID,
                      jchar val) {
        functions->SetCharField(this,obj,fieldID,val);
    }
    void SetShortField(jobject obj, jfieldID fieldID,
                       jshort val) {
        functions->SetShortField(this,obj,fieldID,val);
    }
    void SetIntField(jobject obj, jfieldID fieldID,
                     jint val) {
        functions->SetIntField(this,obj,fieldID,val);
    }
    void SetLongField(jobject obj, jfieldID fieldID,
                      jlong val) {
        functions->SetLongField(this,obj,fieldID,val);
    }
    void SetFloatField(jobject obj, jfieldID fieldID,
                       jfloat val) {
        functions->SetFloatField(this,obj,fieldID,val);
    }
    void SetDoubleField(jobject obj, jfieldID fieldID,
                        jdouble val) {
        functions->SetDoubleField(this,obj,fieldID,val);
    }

    jmethodID GetStaticMethodID(jclass clazz, const char *name,
                                const char *sig) {
        return functions->GetStaticMethodID(this,clazz,name,sig);
    }

    jobject CallStaticObjectMethod(jclass clazz, jmethodID methodID,
                             ...) {
        va_list args;
        jobject result;
        va_start(args,methodID);
        result = functions->CallStaticObjectMethodV(this,clazz,methodID,args);
        va_end(args);
        return result;
    }
    jobject CallStaticObjectMethodV(jclass clazz, jmethodID methodID,
                              va_list args) {
        return functions->CallStaticObjectMethodV(this,clazz,methodID,args);
    }
    jobject CallStaticObjectMethodA(jclass clazz, jmethodID methodID,
                              const jvalue *args) {
        return functions->CallStaticObjectMethodA(this,clazz,methodID,args);
    }

    jboolean CallStaticBooleanMethod(jclass clazz,
                                     jmethodID methodID, ...) {
        va_list args;
        jboolean result;
        va_start(args,methodID);
        result = functions->CallStaticBooleanMethodV(this,clazz,methodID,args);
        va_end(args);
        return result;
    }
    jboolean CallStaticBooleanMethodV(jclass clazz,
                                      jmethodID methodID, va_list args) {
        return functions->CallStaticBooleanMethodV(this,clazz,methodID,args);
    }
    jboolean CallStaticBooleanMethodA(jclass clazz,
                                      jmethodID methodID, const jvalue *args) {
        return functions->CallStaticBooleanMethodA(this,clazz,methodID,args);
    }

    jbyte CallStaticByteMethod(jclass clazz,
                               jmethodID methodID, ...) {
        va_list args;
        jbyte result;
        va_start(args,methodID);
        result = functions->CallStaticByteMethodV(this,clazz,methodID,args);
        va_end(args);
        return result;
    }
    jbyte CallStaticByteMethodV(jclass clazz,
                                jmethodID methodID, va_list args) {
        return functions->CallStaticByteMethodV(this,clazz,methodID,args);
    }
    jbyte CallStaticByteMethodA(jclass clazz,
                                jmethodID methodID, const jvalue *args) {
        return functions->CallStaticByteMethodA(this,clazz,methodID,args);
    }

    jchar CallStaticCharMethod(jclass clazz,
                               jmethodID methodID, ...) {
        va_list args;
        jchar result;
        va_start(args,methodID);
        result = functions->CallStaticCharMethodV(this,clazz,methodID,args);
        va_end(args);
        return result;
    }
    jchar CallStaticCharMethodV(jclass clazz,
                                jmethodID methodID, va_list args) {
        return functions->CallStaticCharMethodV(this,clazz,methodID,args);
    }
    jchar CallStaticCharMethodA(jclass clazz,
                                jmethodID methodID, const jvalue *args) {
        return functions->CallStaticCharMethodA(this,clazz,methodID,args);
    }

    jshort CallStaticShortMethod(jclass clazz,
                                 jmethodID methodID, ...) {
        va_list args;
        jshort result;
        va_start(args,methodID);
        result = functions->CallStaticShortMethodV(this,clazz,methodID,args);
        va_end(args);
        return result;
    }
    jshort CallStaticShortMethodV(jclass clazz,
                                  jmethodID methodID, va_list args) {
        return functions->CallStaticShortMethodV(this,clazz,methodID,args);
    }
    jshort CallStaticShortMethodA(jclass clazz,
                                  jmethodID methodID, const jvalue *args) {
        return functions->CallStaticShortMethodA(this,clazz,methodID,args);
    }

    jint CallStaticIntMethod(jclass clazz,
                             jmethodID methodID, ...) {
        va_list args;
        jint result;
        va_start(args,methodID);
        result = functions->CallStaticIntMethodV(this,clazz,methodID,args);
        va_end(args);
        return result;
    }
    jint CallStaticIntMethodV(jclass clazz,
                              jmethodID methodID, va_list args) {
        return functions->CallStaticIntMethodV(this,clazz,methodID,args);
    }
    jint CallStaticIntMethodA(jclass clazz,
                              jmethodID methodID, const jvalue *args) {
        return functions->CallStaticIntMethodA(this,clazz,methodID,args);
    }

    jlong CallStaticLongMethod(jclass clazz,
                               jmethodID methodID, ...) {
        va_list args;
        jlong result;
        va_start(args,methodID);
        result = functions->CallStaticLongMethodV(this,clazz,methodID,args);
        va_end(args);
        return result;
    }
    jlong CallStaticLongMethodV(jclass clazz,
                                jmethodID methodID, va_list args) {
        return functions->CallStaticLongMethodV(this,clazz,methodID,args);
    }
    jlong CallStaticLongMethodA(jclass clazz,
                                jmethodID methodID, const jvalue *args) {
        return functions->CallStaticLongMethodA(this,clazz,methodID,args);
    }

    jfloat CallStaticFloatMethod(jclass clazz,
                                 jmethodID methodID, ...) {
        va_list args;
        jfloat result;
        va_start(args,methodID);
        result = functions->CallStaticFloatMethodV(this,clazz,methodID,args);
        va_end(args);
        return result;
    }
    jfloat CallStaticFloatMethodV(jclass clazz,
                                  jmethodID methodID, va_list args) {
        return functions->CallStaticFloatMethodV(this,clazz,methodID,args);
    }
    jfloat CallStaticFloatMethodA(jclass clazz,
                                  jmethodID methodID, const jvalue *args) {
        return functions->CallStaticFloatMethodA(this,clazz,methodID,args);
    }

    jdouble CallStaticDoubleMethod(jclass clazz,
                                   jmethodID methodID, ...) {
        va_list args;
        jdouble result;
        va_start(args,methodID);
        result = functions->CallStaticDoubleMethodV(this,clazz,methodID,args);
        va_end(args);
        return result;
    }
    jdouble CallStaticDoubleMethodV(jclass clazz,
                                    jmethodID methodID, va_list args) {
        return functions->CallStaticDoubleMethodV(this,clazz,methodID,args);
    }
    jdouble CallStaticDoubleMethodA(jclass clazz,
                                    jmethodID methodID, const jvalue *args) {
        return functions->CallStaticDoubleMethodA(this,clazz,methodID,args);
    }

    void CallStaticVoidMethod(jclass cls, jmethodID methodID, ...) {
        va_list args;
        va_start(args,methodID);
        functions->CallStaticVoidMethodV(this,cls,methodID,args);
        va_end(args);
    }
    void CallStaticVoidMethodV(jclass cls, jmethodID methodID,
                               va_list args) {
        functions->CallStaticVoidMethodV(this,cls,methodID,args);
    }
    void CallStaticVoidMethodA(jclass cls, jmethodID methodID,
                               const jvalue * args) {
        functions->CallStaticVoidMethodA(this,cls,methodID,args);
    }

    jfieldID GetStaticFieldID(jclass clazz, const char *name,
                              const char *sig) {
        return functions->GetStaticFieldID(this,clazz,name,sig);
    }
    jobject GetStaticObjectField(jclass clazz, jfieldID fieldID) {
        return functions->GetStaticObjectField(this,clazz,fieldID);
    }
    jboolean GetStaticBooleanField(jclass clazz, jfieldID fieldID) {
        return functions->GetStaticBooleanField(this,clazz,fieldID);
    }
    jbyte GetStaticByteField(jclass clazz, jfieldID fieldID) {
        return functions->GetStaticByteField(this,clazz,fieldID);
    }
    jchar GetStaticCharField(jclass clazz, jfieldID fieldID) {
        return functions->GetStaticCharField(this,clazz,fieldID);
    }
    jshort GetStaticShortField(jclass clazz, jfieldID fieldID) {
        return functions->GetStaticShortField(this,clazz,fieldID);
    }
    jint GetStaticIntField(jclass clazz, jfieldID fieldID) {
        return functions->GetStaticIntField(this,clazz,fieldID);
    }
    jlong GetStaticLongField(jclass clazz, jfieldID fieldID) {
        return functions->GetStaticLongField(this,clazz,fieldID);
    }
    jfloat GetStaticFloatField(jclass clazz, jfieldID fieldID) {
        return functions->GetStaticFloatField(this,clazz,fieldID);
    }
    jdouble GetStaticDoubleField(jclass clazz, jfieldID fieldID) {
        return functions->GetStaticDoubleField(this,clazz,fieldID);
    }

    void SetStaticObjectField(jclass clazz, jfieldID fieldID,
                        jobject value) {
      functions->SetStaticObjectField(this,clazz,fieldID,value);
    }
    void SetStaticBooleanField(jclass clazz, jfieldID fieldID,
                        jboolean value) {
      functions->SetStaticBooleanField(this,clazz,fieldID,value);
    }
    void SetStaticByteField(jclass clazz, jfieldID fieldID,
                        jbyte value) {
      functions->SetStaticByteField(this,clazz,fieldID,value);
    }
    void SetStaticCharField(jclass clazz, jfieldID fieldID,
                        jchar value) {
      functions->SetStaticCharField(this,clazz,fieldID,value);
    }
    void SetStaticShortField(jclass clazz, jfieldID fieldID,
                        jshort value) {
      functions->SetStaticShortField(this,clazz,fieldID,value);
    }
    void SetStaticIntField(jclass clazz, jfieldID fieldID,
                        jint value) {
      functions->SetStaticIntField(this,clazz,fieldID,value);
    }
    void SetStaticLongField(jclass clazz, jfieldID fieldID,
                        jlong value) {
      functions->SetStaticLongField(this,clazz,fieldID,value);
    }
    void SetStaticFloatField(jclass clazz, jfieldID fieldID,
                        jfloat value) {
      functions->SetStaticFloatField(this,clazz,fieldID,value);
    }
    void SetStaticDoubleField(jclass clazz, jfieldID fieldID,
                        jdouble value) {
      functions->SetStaticDoubleField(this,clazz,fieldID,value);
    }

    jstring NewString(const jchar *unicode, jsize len) {
        return functions->NewString(this,unicode,len);
    }
    jsize GetStringLength(jstring str) {
        return functions->GetStringLength(this,str);
    }
    const jchar *GetStringChars(jstring str, jboolean *isCopy) {
        return functions->GetStringChars(this,str,isCopy);
    }
    void ReleaseStringChars(jstring str, const jchar *chars) {
        functions->ReleaseStringChars(this,str,chars);
    }

    jstring NewStringUTF(const char *utf) {
        return functions->NewStringUTF(this,utf);
    }
    jsize GetStringUTFLength(jstring str) {
        return functions->GetStringUTFLength(this,str);
    }
    const char* GetStringUTFChars(jstring str, jboolean *isCopy) {
        return functions->GetStringUTFChars(this,str,isCopy);
    }
    void ReleaseStringUTFChars(jstring str, const char* chars) {
        functions->ReleaseStringUTFChars(this,str,chars);
    }

    jsize GetArrayLength(jarray array) {
        return functions->GetArrayLength(this,array);
    }

    jobjectArray NewObjectArray(jsize len, jclass clazz,
                                jobject init) {
        return functions->NewObjectArray(this,len,clazz,init);
    }
    jobject GetObjectArrayElement(jobjectArray array, jsize index) {
        return functions->GetObjectArrayElement(this,array,index);
    }
    void SetObjectArrayElement(jobjectArray array, jsize index,
                               jobject val) {
        functions->SetObjectArrayElement(this,array,index,val);
    }

    jbooleanArray NewBooleanArray(jsize len) {
        return functions->NewBooleanArray(this,len);
    }
    jbyteArray NewByteArray(jsize len) {
        return functions->NewByteArray(this,len);
    }
    jcharArray NewCharArray(jsize len) {
        return functions->NewCharArray(this,len);
    }
    jshortArray NewShortArray(jsize len) {
        return functions->NewShortArray(this,len);
    }
    jintArray NewIntArray(jsize len) {
        return functions->NewIntArray(this,len);
    }
    jlongArray NewLongArray(jsize len) {
        return functions->NewLongArray(this,len);
    }
    jfloatArray NewFloatArray(jsize len) {
        return functions->NewFloatArray(this,len);
    }
    jdoubleArray NewDoubleArray(jsize len) {
        return functions->NewDoubleArray(this,len);
    }

    jboolean * GetBooleanArrayElements(jbooleanArray array, jboolean *isCopy) {
        return functions->GetBooleanArrayElements(this,array,isCopy);
    }
    jbyte * GetByteArrayElements(jbyteArray array, jboolean *isCopy) {
        return functions->GetByteArrayElements(this,array,isCopy);
    }
    jchar * GetCharArrayElements(jcharArray array, jboolean *isCopy) {
        return functions->GetCharArrayElements(this,array,isCopy);
    }
    jshort * GetShortArrayElements(jshortArray array, jboolean *isCopy) {
        return functions->GetShortArrayElements(this,array,isCopy);
    }
    jint * GetIntArrayElements(jintArray array, jboolean *isCopy) {
        return functions->GetIntArrayElements(this,array,isCopy);
    }
    jlong * GetLongArrayElements(jlongArray array, jboolean *isCopy) {
        return functions->GetLongArrayElements(this,array,isCopy);
    }
    jfloat * GetFloatArrayElements(jfloatArray array, jboolean *isCopy) {
        return functions->GetFloatArrayElements(this,array,isCopy);
    }
    jdouble * GetDoubleArrayElements(jdoubleArray array, jboolean *isCopy) {
        return functions->GetDoubleArrayElements(this,array,isCopy);
    }

    void ReleaseBooleanArrayElements(jbooleanArray array,
                                     jboolean *elems,
                                     jint mode) {
        functions->ReleaseBooleanArrayElements(this,array,elems,mode);
    }
    void ReleaseByteArrayElements(jbyteArray array,
                                  jbyte *elems,
                                  jint mode) {
        functions->ReleaseByteArrayElements(this,array,elems,mode);
    }
    void ReleaseCharArrayElements(jcharArray array,
                                  jchar *elems,
                                  jint mode) {
        functions->ReleaseCharArrayElements(this,array,elems,mode);
    }
    void ReleaseShortArrayElements(jshortArray array,
                                   jshort *elems,
                                   jint mode) {
        functions->ReleaseShortArrayElements(this,array,elems,mode);
    }
    void ReleaseIntArrayElements(jintArray array,
                                 jint *elems,
                                 jint mode) {
        functions->ReleaseIntArrayElements(this,array,elems,mode);
    }
    void ReleaseLongArrayElements(jlongArray array,
                                  jlong *elems,
                                  jint mode) {
        functions->ReleaseLongArrayElements(this,array,elems,mode);
    }
    void ReleaseFloatArrayElements(jfloatArray array,
                                   jfloat *elems,
                                   jint mode) {
        functions->ReleaseFloatArrayElements(this,array,elems,mode);
    }
    void ReleaseDoubleArrayElements(jdoubleArray array,
                                    jdouble *elems,
                                    jint mode) {
        functions->ReleaseDoubleArrayElements(this,array,elems,mode);
    }

    void GetBooleanArrayRegion(jbooleanArray array,
                               jsize start, jsize len, jboolean *buf) {
        functions->GetBooleanArrayRegion(this,array,start,len,buf);
    }
    void GetByteArrayRegion(jbyteArray array,
                            jsize start, jsize len, jbyte *buf) {
        functions->GetByteArrayRegion(this,array,start,len,buf);
    }
    void GetCharArrayRegion(jcharArray array,
                            jsize start, jsize len, jchar *buf) {
        functions->GetCharArrayRegion(this,array,start,len,buf);
    }
    void GetShortArrayRegion(jshortArray array,
                             jsize start, jsize len, jshort *buf) {
        functions->GetShortArrayRegion(this,array,start,len,buf);
    }
    void GetIntArrayRegion(jintArray array,
                           jsize start, jsize len, jint *buf) {
        functions->GetIntArrayRegion(this,array,start,len,buf);
    }
    void GetLongArrayRegion(jlongArray array,
                            jsize start, jsize len, jlong *buf) {
        functions->GetLongArrayRegion(this,array,start,len,buf);
    }
    void GetFloatArrayRegion(jfloatArray array,
                             jsize start, jsize len, jfloat *buf) {
        functions->GetFloatArrayRegion(this,array,start,len,buf);
    }
    void GetDoubleArrayRegion(jdoubleArray array,
                              jsize start, jsize len, jdouble *buf) {
        functions->GetDoubleArrayRegion(this,array,start,len,buf);
    }

    void SetBooleanArrayRegion(jbooleanArray array, jsize start, jsize len,
                               const jboolean *buf) {
        functions->SetBooleanArrayRegion(this,array,start,len,buf);
    }
    void SetByteArrayRegion(jbyteArray array, jsize start, jsize len,
                            const jbyte *buf) {
        functions->SetByteArrayRegion(this,array,start,len,buf);
    }
    void SetCharArrayRegion(jcharArray array, jsize start, jsize len,
                            const jchar *buf) {
        functions->SetCharArrayRegion(this,array,start,len,buf);
    }
    void SetShortArrayRegion(jshortArray array, jsize start, jsize len,
                             const jshort *buf) {
        functions->SetShortArrayRegion(this,array,start,len,buf);
    }
    void SetIntArrayRegion(jintArray array, jsize start, jsize len,
                           const jint *buf) {
        functions->SetIntArrayRegion(this,array,start,len,buf);
    }
    void SetLongArrayRegion(jlongArray array, jsize start, jsize len,
                            const jlong *buf) {
        functions->SetLongArrayRegion(this,array,start,len,buf);
    }
    void SetFloatArrayRegion(jfloatArray array, jsize start, jsize len,
                             const jfloat *buf) {
        functions->SetFloatArrayRegion(this,array,start,len,buf);
    }
    void SetDoubleArrayRegion(jdoubleArray array, jsize start, jsize len,
                              const jdouble *buf) {
        functions->SetDoubleArrayRegion(this,array,start,len,buf);
    }

    jint RegisterNatives(jclass clazz, const JNINativeMethod *methods,
                         jint nMethods) {
        return functions->RegisterNatives(this,clazz,methods,nMethods);
    }
    jint UnregisterNatives(jclass clazz) {
        return functions->UnregisterNatives(this,clazz);
    }

    jint MonitorEnter(jobject obj) {
        return functions->MonitorEnter(this,obj);
    }
    jint MonitorExit(jobject obj) {
        return functions->MonitorExit(this,obj);
    }

    jint GetJavaVM(JavaVM **vm) {
        return functions->GetJavaVM(this,vm);
    }

    void GetStringRegion(jstring str, jsize start, jsize len, jchar *buf) {
        functions->GetStringRegion(this,str,start,len,buf);
    }
    void GetStringUTFRegion(jstring str, jsize start, jsize len, char *buf) {
        functions->GetStringUTFRegion(this,str,start,len,buf);
    }

    void * GetPrimitiveArrayCritical(jarray array, jboolean *isCopy) {
        return functions->GetPrimitiveArrayCritical(this,array,isCopy);
    }
    void ReleasePrimitiveArrayCritical(jarray array, void *carray, jint mode) {
        functions->ReleasePrimitiveArrayCritical(this,array,carray,mode);
    }

    const jchar * GetStringCritical(jstring string, jboolean *isCopy) {
        return functions->GetStringCritical(this,string,isCopy);
    }
    void ReleaseStringCritical(jstring string, const jchar *cstring) {
        functions->ReleaseStringCritical(this,string,cstring);
    }

    jweak NewWeakGlobalRef(jobject obj) {
        return functions->NewWeakGlobalRef(this,obj);
    }
    void DeleteWeakGlobalRef(jweak ref) {
        functions->DeleteWeakGlobalRef(this,ref);
    }

    jboolean ExceptionCheck() {
        return functions->ExceptionCheck(this);
    }

    jobject NewDirectByteBuffer(void* address, jlong capacity) {
        return functions->NewDirectByteBuffer(this, address, capacity);
    }
    void* GetDirectBufferAddress(jobject buf) {
        return functions->GetDirectBufferAddress(this, buf);
    }
    jlong GetDirectBufferCapacity(jobject buf) {
        return functions->GetDirectBufferCapacity(this, buf);
    }
    jobjectRefType GetObjectRefType(jobject obj) {
        return functions->GetObjectRefType(this, obj);
    }

    /* Module Features */

    jobject GetModule(jclass clazz) {
        return functions->GetModule(this, clazz);
    }

    /* Virtual threads */

    jboolean IsVirtualThread(jobject obj) {
        return functions->IsVirtualThread(this, obj);
    }

#endif /* __cplusplus */
};

/*
 * optionString may be any option accepted by the JVM, or one of the
 * following:
 *
 * -D<name>=<value>          Set a system property.
 * -verbose[:class|gc|jni]   Enable verbose output, comma-separated. E.g.
 *                           "-verbose:class" or "-verbose:gc,class"
 *                           Standard names include: gc, class, and jni.
 *                           All nonstandard (VM-specific) names must begin
 *                           with "X".
 * vfprintf                  extraInfo is a pointer to the vfprintf hook.
 * exit                      extraInfo is a pointer to the exit hook.
 * abort                     extraInfo is a pointer to the abort hook.
 */
typedef struct JavaVMOption {
    char *optionString;
    void *extraInfo;
} JavaVMOption;

typedef struct JavaVMInitArgs {
    jint version;

    jint nOptions;
    JavaVMOption *options;
    jboolean ignoreUnrecognized;
} JavaVMInitArgs;

typedef struct JavaVMAttachArgs {
    jint version;

    char *name;
    jobject group;
} JavaVMAttachArgs;

/* These will be VM-specific. */

#define JDK1_2
#define JDK1_4

/* End VM-specific. */

struct JNIInvokeInterface_ {
    void *reserved0;
    void *reserved1;
    void *reserved2;

    jint (JNICALL *DestroyJavaVM)(JavaVM *vm);

    jint (JNICALL *AttachCurrentThread)(JavaVM *vm, void **penv, void *args);

    jint (JNICALL *DetachCurrentThread)(JavaVM *vm);

    jint (JNICALL *GetEnv)(JavaVM *vm, void **penv, jint version);

    jint (JNICALL *AttachCurrentThreadAsDaemon)(JavaVM *vm, void **penv, void *args);
};

struct JavaVM_ {
    const struct JNIInvokeInterface_ *functions;
#ifdef __cplusplus

    jint DestroyJavaVM() {
        return functions->DestroyJavaVM(this);
    }
    jint AttachCurrentThread(void **penv, void *args) {
        return functions->AttachCurrentThread(this, penv, args);
    }
    jint DetachCurrentThread() {
        return functions->DetachCurrentThread(this);
    }

    jint GetEnv(void **penv, jint version) {
        return functions->GetEnv(this, penv, version);
    }
    jint AttachCurrentThreadAsDaemon(void **penv, void *args) {
        return functions->AttachCurrentThreadAsDaemon(this, penv, args);
    }
#endif
};

#ifdef _JNI_IMPLEMENTATION_
#define _JNI_IMPORT_OR_EXPORT_ JNIEXPORT
#else
#define _JNI_IMPORT_OR_EXPORT_ JNIIMPORT
#endif
_JNI_IMPORT_OR_EXPORT_ jint JNICALL
JNI_GetDefaultJavaVMInitArgs(void *args);

_JNI_IMPORT_OR_EXPORT_ jint JNICALL
JNI_CreateJavaVM(JavaVM **pvm, void **penv, void *args);

_JNI_IMPORT_OR_EXPORT_ jint JNICALL
JNI_GetCreatedJavaVMs(JavaVM **, jsize, jsize *);

/* Defined by native libraries. */
JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM *vm, void *reserved);

JNIEXPORT void JNICALL
JNI_OnUnload(JavaVM *vm, void *reserved);

#define JNI_VERSION_1_1 0x00010001
#define JNI_VERSION_1_2 0x00010002
#define JNI_VERSION_1_4 0x00010004
#define JNI_VERSION_1_6 0x00010006
#define JNI_VERSION_1_8 0x00010008
#define JNI_VERSION_9   0x00090000
#define JNI_VERSION_10  0x000a0000
#define JNI_VERSION_19  0x00130000
#define JNI_VERSION_20  0x00140000
#define JNI_VERSION_21  0x00150000

#ifdef __cplusplus
} /* extern "C" */
#endif /* __cplusplus */

#endif /* !_JAVASOFT_JNI_H_ */
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/nativeInterop/cinterop/jni_md.h
### Write `vendor/yokan-ext/src/nativeInterop/cinterop/jni_md.h`

Create this path in your reconstruction project. Source set: **nativeInterop**. [Exact file download](../reference/source/vendor/yokan-ext/src/nativeInterop/cinterop/jni_md.h).

```cpp
/*
 * Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

#ifndef _JAVASOFT_JNI_MD_H_
#define _JAVASOFT_JNI_MD_H_

#ifndef __has_attribute
  #define __has_attribute(x) 0
#endif

#ifndef JNIEXPORT
  #if (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4) && (__GNUC_MINOR__ > 2))) || __has_attribute(visibility)
    #ifdef ARM
      #define JNIEXPORT     __attribute__((externally_visible,visibility("default")))
    #else
      #define JNIEXPORT     __attribute__((visibility("default")))
    #endif
  #else
    #define JNIEXPORT
  #endif
#endif

#if (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4) && (__GNUC_MINOR__ > 2))) || __has_attribute(visibility)
  #ifdef ARM
    #define JNIIMPORT     __attribute__((externally_visible,visibility("default")))
  #else
    #define JNIIMPORT     __attribute__((visibility("default")))
  #endif
#else
  #define JNIIMPORT
#endif

#define JNICALL

typedef int jint;
#ifdef _LP64
typedef long jlong;
#else
typedef long long jlong;
#endif

typedef signed char jbyte;

#endif /* !_JAVASOFT_JNI_MD_H_ */
```
[chapter-file-end]: #

### Check your understanding

Trace the common start call through the iOS actual and host bridge. Identify which binary/framework must exist on device and what the simulator returns without it.
[chapter-content-end]: #


[chapter-content-start]: #
## Recreate the tests and verify the chapter

Run the submodule's shared contract/release tests, desktop installer/process fixtures, Android invoker/ABI tests and iOS installation checks from its own Gradle root. Inspect its tasks after recreating the pinned build. Main-app fixture success does not establish that a real third-party APK or embedded runtime loads.

These are source tests to reproduce and run in your reconstruction. Their inclusion here is not a claim that application/native/device tests were executed while writing the guide.

[chapter-file-start]: #vendor/yokan-ext/src/androidHostTest/kotlin/eu/friedcutlet/yokan/ext/CastBridgeCompatibilityTest.kt
### Write `vendor/yokan-ext/src/androidHostTest/kotlin/eu/friedcutlet/yokan/ext/CastBridgeCompatibilityTest.kt`

Create this path in your reconstruction project. Source set: **androidHostTest**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidHostTest/kotlin/eu/friedcutlet/yokan/ext/CastBridgeCompatibilityTest.kt).

The implementation below defines `CastBridgeCompatibilityTest`, `SAnime`, `LegacyAnime`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `classCompiledAgainstAnOlderInterfaceLinksAgainstTheCurrentHost`
- `hostAnimeCreditsSurviveCopyAndBridgeSerialization`
- `legacyExtensionWithoutAccessorStillReturnsDetails`
- `explicitEmptyCreditsRemainAnExplicitClear`

```kotlin
package eu.friedcutlet.yokan.ext

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import eu.kanade.tachiyomi.animesource.model.Credit
import eu.kanade.tachiyomi.animesource.model.SAnime
import kotlinx.serialization.json.Json
import m_extension_server.model.toJAnime
import java.net.URLClassLoader
import java.nio.file.Files
import javax.tools.ToolProvider
import kotlin.test.*

class CastBridgeCompatibilityTest {
    @Test fun classCompiledAgainstAnOlderInterfaceLinksAgainstTheCurrentHost() {
        val directory = Files.createTempDirectory("yokan-legacy-anime-api").toFile()
        try {
            val source = directory.resolve("eu/kanade/tachiyomi/animesource/model").apply { mkdirs() }
            // Deliberately compile without the new cast member, then load against the real host.
            source.resolve("SAnime.java").writeText("""
                package eu.kanade.tachiyomi.animesource.model;
                public interface SAnime {
                    String getUrl(); String getTitle(); String getArtist(); String getAuthor();
                    String getDescription(); String getGenre(); String getThumbnail_url();
                    int getStatus(); boolean getInitialized();
                }
            """.trimIndent())
            source.resolve("LegacyAnime.java").writeText("""
                package eu.kanade.tachiyomi.animesource.model;
                public class LegacyAnime implements SAnime {
                    public String getUrl() { return "/legacy-binary"; }
                    public String getTitle() { return "Old binary"; }
                    public String getArtist() { return null; }
                    public String getAuthor() { return "Author"; }
                    public String getDescription() { return null; }
                    public String getGenre() { return null; }
                    public String getThumbnail_url() { return null; }
                    public int getStatus() { return 1; }
                    public boolean getInitialized() { return true; }
                }
            """.trimIndent())
            val compiler = requireNotNull(ToolProvider.getSystemJavaCompiler()) { "Run bridge unit tests with a JDK" }
            assertEquals(0, compiler.run(null, null, null, "-d", directory.path,
                source.resolve("SAnime.java").path, source.resolve("LegacyAnime.java").path))
            URLClassLoader(arrayOf(directory.toURI().toURL()), SAnime::class.java.classLoader).use { loader ->
                val old = loader.loadClass("eu.kanade.tachiyomi.animesource.model.LegacyAnime")
                    .getDeclaredConstructor().newInstance() as SAnime
                assertEquals("Old binary", old.toJAnime().title)
                assertNull(old.toJAnime().cast)
                assertEquals("Episodes", old.toJAnime().fetch_type)
                assertEquals(-1.0, old.toJAnime().season_number)
                val copy = SAnime.create().apply { url = old.url; copyFrom(old) }
                assertEquals("Author", copy.author)
                assertNull(copy.cast)
                assertEquals(eu.kanade.tachiyomi.animesource.model.FetchType.Episodes, copy.fetch_type)
            }
        } finally { directory.deleteRecursively() }
    }

    @Test fun hostAnimeCreditsSurviveCopyAndBridgeSerialization() {
        val credit = Credit("Actor", "Voice actor", "Hero", "https://cdn.example/actor.jpg")
        val anime = SAnime.create().apply {
            url = "/title"
            title = "Title"
            status = SAnime.UPCOMING
            cast = listOf(credit)
        }
        val copy = SAnime.create().apply { url = anime.url; copyFrom(anime) }
        assertEquals(listOf(credit), copy.cast)
        assertEquals(SAnime.UPCOMING, copy.status)
        assertEquals(credit, Json.decodeFromString<Credit>(Json.encodeToString(Credit.serializer(), credit)))

        val mapper = jacksonObjectMapper()
        val json = mapper.readTree(mapper.writeValueAsString(copy.toJAnime()))
        assertEquals("Actor", json["cast"][0]["name"].asText())
        assertEquals("https://cdn.example/actor.jpg", json["cast"][0]["image_url"].asText())
        assertEquals("Hero", json["cast"][0]["character"].asText())
        assertEquals(7, json["status"].asInt())
    }

    @Test fun legacyExtensionWithoutAccessorStillReturnsDetails() {
        val base = SAnime.create().apply { url = "/legacy"; title = "Legacy title" }
        val oldBinary = object : SAnime by base {
            override var cast: List<Credit>?
                get() = throw AbstractMethodError("Older APK has no getCast accessor")
                set(_) { throw AbstractMethodError("Older APK has no setCast accessor") }
        }
        assertEquals("Legacy title", oldBinary.toJAnime().title)
        assertNull(oldBinary.toJAnime().cast)
        val copy = SAnime.create().apply { url = oldBinary.url; copyFrom(oldBinary) }
        assertEquals("Legacy title", copy.title)
        assertNull(copy.cast)
    }

    @Test fun explicitEmptyCreditsRemainAnExplicitClear() {
        val anime = SAnime.create().apply { url = "/title"; title = "Title"; cast = emptyList() }
        val copy = SAnime.create().apply { url = anime.url; cast = listOf(Credit("Old")); copyFrom(anime) }
        assertEquals(emptyList(), copy.toJAnime().cast)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidHostTest/kotlin/eu/friedcutlet/yokan/ext/RelatedBridgeTest.kt
### Write `vendor/yokan-ext/src/androidHostTest/kotlin/eu/friedcutlet/yokan/ext/RelatedBridgeTest.kt`

Create this path in your reconstruction project. Source set: **androidHostTest**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidHostTest/kotlin/eu/friedcutlet/yokan/ext/RelatedBridgeTest.kt).

The implementation below defines `RelatedBridgeTest`, `getRelatedAnimeList`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `forwardsGroupedSourceRelationsAndAdvertisesUnsupportedWithoutCallingIt`

```kotlin
package eu.friedcutlet.yokan.ext

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import eu.kanade.tachiyomi.animesource.AnimeSource
import eu.kanade.tachiyomi.animesource.model.AnimeRelation
import eu.kanade.tachiyomi.animesource.model.SAnime
import m_extension_server.impl.MihonInvoker
import m_extension_server.model.AnimeData
import kotlin.test.*

class RelatedBridgeTest {
    private val data = AnimeData("/parent", "Parent", null, null, null, null, null, null, null)
    @Test fun forwardsGroupedSourceRelationsAndAdvertisesUnsupportedWithoutCallingIt() {
        var calls = 0
        val source = object : AnimeSource {
            override val id = 42L
            override val name = "Source"
            override val supportsRelatedAnime = true
            override suspend fun getRelatedAnimeList(anime: SAnime): List<AnimeRelation> {
                calls++
                assertEquals("/parent", anime.url)
                return listOf(AnimeRelation("Sequel", listOf(SAnime.create().apply { url = "/next"; title = "Next" })))
            }
        }
        val mapper = jacksonObjectMapper()
        val json = mapper.readTree(mapper.writeValueAsString(MihonInvoker.invokeGetRelatedAnimeList(source, data)))
        assertTrue(json["supported"].asBoolean())
        assertEquals("Sequel", json["groups"][0]["name"].asText())
        assertEquals("/next", json["groups"][0]["animes"][0]["url"].asText())
        val unsupported = object : AnimeSource by source { override val supportsRelatedAnime = false }
        assertEquals(false, MihonInvoker.invokeGetRelatedAnimeList(unsupported, data)["supported"])
        assertEquals(1, calls)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/androidHostTest/kotlin/eu/friedcutlet/yokan/ext/SeasonBridgeTest.kt
### Write `vendor/yokan-ext/src/androidHostTest/kotlin/eu/friedcutlet/yokan/ext/SeasonBridgeTest.kt`

Create this path in your reconstruction project. Source set: **androidHostTest**. [Exact file download](../reference/source/vendor/yokan-ext/src/androidHostTest/kotlin/eu/friedcutlet/yokan/ext/SeasonBridgeTest.kt).

The implementation below defines `SeasonBridgeTest`, `getSeasonList`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `forwardsSeasonEntriesWithFetchTypeAndNumber`
- `olderSourcesListNoSeasonsAndDetailsStayEpisodeLists`

```kotlin
package eu.friedcutlet.yokan.ext

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import eu.kanade.tachiyomi.animesource.AnimeSource
import eu.kanade.tachiyomi.animesource.model.FetchType
import eu.kanade.tachiyomi.animesource.model.SAnime
import m_extension_server.impl.MihonInvoker
import m_extension_server.model.AnimeData
import m_extension_server.model.toJAnime
import kotlin.test.*

class SeasonBridgeTest {
    private val data = AnimeData("/show", "Show", null, null, null, null, null, null, null)
    private val mapper = jacksonObjectMapper()

    @Test fun forwardsSeasonEntriesWithFetchTypeAndNumber() {
        val source = object : AnimeSource {
            override val id = 7L
            override val name = "Source"
            override suspend fun getSeasonList(anime: SAnime): List<SAnime> {
                assertEquals("/show", anime.url)
                return listOf(
                    SAnime.create().apply { url = "/show/s1"; title = "Season 1"; season_number = 1.0 },
                    SAnime.create().apply { url = "/show/movies"; title = "Movies"; fetch_type = FetchType.Seasons },
                )
            }
        }
        val json = mapper.readTree(mapper.writeValueAsString(MihonInvoker.invokeGetSeasonList(source, data)))
        assertEquals("/show/s1", json[0]["url"].asText())
        assertEquals(1.0, json[0]["season_number"].asDouble())
        assertEquals("Episodes", json[0]["fetch_type"].asText())
        assertEquals("Seasons", json[1]["fetch_type"].asText())
        assertEquals(-1.0, json[1]["season_number"].asDouble())
    }

    @Test fun olderSourcesListNoSeasonsAndDetailsStayEpisodeLists() {
        val source = object : AnimeSource { override val id = 8L; override val name = "Old" }
        assertEquals(emptyList(), MihonInvoker.invokeGetSeasonList(source, data))
        val parent = SAnime.create().apply { url = "/show"; title = "Show"; fetch_type = FetchType.Seasons }
        assertEquals("Seasons", mapper.readTree(mapper.writeValueAsString(parent.toJAnime()))["fetch_type"].asText())
        val copy = SAnime.create().apply { url = parent.url; copyFrom(parent) }
        assertEquals(FetchType.Seasons, copy.fetch_type)
        assertFailsWith<IllegalArgumentException> { MihonInvoker.invokeGetSeasonList(source, null) }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/commonTest/kotlin/eu/friedcutlet/yokan/ext/ExtensionServerContractTest.kt
### Write `vendor/yokan-ext/src/commonTest/kotlin/eu/friedcutlet/yokan/ext/ExtensionServerContractTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/vendor/yokan-ext/src/commonTest/kotlin/eu/friedcutlet/yokan/ext/ExtensionServerContractTest.kt).

The implementation below defines `ExtensionServerContractTest`, `configBuildsLoopbackUrl`, `configRejectsInvalidPorts`, `runningStatusExposesLoopbackUrl`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `configBuildsLoopbackUrl`
- `configRejectsInvalidPorts`
- `runningStatusExposesLoopbackUrl`

```kotlin
package eu.friedcutlet.yokan.ext

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith

class ExtensionServerContractTest {
    @Test
    fun configBuildsLoopbackUrl() {
        assertEquals("http://127.0.0.1:8080", ExtensionServerConfig(8080).baseUrl)
    }

    @Test
    fun configRejectsInvalidPorts() {
        assertFailsWith<IllegalArgumentException> { ExtensionServerConfig(0) }
        assertFailsWith<IllegalArgumentException> { ExtensionServerConfig(65536) }
    }

    @Test
    fun runningStatusExposesLoopbackUrl() {
        val status = ExtensionServerStatus(ExtensionServerPhase.Running, 43123)
        assertEquals(true, status.isRunning)
        assertEquals("http://127.0.0.1:43123", status.baseUrl)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/commonTest/kotlin/eu/friedcutlet/yokan/ext/ExtensionServerReleaseTest.kt
### Write `vendor/yokan-ext/src/commonTest/kotlin/eu/friedcutlet/yokan/ext/ExtensionServerReleaseTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/vendor/yokan-ext/src/commonTest/kotlin/eu/friedcutlet/yokan/ext/ExtensionServerReleaseTest.kt).

The implementation below defines `ExtensionServerReleaseTest`, `parsesVersionDigestAndAssetMetadata`, `resolvesDigestFromBuildTrustedAllowlist`, `rejectsReleaseMissingFromBuildTrustedAllowlist`, `selectsExactHostAsset`, `selectsArchitectureIndependentJarBundleForIos`, `rejectsUnavailableHostAsset`, `rejectsUnsupportedArchitecture`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `parsesVersionDigestAndAssetMetadata`
- `resolvesDigestFromBuildTrustedAllowlist`
- `rejectsReleaseMissingFromBuildTrustedAllowlist`
- `selectsExactHostAsset`
- `selectsArchitectureIndependentJarBundleForIos`
- `rejectsUnavailableHostAsset`
- `rejectsUnsupportedArchitecture`

```kotlin
package eu.friedcutlet.yokan.ext

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith

class ExtensionServerReleaseTest {
    private val release = parseExtensionServerRelease(
        """{
          "tag_name":"v1.2.3",
          "assets":[
            {"name":"macOS-arm64-bundle.zip","browser_download_url":"https://example.test/mac.zip","size":12,"digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
            {"name":"windows-x64-bundle.zip","browser_download_url":"https://example.test/win.zip","size":20,"digest":"sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}
          ]
        }""",
    )

    @Test
    fun parsesVersionDigestAndAssetMetadata() {
        assertEquals("1.2.3", release.version)
        assertEquals(12, release.assets.first().size)
        assertEquals("a".repeat(64), release.assets.first().sha256)
    }

    @Test
    fun resolvesDigestFromBuildTrustedAllowlist() {
        val asset = ExtensionServerReleaseAsset(
            name = "macOS-arm64-bundle.zip",
            downloadUrl = "https://example.test/attacker-controlled.zip",
            size = 1,
            sha256 = "0".repeat(64),
        )

        assertEquals(
            "2fc07c86d1d9598bb8e15835bfd1b39db5948c2048c83e05f2d1171f267eeb5f",
            ExtensionServerRelease("1.0.5", listOf(asset)).trustedSha256(asset),
        )
    }

    @Test
    fun rejectsReleaseMissingFromBuildTrustedAllowlist() {
        val asset = release.assets.first()
        val error = assertFailsWith<ExtensionServerException> { release.trustedSha256(asset) }

        assertEquals("UNTRUSTED_RELEASE", error.code)
    }

    @Test
    fun selectsExactHostAsset() {
        val selected = release.selectBundle(ExtensionServerHost(ExtensionServerHostOs.MacOs, ExtensionServerHostArch.Arm64))
        assertEquals("macOS-arm64-bundle.zip", selected.name)
    }
    @Test
    fun selectsArchitectureIndependentJarBundleForIos() {
        val selected = release.selectBundle(ExtensionServerHost(ExtensionServerHostOs.Ios, ExtensionServerHostArch.Arm64))
        assertEquals("macOS-arm64-bundle.zip", selected.name)
    }


    @Test
    fun rejectsUnavailableHostAsset() {
        assertFailsWith<ExtensionServerException> {
            release.selectBundle(ExtensionServerHost(ExtensionServerHostOs.Linux, ExtensionServerHostArch.X64))
        }
    }

    @Test
    fun rejectsUnsupportedArchitecture() {
        assertFailsWith<ExtensionServerException> {
            release.selectBundle(ExtensionServerHost(ExtensionServerHostOs.Windows, ExtensionServerHostArch.Arm64))
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/desktopTest/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServerInstallerTest.kt
### Write `vendor/yokan-ext/src/desktopTest/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServerInstallerTest.kt`

Create this path in your reconstruction project. Source set: **desktopTest**. [Exact file download](../reference/source/vendor/yokan-ext/src/desktopTest/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServerInstallerTest.kt).

The implementation below defines `DesktopExtensionServerInstallerTest`, `verifiesExtractsAndResolvesBundle`, `rejectsDigestMismatchWithoutInstallingVersion`, `createBundleArchive`, `serveFile`, `sha256`, `deleteRecursively`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `verifiesExtractsAndResolvesBundle`
- `rejectsDigestMismatchWithoutInstallingVersion`

```kotlin
package eu.friedcutlet.yokan.ext

import com.sun.net.httpserver.HttpServer
import java.net.InetSocketAddress
import java.nio.file.Files
import java.security.MessageDigest
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import kotlinx.coroutines.test.runTest
import kotlin.io.path.exists
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue

class DesktopExtensionServerInstallerTest {
    @Test
    fun verifiesExtractsAndResolvesBundle() = runTest {
        val root = Files.createTempDirectory("yokan-ext-installer-")
        val archive = createBundleArchive(root)
        val server = serveFile(archive)
        try {
            val asset = ExtensionServerReleaseAsset(
                name = "test-bundle.zip",
                downloadUrl = "http://127.0.0.1:${server.address.port}/bundle.zip",
                size = Files.size(archive),
                sha256 = sha256(archive),
            )
            val release = ExtensionServerRelease("9.9.9", listOf(asset))
            val progress = mutableListOf<Long>()
            val bundle = DesktopExtensionServerInstaller(root.resolve("installed"))
                .install(release, asset) { downloaded, _ -> progress += downloaded }

            assertEquals("9.9.9", bundle.version)
            assertTrue(Files.isRegularFile(java.nio.file.Path.of(bundle.serverJarPath)))
            assertTrue(Files.isRegularFile(java.nio.file.Path.of(bundle.jvmPath)))
            assertTrue(progress.last() == asset.size)
        } finally {
            server.stop(0)
            deleteRecursively(root)
        }
    }

    @Test
    fun rejectsDigestMismatchWithoutInstallingVersion() = runTest {
        val root = Files.createTempDirectory("yokan-ext-digest-")
        val archive = createBundleArchive(root)
        val server = serveFile(archive)
        try {
            val asset = ExtensionServerReleaseAsset(
                "test-bundle.zip",
                "http://127.0.0.1:${server.address.port}/bundle.zip",
                Files.size(archive),
                "0".repeat(64),
            )
            val installer = DesktopExtensionServerInstaller(root.resolve("installed"))
            val error = assertFailsWith<ExtensionServerException> {
                installer.install(ExtensionServerRelease("1.0.0", listOf(asset)), asset)
            }
            assertEquals("DIGEST_MISMATCH", error.code)
            assertTrue(!root.resolve("installed/1.0.0").exists())
        } finally {
            server.stop(0)
            deleteRecursively(root)
        }
    }

    private fun createBundleArchive(root: java.nio.file.Path): java.nio.file.Path {
        val archive = root.resolve("bundle.zip")
        ZipOutputStream(Files.newOutputStream(archive)).use { zip ->
            mapOf(
                "bundle/jre/bin/${if (System.getProperty("os.name").contains("win", true)) "java.exe" else "java"}" to "fake java",
                "bundle/MExtensionServer.jar" to "fake jar",
            ).forEach { (name, content) ->
                zip.putNextEntry(ZipEntry(name))
                zip.write(content.encodeToByteArray())
                zip.closeEntry()
            }
        }
        return archive
    }

    private fun serveFile(path: java.nio.file.Path): HttpServer {
        val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)
        server.createContext("/bundle.zip") { exchange ->
            val bytes = Files.readAllBytes(path)
            exchange.sendResponseHeaders(200, bytes.size.toLong())
            exchange.responseBody.use { it.write(bytes) }
        }
        server.start()
        return server
    }

    private fun sha256(path: java.nio.file.Path): String {
        val digest = MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(path))
        return digest.joinToString("") { "%02x".format(it) }
    }

    private fun deleteRecursively(path: java.nio.file.Path) {
        if (!Files.exists(path)) return
        Files.walk(path).use { paths -> paths.sorted(Comparator.reverseOrder()).forEach(Files::deleteIfExists) }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/desktopTest/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServerTest.kt
### Write `vendor/yokan-ext/src/desktopTest/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServerTest.kt`

Create this path in your reconstruction project. Source set: **desktopTest**. [Exact file download](../reference/source/vendor/yokan-ext/src/desktopTest/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServerTest.kt).

The implementation below defines `DesktopExtensionServerTest`, `missingJarFailsBeforeLaunching`, `ownsAndStopsLaunchedProcess`, `dataDirConfinesHomeTempAndOnlyWhenSet`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `missingJarFailsBeforeLaunching`
- `ownsAndStopsLaunchedProcess`
- `dataDirConfinesHomeTempAndOnlyWhenSet`

```kotlin
package eu.friedcutlet.yokan.ext

import java.nio.file.Files
import kotlin.io.path.writeText
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue

class DesktopExtensionServerTest {
    @Test
    fun missingJarFailsBeforeLaunching() = runTest {
        val server = DesktopExtensionServer()
        val error = assertFailsWith<ExtensionServerException> {
            server.start(ExtensionServerConfig(43122, serverJarPath = "/missing/server.jar"))
        }
        assertEquals("MISSING_JAR", error.code)
        assertEquals(ExtensionServerPhase.Failed, server.status.value.phase)
    }

    @Test
    fun ownsAndStopsLaunchedProcess() = runTest {
        if (System.getProperty("os.name").contains("win", ignoreCase = true)) return@runTest
        val directory = Files.createTempDirectory("yokan-ext-runner-")
        try {
            val java = directory.resolve("fake-java")
            java.writeText("#!/bin/sh\nsleep 30\n")
            assertTrue(java.toFile().setExecutable(true))
            val jar = Files.createFile(directory.resolve("MExtensionServer.jar"))
            val server = DesktopExtensionServer()

            val running = server.start(ExtensionServerConfig(43123, java.toString(), jar.toString()))
            assertEquals(ExtensionServerPhase.Running, running.phase)
            assertEquals(43123, running.port)

            val stopped = server.stop()
            assertEquals(ExtensionServerPhase.Stopped, stopped.phase)
        } finally {
            Files.walk(directory).use { paths ->
                paths.sorted(Comparator.reverseOrder()).forEach(Files::deleteIfExists)
            }
        }
    }

    @Test
    fun dataDirConfinesHomeTempAndOnlyWhenSet() {
        val jar = java.io.File("/opt/MExtensionServer.jar")
        val dataDir = java.io.File("/data/profiles/p_1/extension-server-data")

        assertEquals(
            listOf("java", "-jar", jar.absolutePath, "8080"),
            desktopExtensionServerCommand("java", jar, 8080, null),
        )
        assertEquals(
            listOf(
                "java",
                "-Duser.home=${dataDir.absolutePath}",
                "-Djava.io.tmpdir=${java.io.File(dataDir, "tmp").absolutePath}",
                "-jar",
                jar.absolutePath,
                "8080",
            ),
            desktopExtensionServerCommand("java", jar, 8080, dataDir),
        )
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #vendor/yokan-ext/src/iosTest/kotlin/eu/friedcutlet/yokan/ext/IosExtensionServerInstallerTest.kt
### Write `vendor/yokan-ext/src/iosTest/kotlin/eu/friedcutlet/yokan/ext/IosExtensionServerInstallerTest.kt`

Create this path in your reconstruction project. Source set: **iosTest**. [Exact file download](../reference/source/vendor/yokan-ext/src/iosTest/kotlin/eu/friedcutlet/yokan/ext/IosExtensionServerInstallerTest.kt).

The implementation below defines `IosExtensionServerInstallerTest`, `importsJarAtomicallyAndUsesBundledJvm`, `rejectsNonJarImports`, `rejectsUntrustedReleaseBeforeDownload`, `verifiesChecksumAndSelectsExtensionServerJar`, `rejectsMissingTrustedDigest`, `removesArchiveAndStagingAfterChecksumMismatch`, `releaseAsset`, `testInstaller`, `writeBytes` and 4 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

- `importsJarAtomicallyAndUsesBundledJvm`
- `rejectsNonJarImports`
- `rejectsUntrustedReleaseBeforeDownload`
- `verifiesChecksumAndSelectsExtensionServerJar`
- `rejectsMissingTrustedDigest`
- `removesArchiveAndStagingAfterChecksumMismatch`

```kotlin
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)

package eu.friedcutlet.yokan.ext

import kotlinx.coroutines.test.runTest
import okio.FileSystem
import okio.ByteString.Companion.decodeBase64
import okio.Path
import okio.Path.Companion.toPath
import okio.buffer
import platform.Foundation.NSTemporaryDirectory
import platform.Foundation.NSUUID
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue

class IosExtensionServerInstallerTest {
    private val fileSystem = FileSystem.SYSTEM

    @Test
    fun importsJarAtomicallyAndUsesBundledJvm() = withTemporaryRoot { root ->
        val source = root / "MExtensionServer-v1.2.3.jar"
        writeText(source, "server")
        val installer = IosExtensionServerInstaller(
            installRoot = (root / "installed").toString(),
            bundledJvmPath = "/app/java-21-openjdk",
        )

        val installed = installer.importJar(source.toString())

        assertEquals("1.2.3", installed.version)
        assertEquals("/app/java-21-openjdk", installed.jvmPath)
        assertTrue(fileSystem.exists(installed.serverJarPath.toPath()))
        assertEquals("server", readText(installed.serverJarPath.toPath()))
    }

    @Test
    fun rejectsNonJarImports() = withTemporaryRoot { root ->
        val source = root / "MExtensionServer.txt"
        writeText(source, "not a jar")
        val installer = IosExtensionServerInstaller(
            installRoot = (root / "installed").toString(),
            bundledJvmPath = "/app/java-21-openjdk",
        )

        val error = assertFailsWith<ExtensionServerException> {
            installer.importJar(source.toString())
        }

        assertEquals("MISSING_JAR", error.code)
    }

    @Test
    fun rejectsUntrustedReleaseBeforeDownload() = runTest {
        withTemporaryRootSuspend { root ->
            val installRoot = root / "installed"
            val asset = releaseAsset()
            var downloadCalled = false
            val installer = IosExtensionServerInstaller.createForTesting(
                installRoot = installRoot.toString(),
                bundledJvmPath = "/app/java-21-openjdk",
                fileSystem = fileSystem,
                archiveDownloader = { _, _, _ -> downloadCalled = true },
                trustedDigest = { release, selected -> release.trustedSha256(selected) },
            )

            val error = assertFailsWith<ExtensionServerException> {
                installer.install(ExtensionServerRelease("9.9.9", listOf(asset)), asset)
            }

            assertEquals("UNTRUSTED_RELEASE", error.code)
            assertTrue(!downloadCalled)
            assertTrue(!fileSystem.exists(installRoot))
        }
    }

    @Test
    fun verifiesChecksumAndSelectsExtensionServerJar() = runTest {
        withTemporaryRootSuspend { root ->
            val installRoot = root / "installed"
            val asset = releaseAsset()
            val progress = mutableListOf<Long>()
            val installer = testInstaller(installRoot, FixtureSha256) { _, target, onProgress ->
                writeBytes(target, FixtureArchive)
                onProgress(FixtureArchive.size.toLong(), FixtureArchive.size.toLong())
            }

            val installed = installer.install(ExtensionServerRelease("1.0.4", listOf(asset)), asset) {
                    downloaded,
                    _,
                ->
                progress += downloaded
            }

            assertEquals("MExtensionServer.jar", installed.serverJarPath.toPath().name)
            assertEquals("server", readText(installed.serverJarPath.toPath()))
            assertEquals(FixtureArchive.size.toLong(), progress.last())
        }
    }

    @Test
    fun rejectsMissingTrustedDigest() = withTemporaryRoot { root ->
        val archive = root / "bundle.zip"
        writeBytes(archive, FixtureArchive)

        val error = assertFailsWith<ExtensionServerException> {
            verifyIosExtensionServerArchiveSha256(fileSystem, archive, null)
        }

        assertEquals("MISSING_DIGEST", error.code)
    }

    @Test
    fun removesArchiveAndStagingAfterChecksumMismatch() = runTest {
        withTemporaryRootSuspend { root ->
            val installRoot = root / "installed"
            val asset = releaseAsset()
            val installer = testInstaller(installRoot, "0".repeat(64)) { _, target, _ ->
                writeBytes(target, FixtureArchive)
            }

            val error = assertFailsWith<ExtensionServerException> {
                installer.install(ExtensionServerRelease("1.0.4", listOf(asset)), asset)
            }

            assertEquals("CHECKSUM_MISMATCH", error.code)
            assertTrue(!fileSystem.exists(installRoot / ".download-1.0.4.zip"))
            assertTrue(!fileSystem.exists(installRoot / ".install-1.0.4"))
            assertTrue(!fileSystem.exists(installRoot / "1.0.4"))
        }
    }

    private fun releaseAsset() = ExtensionServerReleaseAsset(
        name = "macOS-arm64-bundle.zip",
        downloadUrl = "https://example.test/bundle.zip",
        size = FixtureArchive.size.toLong(),
        sha256 = null,
    )

    private fun testInstaller(
        installRoot: Path,
        digest: String,
        downloader: suspend (ExtensionServerReleaseAsset, Path, (Long, Long) -> Unit) -> Unit,
    ) = IosExtensionServerInstaller.createForTesting(
        installRoot = installRoot.toString(),
        bundledJvmPath = "/app/java-21-openjdk",
        fileSystem = fileSystem,
        archiveDownloader = downloader,
        trustedDigest = { _, _ -> digest },
    )

    private fun writeBytes(path: Path, value: ByteArray) {
        val sink = fileSystem.sink(path).buffer()
        try {
            sink.write(value)
        } finally {
            sink.close()
        }
    }

    private fun writeText(path: Path, value: String) {
        val sink = fileSystem.sink(path).buffer()
        try {
            sink.writeUtf8(value)
        } finally {
            sink.close()
        }
    }

    private fun readText(path: Path): String {
        val source = fileSystem.source(path).buffer()
        return try {
            source.readUtf8()
        } finally {
            source.close()
        }
    }

    private fun withTemporaryRoot(block: (Path) -> Unit) {
        val root = "${NSTemporaryDirectory().trimEnd('/')}/yokan-ext-${NSUUID.UUID().UUIDString}".toPath()
        fileSystem.createDirectories(root)
        try {
            block(root)
        } finally {
            fileSystem.deleteRecursively(root, mustExist = false)
        }
    }

    private suspend fun withTemporaryRootSuspend(block: suspend (Path) -> Unit) {
        val root = "${NSTemporaryDirectory().trimEnd('/')}/yokan-ext-${NSUUID.UUID().UUIDString}".toPath()
        fileSystem.createDirectories(root)
        try {
            block(root)
        } finally {
            fileSystem.deleteRecursively(root, mustExist = false)
        }
    }

    private companion object {
        const val FixtureSha256 = "ad0b8a48643602e5baf16bdc621000450254ea2280606a5b590a94ba245145b6"
        val FixtureArchive = checkNotNull(
            "UEsDBBQAAAAAAAAAIQAo6kUnBQAAAAUAAAAQAAAAYnVuZGxlL290aGVyLmphcmRlY295UEsDBBQAAAAAAAAAIQD21W1aBgAAAAYAAAAbAAAAYnVuZGxlL01FeHRlbnNpb25TZXJ2ZXIuamFyc2VydmVyUEsBAhQDFAAAAAAAAAAhACjqRScFAAAABQAAABAAAAAAAAAAAAAAAIABAAAAAGJ1bmRsZS9vdGhlci5qYXJQSwECFAMUAAAAAAAAACEA9tVtWgYAAAAGAAAAGwAAAAAAAAAAAAAAgAEzAAAAYnVuZGxlL01FeHRlbnNpb25TZXJ2ZXIuamFyUEsFBgAAAAACAAIAhwAAAHIAAAAAAA=="
                .decodeBase64(),
        ).toByteArray()
    }
}
```
[chapter-file-end]: #

### Completion record

- [ ] Every implementation/configuration and required asset shown above is present at its displayed path.
- [ ] Cross-chapter imports resolve against the intended contracts and platform source sets.
- [ ] The tests for this chapter pass in the rebuilt app; record the command, platform and result.
- [ ] Native, device, browser and live-service checks have evidence or an explicit “not run” entry.
[chapter-content-end]: #


Gate: shared contract/release tests, desktop installer/process tests, Android bridge tests for cast/relations/seasons, and iOS installer tests pass independently before main-app integration. Validate real loading on each supported host separately. Preserve `LICENSE-APACHE-MIHON` and notices when retaining compatibility code.
