Prerequisite: work through this chapter after each milestone, then repeat the final acceptance matrix. File workbook · all extracted test behaviors.
How to write this chapter
Recreate the verification harness, package builders and release automation as code. Validation here means executable assertions plus clean-host/device evidence; source coverage alone is not behavioral parity.
The 35 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: Write controlled test/runtime/browser harnesses and fixtures.
- Step 2: Recreate CI/build commands and compile every target.
- Step 3: Run the end-to-end acceptance matrix and retain evidence.
- Step 4: Preserve shared version/channel and update/release ordering policy.
- Step 5: Write packaging, signing and resumable release automation.
- Verification: recreate the full test/fixture listings and run the relevant target tasks. [chapter-content-end]: #
Step 1: establish test layers
Recreate commonTest fakes for database, HTTP, files, notifications, clocks, runtimes and ViewModel dispatchers. Tests should assert observable data/behavior, not just repeat implementation expressions. Port the tests associated with each file as you write it. Use coroutine test scheduling and controlled deferred responses for races; do not hide timing bugs with sleeps.
Use nonWebTest for QuickJS/mpv-specific contracts, jvmCommonTest for JVM file/proxy/host behavior, desktopTest for Room, native/Compose/JavaFX/integration tests, androidHostTest for host-compatible Android contracts, iosTest for native file/compression/UI boundaries, wasmJsTest for browser storage/network/media and skikoTest for image processing. Vendor modules have their own tests. A JVM pass is not a browser or device pass.
Separate deterministic fixture tests from opt-in live/Docker/native tests. For each unavailable integration record “not run” and its prerequisite. The original README records existing browser Karma import.meta and iOS IosLocalMediaInputTest problems; treat these as baseline caveats to investigate, not permission to silently mark tests green. Verify their status in your rebuilt environment.
Follow the code
Common tests exercise policy with fakes and controlled coroutine scheduling; platform suites exercise Room/native/browser behavior. Harness files configure the environment and expose startup/storage failures instead of hiding them. Fixtures retain exact values/bytes where their format is part of a test. Keep opt-in live/native tests separate so a missing prerequisite cannot silently look like a pass.
Write these files in this order:
composeApp/karma.config.d/browser-storage.jscomposeApp/karma.config.d/startup-errors.jscomposeApp/karma/startup-errors.js
Write composeApp/karma.config.d/browser-storage.js
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
// Load the same OPFS implementation used by the application before Kotlin/Wasm contract tests.
{
const fs = require('fs');
const path = require('path');
let directory = process.cwd();
let script;
while (true) {
script = [path.join(directory, 'src/wasmJsMain/resources/browser-storage.js'),
path.join(directory, 'composeApp/src/wasmJsMain/resources/browser-storage.js')].find(p => fs.existsSync(p));
if (script || path.dirname(directory) === directory) break;
directory = path.dirname(directory);
}
if (!script) throw new Error('Cannot locate browser-storage.js for Kotlin/Wasm tests');
config.files.unshift({ pattern: script, included: true, served: true, watched: false });
config.files.push({ pattern: path.join(path.dirname(script), 'browser-archives.js'), included: false, served: true, watched: false });
config.files.push({ pattern: path.join(path.dirname(script), 'browser-files-sw.js'), included: false, served: true, watched: false });
config.files.push({ pattern: path.join(path.dirname(script), 'vendor/zipjs-2.23.0/zip-native.min.js'), included: false, served: true, watched: false });
// The production media worker and its dependencies live alongside the app page.
// Karma otherwise serves these scripts under /absolute/... outside the runner page's scope.
config.proxies = { ...(config.proxies || {}),
'/browser-files-sw.js': '/absolute' + path.join(path.dirname(script), 'browser-files-sw.js'),
'/browser-archives.js': '/absolute' + path.join(path.dirname(script), 'browser-archives.js'),
'/vendor/zipjs-2.23.0/zip-native.min.js': '/absolute' + path.join(path.dirname(script), 'vendor/zipjs-2.23.0/zip-native.min.js'),
};
config.failOnEmptyTestSuite = true;
// Contract checks stream >64 MiB through Kotlin/Wasm; Mocha's 2 s default flakes on cold/slow hosts.
config.client = config.client || {};
config.client.mocha = { ...(config.client.mocha || {}), timeout: 30000 };
}
Write composeApp/karma.config.d/startup-errors.js
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
config.files.unshift({
pattern: require('path').resolve(config.basePath, '../../../../composeApp/karma/startup-errors.js'),
watched: false
});
Write composeApp/karma/startup-errors.js
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
window.addEventListener('unhandledrejection', function (event) {
window.__karma__.error('Test module failed to load: ' + String(event.reason));
});
Check your understanding
For each test source set, name one failure it can catch that common tests cannot. Record explicit not-run prerequisites for native/live cases. [chapter-content-end]: #
Step 2: run the build checks from the actual project
From the reconstruction root after recreating the build:
./gradlew :composeApp:desktopTest --no-daemon
./gradlew :composeApp:compileAndroidMain :composeApp:compileKotlinWasmJs :composeApp:compileTestKotlinWasmJs :composeApp:testAndroidHostTest --no-daemon
./gradlew :androidApp:assembleDebug
./gradlew :composeApp:wasmJsBrowserDistribution
./gradlew :composeApp:linkDebugFrameworkIosSimulatorArm64
The first two commands match the checked-in Forgejo CI intent. iOS compilation requires macOS/Xcode. Discover target-specific test tasks using Gradle task listings after writing your build, especially if your intentional module names differ. Run submodule tests from their own build roots; inspect their task lists rather than copying stale README task names after an AGP change.
Run python3 .github/scripts/test_release_scripts.py for release script behavior and the browser storage script according to its source arguments/environment. Run skill validation only for development-skills changes; it does not validate the application. Keep schema snapshots committed and compare generated version 16/schema migrations as part of database acceptance.
Follow the code
The command sequence above compiles production and test sources in addition to executing JVM tests. A host test pass can still miss a broken Android manifest, Wasm interop declaration or iOS linker symbol. Preserve the checked-in CI's intended task/target coverage while discovering the actual tasks of any intentionally renamed module. Keep failed/cancelled and unavailable checks distinct in recorded evidence.
Write these files in this order:
.forgejo/workflows/ci.yml
Write .forgejo/workflows/ci.yml
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
name: CI
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: https://code.forgejo.org/actions/checkout@v7
with:
token: ${{ secrets.SUBMODULE_READ_TOKEN }}
persist-credentials: false
submodules: recursive
- name: Setup Java toolchain
uses: https://github.com/actions/setup-java@v6
with:
distribution: temurin
java-version: 21
- name: Setup Android SDK
uses: https://github.com/android-actions/setup-android@v4
with:
packages: platform-tools platforms;android-37.0 build-tools;37.0.0
- name: Run shared and desktop tests
run: ./gradlew :composeApp:desktopTest --no-daemon
- name: Compile Android and Wasm, run Android host tests
run: |
set -euo pipefail
sdk="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}}"
if [[ -z "$sdk" ]]; then
echo "Android SDK unavailable: set ANDROID_HOME or ANDROID_SDK_ROOT" >&2
exit 1
fi
export ANDROID_HOME="$sdk"
export ANDROID_SDK_ROOT="$sdk"
./gradlew \
:composeApp:compileAndroidMain \
:composeApp:compileKotlinWasmJs \
:composeApp:compileTestKotlinWasmJs \
:composeApp:testAndroidHostTest \
--no-daemon
Check your understanding
Build from a clean dependency/cache setup where practical, then compare generated Room schema and native/host outputs to the pinned contracts. [chapter-content-end]: #
Step 3: final behavior matrix
| Scenario | Required observation |
|---|---|
| Fresh install | Empty catalogs/library; onboarding and defaults; no secret/preconfigured account |
| Browse → library | Install controlled source; list/search/detail/favorite; restart preserves identity |
| Refresh concurrent edit | New chapters appear; notes/progress/categories/manual filler survive |
| Manga | Headers, mode/direction, next chapter, zoom/scroll, offline pages and final progress |
| Novel | HTML/EPUB, links/images, typography/pagination, TTS teardown and restored progress |
| Anime | Remote/local stream, resume, subtitles, quality, seek previews, fallback, PiP/Cast where supported |
| Download interruption | Pause/restart/resume preserves request/destination and verifies bytes |
| Local rescan | Nested seasons/archives/sidecars; external originals retained; no late overwrite |
| Profile switch/delete | Reader/workers drain; stale callbacks cannot touch another profile; exports retained |
| Restore | Preview before apply; encrypted/foreign/native formats; selective merge; rollback/conflict |
| Sync | Concurrent devices, account switch, retry/conflict, offline journal and provider lossiness |
| Together | Join/admission, role policy, position update, reconnect and account/profile retirement |
| Accessibility | Compact/wide/TV, large text, screen reader labels, reduced motion and e-ink |
| OS lifecycle | Cold deep link/backup open, notification action, background work, system permissions |
| Native cleanup | Repeated player/WebView/TTS/extension create-close; no continuing callbacks/resources |
| Upgrade | Earlier SQL/settings data migrates with stable IDs and Default storage adoption |
Record Android device/API, desktop OS/architecture, iOS device/simulator and browser/version for every manual pass. External services need live checks in addition to fake protocol tests. Do not claim an unsupported feature works because the UI rendered its button.
Follow the code
The matrix combines features at their integration seams: source admission to library, readers to progress/automation, profiles to native cleanup, and sync/restore to concurrent edits. Each scenario needs an observable result, platform/version and command or manual procedure. UI rendering is insufficient proof for network/native permissions. Repeated lifecycle tests reveal leaks that a single successful play/open cycle misses.
This step connects or verifies implementations already listed in this chapter or its prerequisites. Follow the named call paths above while reading the complete tests at the end.
Check your understanding
Pick one row from the matrix and specify initial state, exact actions, expected persisted result and cleanup observation. Run it on every supported host where the capability exists. [chapter-content-end]: #
Step 4: reproduce version/channel policy
version.xcconfig is the local version/build-number source shared by Gradle/Xcode. -Pyokan.version overrides YOKAN_VERSION, with optional build-number override. Tags are vMAJOR.MINOR.PATCH; 0.0.x is alpha, 0.x.x beta, major ≥1 stable. Derived build number is major×1,000,000 + minor×1,000 + patch, minimum one, within source bounds.
The updater examines eligible published GitHub releases, skips drafts and applies installed-channel policy. Beta accepts beta/stable; alpha all channels; stable only stable. Reproduce version ordering and asset selection fixtures. macOS package internal major is shifted +1 to satisfy packager requirements while visible app version remains unchanged.
Follow the code
Version parsing produces visible version, channel and bounded build number shared by Gradle/Xcode/scripts. The updater filters eligible published releases before selecting an asset; it does not compare arbitrary strings or accept drafts. Release scripts validate the selected remote tag/commit before building. Read the version-policy fixtures with the implementation so edge cases and channel transitions stay reproducible.
Write these files in this order:
scripts/yokan-version.sh
Write scripts/yokan-version.sh
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
This script participates in the same version/channel policy as Gradle and Xcode. Preserve accepted tag syntax, numeric bounds and overrides rather than independently deriving a build number.
#!/bin/sh
# Source with REPO_ROOT set. Exports the same release metadata as Gradle/Xcode.
YOKAN_VERSION="${YOKAN_VERSION:-$(awk '$1 == "YOKAN_VERSION" && $2 == "=" {print $3; exit}' "$REPO_ROOT/version.xcconfig")}"
YOKAN_VERSION="${YOKAN_VERSION#v}"
if ! printf '%s\n' "$YOKAN_VERSION" | awk -F. '
NF != 3 { exit 1 }
{ for (i = 1; i <= 3; i++) if ($i !~ /^(0|[1-9][0-9]*)$/) exit 1 }
$1 > 2099 || $2 > 999 || $3 > 999 { exit 1 }
'; then
echo "error: Yokan version must be MAJOR.MINOR.PATCH within platform version-code limits" >&2
exit 2
fi
YOKAN_RELEASE_CHANNEL="$(printf '%s\n' "$YOKAN_VERSION" | awk -F. '{print ($1 > 0 ? "stable" : ($2 > 0 ? "beta" : "alpha"))}')"
YOKAN_VERSION_CODE="${YOKAN_VERSION_CODE:-$(printf '%s\n' "$YOKAN_VERSION" | awk -F. '{code = $1 * 1000000 + $2 * 1000 + $3; printf "%.0f", (code > 0 ? code : 1)}')}"
if ! printf '%s\n' "$YOKAN_VERSION_CODE" | awk '$0 !~ /^[1-9][0-9]*$/ || $0 > 2100000000 {exit 1}'; then
echo "error: Yokan versionCode must be between 1 and 2100000000" >&2
exit 2
fi
export YOKAN_VERSION YOKAN_RELEASE_CHANNEL YOKAN_VERSION_CODE
Check your understanding
Test alpha/beta/stable eligibility and malformed/out-of-range versions. Verify displayed app version stays consistent despite platform packaging adjustments. [chapter-content-end]: #
Step 5: reproduce packaging and automation
Create Android debug/release configuration, native ABI filters and signing script with verification. Keep signing material outside source. Rebuild Linux AppImage/DEB, macOS DMG and Windows MSI tasks, native resources and icon generation. Test installed packages, not only Gradle run. Include the external libraries/frameworks required by each backend.
Recreate unsigned iOS IPA/framework packaging and the shared Xcode scheme/build phases. Codemagic's TestFlight workflow uses separately configured signing/account secrets and selected tester group; copying YAML does not configure those external services. Native Zero/extension-server and media frameworks must be included in the correct output.
Recreate Forgejo CI and GitHub manual release scripts/actions. Manual release validates a Forgejo tag, resolves its commit, builds selected platforms, skips existing assets unless replacement is requested, uploads directly to GitHub Releases and publishes only after selected builds succeed. Preserve draft/resume semantics, concurrency cancellation, least-required workflow permissions, checksum/signing verification and credential handling. Do not publish test artifacts while learning the pipeline.
Follow the code
Package builders include the actual native resources, manifests/icons and architecture slices required by the app. Signing and publishing depend on externally configured secrets/accounts; source code preserves how those inputs are validated without embedding them. Release orchestration creates/reuses a draft, handles existing assets explicitly, and publishes only after selected builds succeed. Fixture tests exercise those decisions without publishing learning artifacts.
Write these files in this order:
.github/actions/release-setup/action.yml.github/scripts/prepare-release.sh.github/scripts/upload-release-assets.sh.github/scripts/with-forgejo-auth.sh.github/workflows/release.ymlcodemagic.yamlpackaging/icons/README.mdpackaging/icons/Yokan.icnspackaging/icons/yokan-source.pngpackaging/icons/yokan.icopackaging/icons/yokan.pngscripts/build-ios-unsigned-ipa.shscripts/build-linux-appimage.shscripts/generate-app-icons.swiftscripts/init-private-submodules.shscripts/sign-android-apk.sh
Write .github/actions/release-setup/action.yml
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
name: Release build setup
description: Check out the selected source commit and prepare the shared build toolchain.
inputs:
commit:
description: Resolved release tag commit
required: true
forgejo-username:
description: Forgejo read account
required: true
forgejo-token:
description: Forgejo source and submodule read token
required: true
runs:
using: composite
steps:
- name: Checkout selected Forgejo release source
shell: bash
env:
SOURCE_COMMIT: ${{ inputs.commit }}
FORGEJO_USERNAME: ${{ inputs.forgejo-username }}
FORGEJO_TOKEN: ${{ inputs.forgejo-token }}
run: |
git init source
git -C source remote add origin https://git.friedcutlet.com/friedcutlet/yokan.git
bash .github/scripts/with-forgejo-auth.sh git -C source fetch --depth 1 origin "$SOURCE_COMMIT"
git -C source checkout --detach FETCH_HEAD
bash .github/scripts/with-forgejo-auth.sh git -C source submodule update --init --recursive --depth 1
- name: Setup Java
uses: actions/setup-java@v6
with:
distribution: temurin
java-version: '21'
- name: Setup Android SDK
uses: android-actions/setup-android@v4
with:
packages: platform-tools platforms;android-37.0 build-tools;37.0.0
- name: Cache Gradle dependencies and reusable build outputs
uses: gradle/actions/setup-gradle@v6
with:
cache-cleanup: on-success
artifact-retention-days: 1
dependency-graph: disabled
Write .github/scripts/prepare-release.sh
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
#!/usr/bin/env bash
set -euo pipefail
# All user input arrives via environment variables, never executable shell text.
: "${RELEASE_TAG:?Choose an existing release tag}"
: "${GH_REPO:?Missing GitHub repository}"
: "${GITHUB_OUTPUT:?Missing workflow output file}"
[[ "$RELEASE_TAG" == v* ]] || { echo 'Release tags must start with v.' >&2; exit 2; }
REPO_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
export YOKAN_VERSION="$RELEASE_TAG"
. "$REPO_ROOT/scripts/yokan-version.sh"
selected=false
for platform in ANDROID LINUX MACOS WINDOWS IOS IOS_FRAMEWORK; do
[[ "${!platform:-false}" != true ]] || selected=true
done
[[ "$selected" == true ]] || { echo 'Select at least one platform.' >&2; exit 2; }
# GitHub hosts releases; the app's source tags live in Forgejo.
refs=$(bash "$REPO_ROOT/.github/scripts/with-forgejo-auth.sh" git ls-remote \
https://git.friedcutlet.com/friedcutlet/yokan.git "refs/tags/$RELEASE_TAG" "refs/tags/$RELEASE_TAG^{}")
commit=$(printf '%s\n' "$refs" | awk -v tag="refs/tags/$RELEASE_TAG" '
$2 == tag { direct = $1 }
$2 == tag "^{}" { peeled = $1 }
END { print (peeled != "" ? peeled : direct) }
')
[[ "$commit" =~ ^[0-9a-f]{40}$ ]] || { echo 'Could not resolve the selected tag commit.' >&2; exit 2; }
prerelease=true
[[ "$YOKAN_RELEASE_CHANNEL" != stable ]] || prerelease=false
# List once: a network/auth failure must not be treated as a nonexistent release.
release_id=$(gh api --paginate "repos/$GH_REPO/releases?per_page=100" --jq ".[] | select(.tag_name == \"$RELEASE_TAG\") | .id")
if [[ -z "$release_id" ]]; then
# Release-only repositories may have no matching GitHub tag yet. Pin that
# hosting tag to the automation commit; source compilation uses Forgejo's SHA.
args=(--repo "$GH_REPO" --target "${GITHUB_SHA:?Missing workflow commit}" --draft --title "Yokan $RELEASE_TAG ($YOKAN_RELEASE_CHANNEL)")
[[ "$prerelease" != true ]] || args+=(--prerelease)
gh release create "$RELEASE_TAG" "${args[@]}"
fi
assets=$(gh release view "$RELEASE_TAG" --repo "$GH_REPO" --json assets --jq '.assets[].name')
needs_asset() {
[[ "${REBUILD_EXISTING:-false}" == true ]] || ! printf '%s\n' "$assets" | grep -Fxq "$1"
}
need_android=false; need_linux=false; need_macos=false; need_windows=false; need_ios=false; need_framework=false
if [[ "${ANDROID:-false}" == true ]] && needs_asset "Yokan-$RELEASE_TAG-android.apk"; then need_android=true; fi
if [[ "${LINUX:-false}" == true ]] && { needs_asset "Yokan-$RELEASE_TAG-linux.deb" || needs_asset "Yokan-$RELEASE_TAG-linux.AppImage"; }; then need_linux=true; fi
if [[ "${MACOS:-false}" == true ]] && needs_asset "Yokan-$RELEASE_TAG-macos.dmg"; then need_macos=true; fi
if [[ "${WINDOWS:-false}" == true ]] && needs_asset "Yokan-$RELEASE_TAG-windows.msi"; then need_windows=true; fi
if [[ "${IOS:-false}" == true ]] && needs_asset "Yokan-$RELEASE_TAG-ios-unsigned.ipa"; then need_ios=true; fi
if [[ "${IOS_FRAMEWORK:-false}" == true ]] && needs_asset "Yokan-$RELEASE_TAG-ios-framework.zip"; then need_framework=true; fi
{
echo "commit=$commit"
echo "channel=$YOKAN_RELEASE_CHANNEL"
echo "prerelease=$prerelease"
echo "android=$need_android"
echo "linux=$need_linux"
echo "macos=$need_macos"
echo "windows=$need_windows"
echo "ios=$need_ios"
echo "ios_framework=$need_framework"
} >> "$GITHUB_OUTPUT"
if [[ -n "${GITHUB_STEP_SUMMARY:-}" ]]; then
printf 'Release: **%s (%s)**\n\nSource commit: `%s`\n\nBuilds needed: Android %s; Linux %s; macOS %s; Windows %s; iOS IPA %s; iOS framework %s.\n' \
"$RELEASE_TAG" "$YOKAN_RELEASE_CHANNEL" "$commit" "$need_android" "$need_linux" "$need_macos" "$need_windows" "$need_ios" "$need_framework" >> "$GITHUB_STEP_SUMMARY"
fi
Write .github/scripts/upload-release-assets.sh
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
#!/usr/bin/env bash
set -euo pipefail
: "${RELEASE_TAG:?Missing release tag}"
: "${GH_REPO:?Missing GitHub repository}"
[[ $# -gt 0 ]] || { echo 'No release assets provided.' >&2; exit 2; }
assets=$(gh release view "$RELEASE_TAG" --repo "$GH_REPO" --json assets --jq '.assets[].name')
for file in "$@"; do
[[ -s "$file" ]] || { echo "Release asset missing or empty: $file" >&2; exit 2; }
name=$(basename "$file")
args=(--repo "$GH_REPO")
if [[ "${REBUILD_EXISTING:-false}" == true ]]; then
args+=(--clobber)
elif printf '%s\n' "$assets" | grep -Fxq "$name"; then
echo "Already published: $name"
continue
fi
gh release upload "$RELEASE_TAG" "$file" "${args[@]}"
done
Write .github/scripts/with-forgejo-auth.sh
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
#!/usr/bin/env bash
set -euo pipefail
: "${FORGEJO_USERNAME:?Missing FORGEJO_USERNAME secret}"
: "${FORGEJO_TOKEN:?Missing FORGEJO_TOKEN secret}"
umask 077
auth_dir=$(mktemp -d)
trap 'rm -rf "$auth_dir"' EXIT
cat > "$auth_dir/askpass" <<'ASKPASS'
#!/bin/sh
case "$1" in
*Username*) printf '%s\n' "$FORGEJO_USERNAME" ;;
*) printf '%s\n' "$FORGEJO_TOKEN" ;;
esac
ASKPASS
chmod 700 "$auth_dir/askpass"
GIT_ASKPASS="$auth_dir/askpass" GIT_TERMINAL_PROMPT=0 "$@"
Write .github/workflows/release.yml
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
name: Manual Release
run-name: Release ${{ inputs.release_tag }}
on:
workflow_dispatch:
inputs:
release_tag:
description: Existing Forgejo release tag to build (e.g. v0.1.0)
required: true
type: string
android:
description: Android signed APK
type: boolean
default: true
linux:
description: Linux DEB and AppImage
type: boolean
default: true
macos:
description: macOS DMG (higher runner cost)
type: boolean
default: true
windows:
description: Windows MSI
type: boolean
default: true
ios:
description: iOS unsigned IPA with Zero runtime (higher runner cost)
type: boolean
default: true
ios_framework:
description: iOS framework ZIP (reuses IPA compilation when both are selected)
type: boolean
default: true
rebuild_existing:
description: Rebuild and replace selected assets that already exist
type: boolean
default: false
# Keep only the latest manual release request running, across all tags.
concurrency:
group: yokan-manual-release
cancel-in-progress: true
permissions:
contents: read
env:
RELEASE_TAG: ${{ inputs.release_tag }}
YOKAN_VERSION: ${{ inputs.release_tag }}
GH_REPO: ${{ github.repository }}
GH_TOKEN: ${{ github.token }}
REBUILD_EXISTING: ${{ inputs.rebuild_existing }}
jobs:
prepare:
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: write
outputs:
commit: ${{ steps.release.outputs.commit }}
channel: ${{ steps.release.outputs.channel }}
prerelease: ${{ steps.release.outputs.prerelease }}
android: ${{ steps.release.outputs.android }}
linux: ${{ steps.release.outputs.linux }}
macos: ${{ steps.release.outputs.macos }}
windows: ${{ steps.release.outputs.windows }}
ios: ${{ steps.release.outputs.ios }}
ios_framework: ${{ steps.release.outputs.ios_framework }}
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Test release scripts
run: python3 .github/scripts/test_release_scripts.py
- name: Validate tag and select missing assets
id: release
env:
FORGEJO_USERNAME: ${{ secrets.FORGEJO_USERNAME }}
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
ANDROID: ${{ inputs.android }}
LINUX: ${{ inputs.linux }}
MACOS: ${{ inputs.macos }}
WINDOWS: ${{ inputs.windows }}
IOS: ${{ inputs.ios }}
IOS_FRAMEWORK: ${{ inputs.ios_framework }}
run: bash .github/scripts/prepare-release.sh
- name: Validate Android signing credentials before starting any builds
if: steps.release.outputs.android == 'true'
shell: bash
env:
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
run: |
for name in ANDROID_KEYSTORE_BASE64 ANDROID_KEYSTORE_PASSWORD ANDROID_KEY_ALIAS ANDROID_KEY_PASSWORD; do
test -n "${!name}" || { echo "Missing signing secret: $name" >&2; exit 1; }
done
android:
needs: prepare
if: needs.prepare.outputs.android == 'true'
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: write
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: ./.github/actions/release-setup
with:
commit: ${{ needs.prepare.outputs.commit }}
forgejo-username: ${{ secrets.FORGEJO_USERNAME }}
forgejo-token: ${{ secrets.FORGEJO_TOKEN }}
- name: Build release APK
working-directory: source
run: ./gradlew :androidApp:assembleRelease -Pyokan.version="$YOKAN_VERSION" --no-daemon
- name: Sign and upload directly to release
shell: bash
working-directory: source
env:
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
run: |
mkdir -p release
bash scripts/sign-android-apk.sh androidApp/build/outputs/apk/release/androidApp-release-unsigned.apk "release/Yokan-$RELEASE_TAG-android.apk"
bash ../.github/scripts/upload-release-assets.sh release/*.apk
linux:
needs: prepare
if: needs.prepare.outputs.linux == 'true'
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: write
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: ./.github/actions/release-setup
with:
commit: ${{ needs.prepare.outputs.commit }}
forgejo-username: ${{ secrets.FORGEJO_USERNAME }}
forgejo-token: ${{ secrets.FORGEJO_TOKEN }}
- name: Install packaging dependencies
run: sudo apt-get update && sudo apt-get install -y fakeroot dpkg-dev
- name: Build and upload Linux packages
shell: bash
working-directory: source
run: |
./gradlew :composeApp:packageReleaseDeb :composeApp:createReleaseDistributable -Pyokan.version="$YOKAN_VERSION" --no-daemon
mkdir -p release
cp composeApp/build/compose/binaries/main-release/deb/*.deb "release/Yokan-$RELEASE_TAG-linux.deb"
bash scripts/build-linux-appimage.sh "release/Yokan-$RELEASE_TAG-linux.AppImage"
bash ../.github/scripts/upload-release-assets.sh release/*
macos:
needs: prepare
if: needs.prepare.outputs.macos == 'true'
runs-on: macos-latest
timeout-minutes: 30
permissions:
contents: write
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: ./.github/actions/release-setup
with:
commit: ${{ needs.prepare.outputs.commit }}
forgejo-username: ${{ secrets.FORGEJO_USERNAME }}
forgejo-token: ${{ secrets.FORGEJO_TOKEN }}
- name: Build and upload macOS DMG
working-directory: source
run: |
./gradlew :composeApp:packageReleaseDmg -Pyokan.version="$YOKAN_VERSION" --no-daemon
mkdir -p release
cp composeApp/build/compose/binaries/main-release/dmg/*.dmg "release/Yokan-$RELEASE_TAG-macos.dmg"
bash ../.github/scripts/upload-release-assets.sh release/*
windows:
needs: prepare
if: needs.prepare.outputs.windows == 'true'
runs-on: windows-latest
timeout-minutes: 30
permissions:
contents: write
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: ./.github/actions/release-setup
with:
commit: ${{ needs.prepare.outputs.commit }}
forgejo-username: ${{ secrets.FORGEJO_USERNAME }}
forgejo-token: ${{ secrets.FORGEJO_TOKEN }}
- name: Build and upload Windows MSI
shell: bash
working-directory: source
run: |
./gradlew :composeApp:packageReleaseMsi -Pyokan.version="$YOKAN_VERSION" --no-daemon
mkdir -p release
cp composeApp/build/compose/binaries/main-release/msi/*.msi "release/Yokan-$RELEASE_TAG-windows.msi"
bash ../.github/scripts/upload-release-assets.sh release/*
ios:
needs: prepare
if: needs.prepare.outputs.ios == 'true' || needs.prepare.outputs.ios_framework == 'true'
# The arm64 hosted runner has insufficient memory for this release framework.
runs-on: macos-26-intel
timeout-minutes: 45
permissions:
contents: write
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: ./.github/actions/release-setup
with:
commit: ${{ needs.prepare.outputs.commit }}
forgejo-username: ${{ secrets.FORGEJO_USERNAME }}
forgejo-token: ${{ secrets.FORGEJO_TOKEN }}
- name: Build IPA including Zero interpreter and extension server
if: needs.prepare.outputs.ios == 'true'
working-directory: source
env:
YOKAN_SIDELOAD_RUNTIME: 'YES'
run: |
scripts/build-ios-unsigned-ipa.sh
mkdir -p release
cp build/ios-ipa/dist/*.ipa "release/Yokan-$RELEASE_TAG-ios-unsigned.ipa"
- name: Compile standalone framework when no IPA build is needed
if: needs.prepare.outputs.ios != 'true' && needs.prepare.outputs.ios_framework == 'true'
working-directory: source
run: ./gradlew :composeApp:linkReleaseFrameworkIosArm64 -Pyokan.version="$YOKAN_VERSION" --no-daemon
- name: Package framework from the same compilation
if: needs.prepare.outputs.ios_framework == 'true'
working-directory: source
run: |
mkdir -p release
ditto -c -k --sequesterRsrc --keepParent composeApp/build/bin/iosArm64/releaseFramework/YokanShared.framework "release/Yokan-$RELEASE_TAG-ios-framework.zip"
- name: Upload iOS assets directly to release
working-directory: source
run: bash ../.github/scripts/upload-release-assets.sh release/*
publish:
needs: [prepare, android, linux, macos, windows, ios]
if: >-
${{ !cancelled() && needs.prepare.result == 'success' &&
!contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') }}
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: write
steps:
- name: Publish selected release after all selected builds succeed
env:
CHANNEL: ${{ needs.prepare.outputs.channel }}
PRERELEASE: ${{ needs.prepare.outputs.prerelease }}
run: |
gh release edit "$RELEASE_TAG" --repo "$GH_REPO" --draft=false --prerelease="$PRERELEASE" --title "Yokan $RELEASE_TAG ($CHANNEL)"
gh release view "$RELEASE_TAG" --repo "$GH_REPO" --json url --jq .url >> "$GITHUB_STEP_SUMMARY"
Write codemagic.yaml
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
The source describes its contract as:
/.dSYM - /tmp/xcodebuild_logs/.log publishing: app_store_connect: auth: integration submit_to_testflight: true # Create this group in App Store Connect > Yokan > TestFlight first. beta_groups: - Yokan Testers submit_to_app_store: false ios-sideload: name: iOS sideload IPA (unsigned) instance_type: mac_mini_m2 max_build_duration: 60 triggering: events: - push - pull_request branch_patterns: - pattern: main include: true source: true - pattern: develop include: true source: true environment: groups: - private_git_credentials java: 21 vars: CM_RECURSIVE_SUBMODULE_INIT: "false" cache: cache_paths: - $HOME/.gradle/caches - $HOME/.gradle/wrapper - $HOME/.konan scripts: - name: Initialize private submodules script: | bash "$CM_BUILD_DIR/scripts/init-private-submodules.sh" - name: Build unsigned sideload IPA script: | set -o pipefail mkdir -p build/ios-ipa/logs scripts/build-ios-unsigned-ipa.sh 2>&1 | tee build/ios-ipa/logs/xcodebuild.log artifacts: - build/ios-ipa/dist/.ipa - build/ios-ipa/
# Private submodules require the Codemagic variable group
# `private_git_credentials` with FORGEJO_USERNAME and a secret FORGEJO_TOKEN.
# Configure the HTTPS repository connection separately in Codemagic's UI.
workflows:
ios-testflight:
name: iOS TestFlight
instance_type: mac_mini_m2
max_build_duration: 120
integrations:
# Team settings > Integrations > App Store Connect: use this exact key name.
app_store_connect: yokan-testflight
triggering:
events:
- push
branch_patterns:
- pattern: main
include: true
source: true
environment:
groups:
- private_git_credentials
# Set APP_STORE_APPLE_ID to Yokan's numeric App Store Connect Apple ID.
- ios_testflight
ios_signing:
distribution_type: app_store
bundle_identifier: eu.friedcutlet.yokan
xcode: latest
java: 21
vars:
CM_RECURSIVE_SUBMODULE_INIT: "false"
cache:
cache_paths:
- $HOME/.gradle/caches
- $HOME/.gradle/wrapper
- $HOME/.konan
scripts:
- name: Initialize private submodules
script: |
set -eu
bash "$CM_BUILD_DIR/scripts/init-private-submodules.sh"
- name: Set release version and TestFlight build number
script: |
set -eu
: "${APP_STORE_APPLE_ID:?Set APP_STORE_APPLE_ID in the ios_testflight variable group}"
REPO_ROOT="$CM_BUILD_DIR"
. "$REPO_ROOT/scripts/yokan-version.sh"
LATEST_BUILD_NUMBER=$(app-store-connect get-latest-testflight-build-number "$APP_STORE_APPLE_ID" --platform IOS --all-versions)
LATEST_BUILD_NUMBER=${LATEST_BUILD_NUMBER:-0}
case "$LATEST_BUILD_NUMBER" in
*[!0-9]*) echo "Expected an integer TestFlight build number, got: $LATEST_BUILD_NUMBER" >&2; exit 1 ;;
esac
NEXT_BUILD_NUMBER=$((LATEST_BUILD_NUMBER + 1))
if [ "$NEXT_BUILD_NUMBER" -gt "$YOKAN_VERSION_CODE" ]; then
YOKAN_VERSION_CODE=$NEXT_BUILD_NUMBER
fi
# Share the same override with Xcode and the Gradle build phase.
echo "YOKAN_VERSION=$YOKAN_VERSION" >> "$CM_ENV"
echo "YOKAN_VERSION_CODE=$YOKAN_VERSION_CODE" >> "$CM_ENV"
- name: Apply App Store provisioning profiles
script: |
set -eu
xcode-project use-profiles --project "$CM_BUILD_DIR/iosApp/iosApp.xcodeproj"
- name: Build signed TestFlight IPA
script: |
set -eu
xcode-project build-ipa \
--project "$CM_BUILD_DIR/iosApp/iosApp.xcodeproj" \
--scheme iosApp \
--config Release \
--archive-xcargs "COMPILER_INDEX_STORE_ENABLE=NO YOKAN_VERSION=$YOKAN_VERSION MARKETING_VERSION=$YOKAN_VERSION CURRENT_PROJECT_VERSION=$YOKAN_VERSION_CODE YOKAN_SIDELOAD_RUNTIME=NO YOKAN_SIDELOAD_RUNTIME_ENABLED=0"
artifacts:
- build/ios/ipa/*.ipa
- build/ios/xcarchive/**/*.dSYM
- /tmp/xcodebuild_logs/*.log
publishing:
app_store_connect:
auth: integration
submit_to_testflight: true
# Create this group in App Store Connect > Yokan > TestFlight first.
beta_groups:
- Yokan Testers
submit_to_app_store: false
ios-sideload:
name: iOS sideload IPA (unsigned)
instance_type: mac_mini_m2
max_build_duration: 60
triggering:
events:
- push
- pull_request
branch_patterns:
- pattern: main
include: true
source: true
- pattern: develop
include: true
source: true
environment:
groups:
- private_git_credentials
java: 21
vars:
CM_RECURSIVE_SUBMODULE_INIT: "false"
cache:
cache_paths:
- $HOME/.gradle/caches
- $HOME/.gradle/wrapper
- $HOME/.konan
scripts:
- name: Initialize private submodules
script: |
bash "$CM_BUILD_DIR/scripts/init-private-submodules.sh"
- name: Build unsigned sideload IPA
script: |
set -o pipefail
mkdir -p build/ios-ipa/logs
scripts/build-ios-unsigned-ipa.sh 2>&1 | tee build/ios-ipa/logs/xcodebuild.log
artifacts:
- build/ios-ipa/dist/*.ipa
- build/ios-ipa/**/*.log
- build/ios-ipa/DerivedData/Logs/**
macos-dmg:
name: macOS DMG
instance_type: mac_mini_m2
max_build_duration: 60
triggering:
events:
- push
- pull_request
branch_patterns:
- pattern: main
include: true
source: true
- pattern: develop
include: true
source: true
environment:
groups:
- private_git_credentials
vars:
CM_RECURSIVE_SUBMODULE_INIT: "false"
cache:
cache_paths:
- $HOME/.gradle/caches
- $HOME/.gradle/wrapper
scripts:
- name: Initialize private submodules
script: |
bash "$CM_BUILD_DIR/scripts/init-private-submodules.sh"
- name: Build macOS DMG
script: |
set -o pipefail
mkdir -p build/macos-dmg/logs
./gradlew :composeApp:packageReleaseDistributionForCurrentOS --no-daemon 2>&1 | tee build/macos-dmg/logs/gradle.log
artifacts:
- composeApp/build/compose/binaries/main-release/dmg/*.dmg
- build/macos-dmg/**/*.log
Write packaging/icons/README.md
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
# Default yōkan icon
`yokan-source.png` is the master artwork for the default app icon: a pastel
overhead illustration of cocoa/plum-brown and pistachio/sage-green yōkan filling
most of the square, inspired by the user's yōkan-and-pistachio photo and
the confection described in [Yōkan](https://en.wikipedia.org/wiki/Y%C5%8Dkan).
It was created with the built-in image generation tool, without copying a
Wikipedia photograph.
The default iOS, Android, desktop, web, and shared UI assets are resized exports
of this source. The optional Torii designs are separate assets. On macOS,
regenerate the icons from the repository root with:
```sh
swift -module-cache-path /private/tmp/yokan-icon-cache scripts/generate-app-icons.swift
```
Edit prompt (built-in image generation tool, using the previous icon and the user's food photo as references):
> Use case: style-transfer. Redesign Image 1 (the current Yokan app icon) as a PASTEL ILLUSTRATION, using Image 2 (the user's food photo) only for the yōkan sweet, muted plum-brown colors, and pistachio details. Do NOT copy either image's photographic rendering. The result must look like a simple hand-painted gouache or soft flat editorial illustration, NOT a photograph or 3D render. Preserve the directly overhead top-down composition and large jelly footprint: two broad rounded rectangular yōkan pieces nestled side by side, together filling almost all of the square with a narrow warm cream margin. One piece is muted dusty cocoa/plum-brown, the other soft pastel pistachio/sage-green. Add just a few simple pale pistachio shapes inspired by Image 2. Use clean, softly irregular contours, large matte flat color areas, delicate paper-like brush texture, and at most two subtle tones per jelly piece. Keep shading minimal and soft. No realistic wet shine, reflections, translucent simulation, tiny photographic pores, hard shadows, dark gradients, beveled glass edges, saturated colors, or isometric side faces. Keep the sweet appetizing and the silhouette readable at small app-icon sizes. No plate, utensils, table scene, lettering, logo glyphs, border, watermark, or extra props. One finished square opaque app icon.
Write packaging/icons/Yokan.icns
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
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: #
Write packaging/icons/yokan-source.png
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
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: #
Write packaging/icons/yokan.ico
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
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: #
Write packaging/icons/yokan.png
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
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: #
Write scripts/build-ios-unsigned-ipa.sh
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
#!/bin/sh
# Build an unsigned iOS .ipa for sideloading (AltStore/SideStore re-sign on install).
# Used by the GitHub and Forgejo release workflows and by Codemagic.
#
# Usage:
# scripts/build-ios-unsigned-ipa.sh
#
# Environment:
# YOKAN_SIDELOAD_RUNTIME YES (default) embeds the signed Java 21 runtime and
# M-Extension-Server via iosApp/PrepareExtensionRuntime.sh;
# NO builds without the embedded extension runtime.
# CONFIGURATION Xcode configuration, default Release.
# YOKAN_VERSION Release version/tag; defaults to version.xcconfig.
# YOKAN_VERSION_CODE Optional positive platform build number override.
set -eu
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$SCRIPT_DIR/.."
. "$SCRIPT_DIR/yokan-version.sh"
CONFIGURATION="${CONFIGURATION:-Release}"
SIDELOAD="${YOKAN_SIDELOAD_RUNTIME:-YES}"
case "$SIDELOAD" in
YES) SIDELOAD_ENABLED=1 ;;
NO) SIDELOAD_ENABLED=0 ;;
*) echo "error: YOKAN_SIDELOAD_RUNTIME must be YES or NO" >&2; exit 2 ;;
esac
DERIVED_DATA="$REPO_ROOT/build/ios-ipa/DerivedData"
OUTPUT_DIR="$REPO_ROOT/build/ios-ipa/dist"
PRODUCTS_DIR="$DERIVED_DATA/Build/Products/$CONFIGURATION-iphoneos"
echo "==> Building unsigned $CONFIGURATION iosApp (sideload runtime: $SIDELOAD)"
xcodebuild \
-project "$REPO_ROOT/iosApp/iosApp.xcodeproj" \
-scheme iosApp \
-configuration "$CONFIGURATION" \
-destination 'generic/platform=iOS' \
-derivedDataPath "$DERIVED_DATA" \
YOKAN_SIDELOAD_RUNTIME="$SIDELOAD" \
YOKAN_SIDELOAD_RUNTIME_ENABLED="$SIDELOAD_ENABLED" \
YOKAN_VERSION="$YOKAN_VERSION" \
MARKETING_VERSION="$YOKAN_VERSION" \
CURRENT_PROJECT_VERSION="$YOKAN_VERSION_CODE" \
CODE_SIGNING_ALLOWED=NO \
CODE_SIGNING_REQUIRED=NO \
CODE_SIGN_IDENTITY="" \
build
APP_PATH="$(/bin/ls -d "$PRODUCTS_DIR"/*.app 2>/dev/null | head -n 1 || true)"
if [ -z "$APP_PATH" ]; then
echo "error: no .app produced under $PRODUCTS_DIR" >&2
exit 1
fi
if [ "$SIDELOAD" = "YES" ]; then
for required in \
"$APP_PATH/Frameworks/OpenJDKRuntime.framework/OpenJDKRuntime" \
"$APP_PATH/MExtensionServer.jar"
do
if [ ! -e "$required" ]; then
echo "error: sideload runtime asset missing from app bundle: $required" >&2
exit 1
fi
done
fi
VERSION="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$APP_PATH/Info.plist" 2>/dev/null || echo dev)"
TAG="v$VERSION"
IPA_PATH="$OUTPUT_DIR/Yokan-$TAG-ios-unsigned.ipa"
echo "==> Packaging $IPA_PATH"
STAGE_DIR="$REPO_ROOT/build/ios-ipa/stage"
rm -rf "$STAGE_DIR" "$IPA_PATH"
mkdir -p "$STAGE_DIR/Payload" "$OUTPUT_DIR"
/usr/bin/ditto "$APP_PATH" "$STAGE_DIR/Payload/$(basename "$APP_PATH")"
(cd "$STAGE_DIR" && /usr/bin/ditto -c -k --norsrc --keepParent Payload "$IPA_PATH")
rm -rf "$STAGE_DIR"
/bin/ls -lh "$IPA_PATH"
echo "==> Done. Install with AltStore/SideStore (they re-sign the unsigned bundle)."
Write scripts/build-linux-appimage.sh
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
#!/usr/bin/env bash
# Wraps the jpackage app image (":composeApp:createReleaseDistributable") into a
# standalone AppImage. The app image already carries its own jlink runtime, so the
# AppDir only needs the AppImage entry points: AppRun, a .desktop file and an icon.
set -euo pipefail
if [[ $# != 1 ]]; then
echo "Usage: bash scripts/build-linux-appimage.sh out.AppImage" >&2
exit 2
fi
out=$1
repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
app_image="$repo_root/composeApp/build/compose/binaries/main-release/app/Yokan"
icon="$repo_root/composeApp/src/androidMain/res/mipmap-anydpi/ic_launcher.png"
[[ -x "$app_image/bin/Yokan" ]] || {
echo "Run ./gradlew :composeApp:createReleaseDistributable first; missing $app_image/bin/Yokan" >&2
exit 1
}
[[ -f "$icon" ]] || { echo "Icon does not exist: $icon" >&2; exit 1; }
arch=$(uname -m)
case "$arch" in
x86_64 | aarch64) ;;
*) echo "Unsupported AppImage architecture: $arch" >&2; exit 1 ;;
esac
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
appdir="$work/Yokan.AppDir"
mkdir -p "$appdir/usr"
cp -a "$app_image/." "$appdir/usr/"
cp "$icon" "$appdir/yokan.png"
# appimagetool requires exactly one .desktop entry in the AppDir root, and its Icon
# key must name an image file sitting next to it (extension omitted).
cat > "$appdir/yokan.desktop" <<'DESKTOP'
[Desktop Entry]
Type=Application
Name=Yokan
Comment=Manga, anime and novel library
Exec=Yokan
Icon=yokan
Terminal=false
Categories=AudioVideo;Graphics;
DESKTOP
cat > "$appdir/AppRun" <<'APPRUN'
#!/bin/sh
here=$(dirname "$(readlink -f "$0")")
exec "$here/usr/bin/Yokan" "$@"
APPRUN
chmod +x "$appdir/AppRun"
appimagetool=${APPIMAGETOOL:-}
if [[ -z "$appimagetool" ]]; then
appimagetool="$work/appimagetool"
url="https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-$arch.AppImage"
curl -fsSL "$url" -o "$appimagetool"
chmod +x "$appimagetool"
fi
mkdir -p "$(dirname "$out")"
# --appimage-extract-and-run: GitHub runners have no FUSE, so the tool cannot mount itself.
ARCH="$arch" "$appimagetool" --appimage-extract-and-run "$appdir" "$out"
Write scripts/generate-app-icons.swift
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
// Resize the yōkan default icon and draw the optional Torii artwork on macOS:
// swift -module-cache-path /private/tmp/yokan-icon-cache scripts/generate-app-icons.swift
// The original default artwork is kept in packaging/icons/yokan-source.png.
import AppKit
import Foundation
let root = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
func writePNG(_ path: String, size: Int, draw: (CGContext) -> Void) throws {
let context = CGContext(data: nil, width: size, height: size, bitsPerComponent: 8,
bytesPerRow: size * 4, space: CGColorSpace(name: CGColorSpace.sRGB)!,
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!
draw(context)
let bitmap = NSBitmapImageRep(cgImage: context.makeImage()!)
let target = root.appendingPathComponent(path)
try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
try bitmap.representation(using: .png, properties: [:])!.write(to: target)
}
func color(_ hex: UInt32) -> CGColor {
CGColor(colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!,
components: [CGFloat((hex >> 16) & 255) / 255, CGFloat((hex >> 8) & 255) / 255,
CGFloat(hex & 255) / 255, 1])!
}
let primary = NSImage(contentsOf: root.appendingPathComponent("packaging/icons/yokan-source.png"))!
let original = primary.cgImage(forProposedRect: nil, context: nil, hints: nil)!
func originalPNG(_ path: String, _ size: Int) throws {
try writePNG(path, size: size) { context in
context.setFillColor(color(0xFFFFFF)); context.fill(CGRect(x: 0, y: 0, width: size, height: size))
context.interpolationQuality = .high
context.draw(original, in: CGRect(x: 0, y: 0, width: size, height: size))
}
}
func toriiPNG(_ path: String, background: UInt32, foreground: UInt32) throws {
try writePNG(path, size: 1024) { context in
context.scaleBy(x: 10.24, y: 10.24)
context.translateBy(x: 0, y: 100); context.scaleBy(x: 1, y: -1)
context.setFillColor(color(background)); context.fill(CGRect(x: 0, y: 0, width: 100, height: 100))
context.setFillColor(color(foreground))
let beam = CGMutablePath()
beam.move(to: CGPoint(x: 22, y: 26)); beam.addQuadCurve(to: CGPoint(x: 78, y: 26), control: CGPoint(x: 50, y: 34))
beam.addLine(to: CGPoint(x: 78, y: 34)); beam.addQuadCurve(to: CGPoint(x: 22, y: 34), control: CGPoint(x: 50, y: 42)); beam.closeSubpath()
context.addPath(beam); context.fillPath()
for rect in [CGRect(x: 32, y: 37, width: 8, height: 41), CGRect(x: 60, y: 37, width: 8, height: 41),
CGRect(x: 26, y: 44, width: 48, height: 6), CGRect(x: 47, y: 52, width: 6, height: 12)] {
context.fill(rect)
}
}
}
let catalog = "iosApp/Assets.xcassets"
try originalPNG("composeApp/src/commonMain/composeResources/drawable/icon_red.png", 1024)
try originalPNG("composeApp/src/commonMain/composeResources/drawable/mangayomi_icon.png", 1024)
try originalPNG("composeApp/src/androidMain/res/mipmap-anydpi/ic_launcher.png", 192)
try originalPNG("\(catalog)/AppIcon.appiconset/icon.png", 1024)
try toriiPNG("\(catalog)/ToriiLight.appiconset/icon.png", background: 0xFFF6EB, foreground: 0xB81932)
try toriiPNG("\(catalog)/ToriiDark.appiconset/icon.png", background: 0x211B24, foreground: 0xFFBBC4)
try toriiPNG("\(catalog)/ToriiSystem.appiconset/icon.png", background: 0xFFF6EB, foreground: 0xB81932)
try toriiPNG("\(catalog)/ToriiSystem.appiconset/dark.png", background: 0x211B24, foreground: 0xFFBBC4)
try toriiPNG("\(catalog)/ToriiSystem.appiconset/tinted.png", background: 0x202020, foreground: 0xCCCCCC)
try originalPNG("composeApp/src/wasmJsMain/resources/favicon.png", 192)
try originalPNG("packaging/icons/yokan.png", 256)
// ICO container with one PNG image. Windows/jpackage accept the standard compressed image format.
let png = try Data(contentsOf: root.appendingPathComponent("packaging/icons/yokan.png"))
var ico = Data([0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 24, 0])
func appendLE(_ value: UInt32) { ico.append(contentsOf: (0..<4).map { UInt8((value >> ($0 * 8)) & 255) }) }
appendLE(UInt32(png.count)); appendLE(22); ico.append(png)
try ico.write(to: root.appendingPathComponent("packaging/icons/yokan.ico"))
// Temporary macOS iconset source for the ICNS container below.
for size in [16, 32, 128, 256, 512] {
try originalPNG("packaging/icons/Yokan.iconset/icon_\(size)x\(size).png", size)
try originalPNG("packaging/icons/Yokan.iconset/icon_\(size)x\(size)@2x.png", size * 2)
}
// An ICNS container can embed standard PNG chunks directly; no iconutil service is needed.
var icnsBody = Data()
for (type, file) in [("icp4", "icon_16x16.png"), ("icp5", "icon_32x32.png"), ("icp6", "icon_32x32@2x.png"),
("ic07", "icon_128x128.png"), ("ic08", "icon_256x256.png"),
("ic09", "icon_512x512.png"), ("ic10", "icon_512x512@2x.png")] {
let data = try Data(contentsOf: root.appendingPathComponent("packaging/icons/Yokan.iconset/\(file)"))
icnsBody.append(contentsOf: type.utf8)
let length = UInt32(data.count + 8)
icnsBody.append(contentsOf: (0..<4).reversed().map { UInt8((length >> ($0 * 8)) & 255) })
icnsBody.append(data)
}
var icns = Data("icns".utf8)
let icnsLength = UInt32(icnsBody.count + 8)
icns.append(contentsOf: (0..<4).reversed().map { UInt8((icnsLength >> ($0 * 8)) & 255) })
icns.append(icnsBody)
try icns.write(to: root.appendingPathComponent("packaging/icons/Yokan.icns"))
try FileManager.default.removeItem(at: root.appendingPathComponent("packaging/icons/Yokan.iconset"))
Write scripts/init-private-submodules.sh
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
#!/usr/bin/env bash
# Codemagic supplies these variables from the private_git_credentials group.
set +x
set -eu
: "${FORGEJO_USERNAME:?Set FORGEJO_USERNAME in private_git_credentials}"
: "${FORGEJO_TOKEN:?Set FORGEJO_TOKEN in private_git_credentials}"
# Keep credentials out of clone URLs and files. The helper applies only to this
# HTTPS host and is inherited by Git's recursive submodule clone processes.
GIT_TERMINAL_PROMPT=0 git \
-c credential.helper= \
-c 'credential.https://git.friedcutlet.com.helper=!f() {
if [ "$1" = get ]; then
printf "username=%s\npassword=%s\n" "$FORGEJO_USERNAME" "$FORGEJO_TOKEN"
fi
}; f' \
submodule update --init --recursive
Write scripts/sign-android-apk.sh
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
#!/usr/bin/env bash
# CI release signing: passwords stay in the environment, never command arguments.
set -euo pipefail
if [[ $# != 2 ]]; then
echo "Usage: bash scripts/sign-android-apk.sh unsigned.apk signed.apk" >&2
exit 2
fi
: "${ANDROID_KEYSTORE_BASE64:?Release keystore secret is required}"
: "${ANDROID_KEYSTORE_PASSWORD:?Keystore password secret is required}"
: "${ANDROID_KEY_ALIAS:?Signing alias secret is required}"
: "${ANDROID_KEY_PASSWORD:?Key password secret is required}"
[[ -f "$1" ]] || { echo "Input APK does not exist" >&2; exit 1; }
[[ "$1" != "$2" ]] || { echo "Input and output must differ" >&2; exit 1; }
android_sdk="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}}"
[[ -n "$android_sdk" ]] || { echo "Android SDK is required via ANDROID_HOME or ANDROID_SDK_ROOT" >&2; exit 1; }
[[ -d "$android_sdk" ]] || { echo "Android SDK does not exist: $android_sdk" >&2; exit 1; }
apksigner=""
for candidate in "$android_sdk"/build-tools/*/apksigner; do
[[ -x "$candidate" ]] && apksigner="$candidate"
done
[[ -n "$apksigner" ]] || { echo "Android build-tools apksigner not found under $android_sdk" >&2; exit 1; }
signing_dir=$(mktemp -d)
trap 'rm -f "$signing_dir/release.jks"; rmdir "$signing_dir"' EXIT
umask 077
printf '%s' "$ANDROID_KEYSTORE_BASE64" | base64 --decode > "$signing_dir/release.jks"
"$apksigner" sign --ks "$signing_dir/release.jks" \
--ks-key-alias "$ANDROID_KEY_ALIAS" \
--ks-pass env:ANDROID_KEYSTORE_PASSWORD --key-pass env:ANDROID_KEY_PASSWORD \
--out "$2" "$1"
"$apksigner" verify "$2"
Check your understanding
Simulate a failed selected build, an existing asset and a resumed draft release. Verify the script neither publishes early nor replaces assets without the requested policy. [chapter-content-end]: #
Recreate the tests and verify the chapter
Recreate all test scripts and fixture assets below. Run python3 .github/scripts/test_release_scripts.py from the rebuilt application root, plus the Gradle target tasks above and the browser-storage harness according to its arguments/environment. Record real installed-package/device/native results separately from mocked release-script success.
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.
Write .github/scripts/test_release_scripts.py
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
These tests mock external release/build interactions to verify orchestration and argument policy. They should not publish real releases or stand in for launching the resulting package.
"""Offline release safety checks; never call GitHub or start platform builds."""
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
SCRIPTS = Path(__file__).resolve().parent
PLATFORMS = ("ANDROID", "LINUX", "MACOS", "WINDOWS", "IOS", "IOS_FRAMEWORK")
ASSETS = (
"android.apk", "linux.deb", "linux.AppImage", "macos.dmg", "windows.msi",
"ios-unsigned.ipa", "ios-framework.zip",
)
FAKE_GH = r'''#!/usr/bin/env python3
import json, os, sys
args = sys.argv[1:]
with open(os.environ["GH_CALLS"], "a") as log:
log.write(json.dumps(args) + "\n")
if args[0] == "api":
endpoint = next(arg for arg in args[1:] if arg.startswith("repos/"))
if "/git/ref/" in endpoint:
sys.exit(1 if os.environ.get("MISSING_TAG") else 0)
if "/commits/" in endpoint:
print("a" * 40)
else:
if os.environ.get("LIST_FAILURE"):
sys.exit(1)
if not os.environ.get("NEW_RELEASE"):
print("123")
elif args[:2] == ["release", "view"]:
print(os.environ.get("ASSET_NAMES", ""))
elif args[:2] not in (["release", "create"], ["release", "upload"]):
sys.exit("Unexpected gh command: " + repr(args))
'''
FAKE_GIT = r'''#!/usr/bin/env python3
import os, sys
assert sys.argv[1] == "ls-remote"
if not os.environ.get("MISSING_TAG"):
tag = "refs/tags/" + os.environ["RELEASE_TAG"]
if os.environ.get("ANNOTATED_TAG"):
print("b" * 40 + "\t" + tag)
print("a" * 40 + "\t" + tag + "^{}")
else:
print("a" * 40 + "\t" + tag)
'''
class ReleaseScriptsTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
fake = self.root / "gh"
fake.write_text(FAKE_GH)
fake.chmod(0o755)
fake_git = self.root / "git"
fake_git.write_text(FAKE_GIT)
fake_git.chmod(0o755)
self.env = {
**os.environ,
"PATH": f"{self.root}:{os.environ['PATH']}",
"RELEASE_TAG": "v0.1.0", "GH_REPO": "Schnitzel5/yokan",
"GITHUB_SHA": "c" * 40,
"FORGEJO_USERNAME": "test", "FORGEJO_TOKEN": "offline-test",
"GH_CALLS": str(self.root / "calls.jsonl"),
"GITHUB_OUTPUT": str(self.root / "outputs"),
"GITHUB_STEP_SUMMARY": str(self.root / "summary"),
"REBUILD_EXISTING": "false",
**dict.fromkeys(PLATFORMS, "true"),
}
def run_script(self, name, *args, **env):
return subprocess.run(
["bash", str(SCRIPTS / name), *map(str, args)],
env={**self.env, **env}, capture_output=True, text=True,
)
def outputs(self):
return dict(line.split("=", 1) for line in (self.root / "outputs").read_text().splitlines())
def calls(self):
log = self.root / "calls.jsonl"
return [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else []
def test_completed_release_skips_every_build(self):
names = "\n".join(f"Yokan-v0.1.0-{suffix}" for suffix in ASSETS)
result = self.run_script("prepare-release.sh", ASSET_NAMES=names)
self.assertEqual(0, result.returncode, result.stderr)
outputs = self.outputs()
self.assertEqual("a" * 40, outputs["commit"])
self.assertTrue(all(outputs[p.lower()] == "false" for p in PLATFORMS))
def test_only_selected_missing_platform_builds(self):
result = self.run_script("prepare-release.sh", **dict.fromkeys(PLATFORMS[1:], "false"))
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual("true", self.outputs()["android"])
self.assertTrue(all(self.outputs()[p.lower()] == "false" for p in PLATFORMS[1:]))
def test_annotated_forgejo_tag_builds_peeled_source_commit(self):
result = self.run_script("prepare-release.sh", ANNOTATED_TAG="true")
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual("a" * 40, self.outputs()["commit"])
def test_missing_appimage_requires_linux_but_existing_ipa_is_skipped(self):
result = self.run_script("prepare-release.sh", ASSET_NAMES="Yokan-v0.1.0-linux.deb\nYokan-v0.1.0-ios-unsigned.ipa")
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual("true", self.outputs()["linux"])
self.assertEqual("false", self.outputs()["ios"])
self.assertEqual("true", self.outputs()["ios_framework"])
def test_explicit_rebuild_overrides_existing_assets(self):
names = "\n".join(f"Yokan-v0.1.0-{suffix}" for suffix in ASSETS)
result = self.run_script("prepare-release.sh", ASSET_NAMES=names, REBUILD_EXISTING="true")
self.assertEqual(0, result.returncode, result.stderr)
self.assertTrue(all(self.outputs()[p.lower()] == "true" for p in PLATFORMS))
def test_new_releases_are_drafts_with_correct_channel(self):
for tag, channel, prerelease in (("v0.0.1", "alpha", "true"), ("v0.1.0", "beta", "true"), ("v1.0.0", "stable", "false")):
with self.subTest(tag=tag):
result = self.run_script("prepare-release.sh", RELEASE_TAG=tag, NEW_RELEASE="true")
self.assertEqual(0, result.returncode, result.stderr)
outputs = self.outputs()
self.assertEqual(channel, outputs["channel"])
self.assertEqual(prerelease, outputs["prerelease"])
create = [call for call in self.calls() if call[:3] == ["release", "create", tag]][-1]
self.assertIn("--draft", create)
self.assertEqual("c" * 40, create[create.index("--target") + 1])
self.assertEqual(prerelease == "true", "--prerelease" in create)
def test_bad_input_and_api_failures_never_create_release(self):
cases = ({"RELEASE_TAG": "v1.0.0;echo bad"}, {"MISSING_TAG": "true"}, {"LIST_FAILURE": "true"}, {"FORGEJO_TOKEN": ""}, dict.fromkeys(PLATFORMS, "false"))
for env in cases:
with self.subTest(env=env):
result = self.run_script("prepare-release.sh", **env)
self.assertNotEqual(0, result.returncode)
self.assertFalse(any(call[:2] == ["release", "create"] for call in self.calls()))
def test_upload_preserves_existing_asset_unless_rebuild_requested(self):
asset = self.root / "Yokan-v0.1.0-android.apk"
asset.write_bytes(b"test apk")
result = self.run_script("upload-release-assets.sh", asset, ASSET_NAMES=asset.name)
self.assertEqual(0, result.returncode, result.stderr)
self.assertFalse(any(call[:2] == ["release", "upload"] for call in self.calls()))
result = self.run_script("upload-release-assets.sh", asset, ASSET_NAMES=asset.name, REBUILD_EXISTING="true")
self.assertEqual(0, result.returncode, result.stderr)
upload = [call for call in self.calls() if call[:2] == ["release", "upload"]][-1]
self.assertIn("--clobber", upload)
def test_missing_or_empty_file_is_never_uploaded(self):
asset = self.root / "empty.apk"
asset.touch()
for file in (asset, self.root / "missing.apk"):
result = self.run_script("upload-release-assets.sh", file)
self.assertNotEqual(0, result.returncode)
self.assertFalse(any(call[:2] == ["release", "upload"] for call in self.calls()))
if __name__ == "__main__":
unittest.main()
Write composeApp/src/androidHostTest/kotlin/eu/friedcutlet/yokan/SystemIntentLinkTest.kt
Create this path in your reconstruction project. Source set: androidHostTest. Exact file download.
The implementation below defines SystemIntentLinkTest, sharedTextAndSystemSearchOpenGlobalSearch, viewIntentsKeepTheirData.
Read the setup, action and assertions in these cases before implementing their production paths:
sharedTextAndSystemSearchOpenGlobalSearchviewIntentsKeepTheirData
Cross-chapter imports used by this file: searchDeepLink. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan
import android.app.SearchManager
import android.content.Intent
import eu.friedcutlet.yokan.ui.navigation.searchDeepLink
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class SystemIntentLinkTest {
@Test
fun sharedTextAndSystemSearchOpenGlobalSearch() {
val extras = mapOf(Intent.EXTRA_TEXT to " Dandadan ", SearchManager.QUERY to "Frieren", Intent.EXTRA_PROCESS_TEXT to "Blue Lock")
assertEquals(searchDeepLink("Dandadan"), systemIntentLink(Intent.ACTION_SEND, null, extras::get))
assertEquals(searchDeepLink("Frieren"), systemIntentLink(Intent.ACTION_SEARCH, null, extras::get))
assertEquals(searchDeepLink("Frieren"), systemIntentLink(Intent.ACTION_WEB_SEARCH, null, extras::get))
assertEquals(searchDeepLink("Frieren"), systemIntentLink("com.google.android.gms.actions.SEARCH_ACTION", null, extras::get))
assertEquals(searchDeepLink("Blue Lock"), systemIntentLink(Intent.ACTION_PROCESS_TEXT, null, extras::get))
assertNull(systemIntentLink(Intent.ACTION_SEND, null) { " " })
}
@Test
fun viewIntentsKeepTheirData() {
val backup = "content://com.android.externalstorage.documents/document/primary%3Alibrary.tachibk"
assertEquals(backup, systemIntentLink(Intent.ACTION_VIEW, backup) { null })
assertEquals("yokan://updates", systemIntentLink(Intent.ACTION_VIEW, "yokan://updates") { null })
assertNull(systemIntentLink(Intent.ACTION_MAIN, null) { null })
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/architecture/GuidedViewModelFixture.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
Reviewed implementation — use this listing. Regression tests for the reviewed constructor, state/publication, main-safety and cancellation boundaries. Architecture review.
The implementation below defines GuidedViewModelFixture, prepareMain, closeOwners, own, request, Files, writeBytes, writeBytesAsync, readBytes, readBytesAsync and 7 further declarations.
Cross-chapter imports used by this file: LocalEntry, LocalFileEntry, LocalFileService, HttpRequest, HttpResponse. Keep those contracts available as you connect this step.
package eu.friedcutlet.yokan.architecture
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelStore
import eu.friedcutlet.yokan.services.files.LocalEntry
import eu.friedcutlet.yokan.services.files.LocalFileEntry
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import kotlin.coroutines.ContinuationInterceptor
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
@OptIn(ExperimentalCoroutinesApi::class)
internal abstract class GuidedViewModelFixture {
protected val main = StandardTestDispatcher()
private val owners = ViewModelStore()
private var nextOwner = 0
@BeforeTest
fun prepareMain() { Dispatchers.setMain(main) }
@AfterTest
fun closeOwners() {
try { owners.clear() } finally { Dispatchers.resetMain() }
}
protected fun <T : ViewModel> own(viewModel: T): T = viewModel.also {
owners.put("guided-${nextOwner++}", it)
}
protected val unusedHttp = object : HttpService {
override suspend fun request(request: HttpRequest): HttpResponse = error("No HTTP expected")
}
protected class Files : LocalFileService {
override val downloadRoot = "/downloads"
override val backupRoot = "/backups"
override val cacheRoot = "/cache"
val asyncReadContexts = mutableListOf<ContinuationInterceptor?>()
val writes = mutableListOf<String>()
val revealed = mutableListOf<String>()
var deletions = 0
var readAsync: suspend (String) -> ByteArray = { "log".encodeToByteArray() }
var onDelete: () -> Boolean = { true }
override fun writeBytes(path: String, bytes: ByteArray) { writes += path }
override suspend fun writeBytesAsync(path: String, bytes: ByteArray) { writes += path }
override fun readBytes(path: String) = "crash".encodeToByteArray()
override suspend fun readBytesAsync(path: String, maxBytes: Long): ByteArray {
asyncReadContexts += currentCoroutineContext()[ContinuationInterceptor]
return readAsync(path)
}
override fun canonicalPath(path: String) = path
override fun exists(path: String) = false
override fun deleteRecursively(path: String): Boolean { deletions++; return onDelete() }
override fun directorySize(path: String) = 0L
override fun openLocation(path: String): Boolean { revealed += path; return true }
override fun listLocalEntries(root: String): List<LocalEntry> = emptyList()
override fun listFiles(root: String): List<LocalFileEntry> = emptyList()
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/ConcurrencyTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ConcurrencyTest, TestScope.owner, runJoinedReturnsTheActionResult, rejectedAdmissionNeverStartsTheAction, cancellingTheCallerCancelsTheWorkAndAwaitsItsFinalizers, closingTheOwnerCancelsInFlightWork, resultProducedAfterTheOwnerClosedIsDiscarded.
Read the setup, action and assertions in these cases before implementing their production paths:
runJoinedReturnsTheActionResultrejectedAdmissionNeverStartsTheActioncancellingTheCallerCancelsTheWorkAndAwaitsItsFinalizersclosingTheOwnerCancelsInFlightWorkresultProducedAfterTheOwnerClosedIsDiscarded
package eu.friedcutlet.yokan.services
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
import kotlinx.coroutines.job
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
class ConcurrencyTest {
private fun TestScope.owner() = CoroutineScope(backgroundScope.coroutineContext + SupervisorJob(backgroundScope.coroutineContext.job))
@Test
fun runJoinedReturnsTheActionResult() = runTest {
assertEquals(42, owner().runJoined { 42 })
}
@Test
fun rejectedAdmissionNeverStartsTheAction() = runTest {
var started = false
assertFailsWith<IllegalStateException> {
owner().runJoined(admit = { error("closed") }) { started = true }
}
assertFalse(started)
}
@Test
fun cancellingTheCallerCancelsTheWorkAndAwaitsItsFinalizers() = runTest {
val owner = owner()
val entered = CompletableDeferred<Unit>()
var finalized = false
val caller = launch {
owner.runJoined {
entered.complete(Unit)
try {
awaitCancellation()
} finally {
withContext(NonCancellable) {
delay(10)
finalized = true
}
}
}
}
entered.await()
caller.cancelAndJoin()
assertTrue(finalized)
assertTrue(owner.coroutineContext.job.isActive)
}
@Test
fun closingTheOwnerCancelsInFlightWork() = runTest {
val owner = owner()
val entered = CompletableDeferred<Unit>()
var cancelled = false
val call = async {
assertFailsWith<CancellationException> {
owner.runJoined {
entered.complete(Unit)
try {
awaitCancellation()
} finally {
cancelled = true
}
}
}
}
entered.await()
owner.cancel()
call.await()
assertTrue(cancelled)
}
@Test
fun resultProducedAfterTheOwnerClosedIsDiscarded() = runTest {
val owner = owner()
assertFailsWith<CancellationException> {
owner.runJoined {
// A delegate that returns from a non-cancellable section after its owner closed.
withContext(NonCancellable) {
owner.cancel()
"stale"
}
}
}
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/LayeringRulesTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines LayeringRulesTest, assertNoReferences.
The source describes its contract as:
Enforces CODE_STYLE's package layering across every main source set.
Read the setup, action and assertions in these cases before implementing their production paths:
lowerLayersNeverReferenceUiOrAppdomainDependsOnlyOnItselfAndUtil
package eu.friedcutlet.yokan
import java.io.File
import kotlin.test.Test
import kotlin.test.assertTrue
/** Enforces CODE_STYLE's package layering across every main source set. */
class LayeringRulesTest {
private val mainSourceSets = File("src").listFiles { file -> file.isDirectory && file.name.endsWith("Main") }.orEmpty()
@Test fun lowerLayersNeverReferenceUiOrApp() {
assertNoReferences(packages = listOf("data", "database", "domain", "services"), forbidden = Regex("""\beu\.friedcutlet\.yokan\.(ui|app)\."""))
}
@Test fun domainDependsOnlyOnItselfAndUtil() {
assertNoReferences(packages = listOf("domain"), forbidden = Regex("""\beu\.friedcutlet\.yokan\.(data|database|services)\."""))
}
private fun assertNoReferences(packages: List<String>, forbidden: Regex) {
val roots = mainSourceSets.flatMap { set -> packages.map { set.resolve("kotlin/eu/friedcutlet/yokan/$it") } }
assertTrue(roots.any { it.isDirectory }, "No source roots found under ${File("src").absolutePath}")
val violations = roots.filter { it.isDirectory }
.flatMap { root -> root.walkTopDown().filter { it.extension == "kt" }.toList() }
.flatMap { file ->
file.readLines().mapIndexedNotNull { index, line ->
"${file.path}:${index + 1}: ${line.trim()}".takeIf { forbidden.containsMatchIn(line) }
}
}
assertTrue(violations.isEmpty(), "Layering violations:\n${violations.joinToString("\n")}")
}
}
Write composeApp/src/desktopTest/resources/hardcoded-ui-strings.txt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
# Hardcoded user-visible UI strings per file under commonMain/.../ui (see HardcodedUiStringsTest).
# Counts may only go down: move text to composeResources and lower the number here.
navigation/DeepLinkDialog.kt 3
navigation/NavHost.kt 2
navigation/NavigationStack.kt 1
navigation/RootNavigationBars.kt 1
screens/activity/HistoryScreen.kt 10
screens/activity/TrackerLibraryScreen.kt 13
screens/activity/UpdateErrorsScreen.kt 5
screens/activity/UpdatesScreen.kt 19
screens/browse/BrowseScreen.kt 20
screens/browse/GlobalSearchScreen.kt 6
screens/browse/SourceFilterSheet.kt 1
screens/browse/SourceHomeScreen.kt 10
screens/detail/CategoryEditorSheet.kt 1
screens/detail/ChapterFilterSheet.kt 1
screens/detail/ChapterList.kt 6
screens/detail/DetailDownloads.kt 2
screens/detail/DetailHeader.kt 2
screens/detail/DetailQuickActions.kt 1
screens/detail/DetailScreen.kt 2
screens/detail/DetailTopBar.kt 3
screens/detail/DetailViewModel.kt 3
screens/detail/TrackerSearchDialog.kt 1
screens/discovery/RecommendationsScreen.kt 4
screens/discovery/SequelsScreen.kt 5
screens/discovery/WatchOrderScreen.kt 4
screens/extensions/CodeEditorScreen.kt 4
screens/extensions/CreateExtensionScreen.kt 14
screens/extensions/ExtensionDetailScreen.kt 5
screens/extensions/ExtensionLanguagesScreen.kt 4
screens/extensions/SourcePreferencesCard.kt 1
screens/library/BulkCategoriesDialog.kt 1
screens/library/LibraryGrid.kt 4
screens/library/LibraryScreen.kt 3
screens/library/LibrarySelectionBars.kt 3
screens/library/LibrarySettingsSheet.kt 1
screens/local/LocalEntryManagement.kt 14
screens/local/LocalLibraryBrowseScreen.kt 4
screens/local/LocalLibraryOverviewScreen.kt 27
screens/local/LocalLibraryViewModel.kt 1
screens/local/LocalMetadataReview.kt 5
screens/migration/MassMigrationPreviewScreen.kt 1
screens/migration/MassMigrationSourceScreen.kt 2
screens/migration/MigrationScreen.kt 4
screens/more/MoreScreen.kt 2
screens/novel/NovelPagedReader.kt 1
screens/novel/NovelReaderChrome.kt 9
screens/novel/NovelReaderScreen.kt 2
screens/novel/NovelReaderSettingsContent.kt 17
screens/novel/NovelRichContent.kt 1
screens/onboarding/Onboarding.kt 4
screens/player/AnimePlayerScreen.kt 1
screens/player/PlayerAddons.kt 12
screens/player/PlayerChrome.kt 12
screens/player/PlayerDialogs.kt 1
screens/player/PlayerSettingsSheet.kt 11
screens/reader/ReaderBottomBar.kt 3
screens/reader/ReaderImageActions.kt 9
screens/reader/ReaderOverlays.kt 4
screens/reader/ReaderPages.kt 3
screens/reader/ReaderScreen.kt 3
screens/reader/ReaderSettingsSheet.kt 24
screens/settings/about/AboutSettingsScreen.kt 11
screens/settings/appearance/AppearanceSettingsScreen.kt 1
screens/settings/appearance/MaterialKolorBlock.kt 10
screens/settings/appearance/ThemePreview.kt 4
screens/settings/browse/BrowseSettingsScreen.kt 6
screens/settings/browse/CookiesSettingsScreen.kt 6
screens/settings/browse/RepositoriesViewModel.kt 1
screens/settings/browse/SourceRepositoriesScreen.kt 6
screens/settings/calendar/CalendarSettingsScreen.kt 2
screens/settings/calendar/MonthCalendar.kt 2
screens/settings/data/BackupDialogs.kt 8
screens/settings/data/CreateBackupScreen.kt 3
screens/settings/data/DataAndStorageScreen.kt 12
screens/settings/developer/DeveloperSettingsScreen.kt 3
screens/settings/discord/DiscordSettingsScreen.kt 13
screens/settings/downloads/DownloadsSettingsScreen.kt 12
screens/settings/downloads/LocalFolderDialogs.kt 4
screens/settings/extensionserver/ExtensionServerSettingsScreen.kt 4
screens/settings/general/GeneralSettingsScreen.kt 6
screens/settings/library/CategoriesSettingsScreen.kt 8
screens/settings/library/LibrarySettingsScreen.kt 2
screens/settings/metadata/MetadataServerSettingsScreen.kt 3
screens/settings/navigation/CustomNavigationSettingsScreen.kt 1
screens/settings/player/CustomButtonsScreen.kt 8
screens/settings/player/PlayerSettingsScreens.kt 3
screens/settings/player/TorrentSettingsViewModel.kt 1
screens/settings/security/SecuritySettingsScreen.kt 1
screens/settings/statistics/StatisticsScreen.kt 9
screens/settings/sync/SyncDialogs.kt 5
screens/settings/sync/SyncSettingsScreen.kt 11
screens/settings/tracking/TrackerBranding.kt 4
screens/settings/tracking/TrackingDetailScreen.kt 5
screens/settings/tracking/TrackingSettingsScreen.kt 7
screens/webview/InAppWebViewScreen.kt 10
screens/webview/InAppWebViewViewModel.kt 8
Write composeApp/src/desktopTest/resources/images/LIBAVIF-LICENSE
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
Copyright 2019 Joe Drago. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
Files: src/obu.c
Copyright © 2018-2019, VideoLAN and dav1d authors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
Files: third_party/iccjpeg/*
In plain English:
1. We don't promise that this software works. (But if you find any bugs,
please let us know!)
2. You can use this software for whatever you want. You don't have to pay us.
3. You may not pretend that you wrote this software. If you use it in a
program, you must acknowledge somewhere in your documentation that
you've used the IJG code.
In legalese:
The authors make NO WARRANTY or representation, either express or implied,
with respect to this software, its quality, accuracy, merchantability, or
fitness for a particular purpose. This software is provided "AS IS", and you,
its user, assume the entire risk as to its quality and accuracy.
This software is copyright (C) 1991-2013, Thomas G. Lane, Guido Vollbeding.
All Rights Reserved except as specified below.
Permission is hereby granted to use, copy, modify, and distribute this
software (or portions thereof) for any purpose, without fee, subject to these
conditions:
(1) If any part of the source code for this software is distributed, then this
README file must be included, with this copyright and no-warranty notice
unaltered; and any additions, deletions, or changes to the original files
must be clearly indicated in accompanying documentation.
(2) If only executable code is distributed, then the accompanying
documentation must state that "this software is based in part on the work of
the Independent JPEG Group".
(3) Permission for use of this software is granted only if the user accepts
full responsibility for any undesirable consequences; the authors accept
NO LIABILITY for damages of any kind.
These conditions apply to any software derived from or based on the IJG code,
not just to the unmodified library. If you use our work, you ought to
acknowledge us.
Permission is NOT granted for the use of any IJG author's name or company name
in advertising or publicity relating to this software or products derived from
it. This software may be referred to only as "the Independent JPEG Group's
software".
We specifically permit and encourage the use of this software as the basis of
commercial products, provided that all warranty or liability claims are
assumed by the product vendor.
The Unix configuration script "configure" was produced with GNU Autoconf.
It is copyright by the Free Software Foundation but is freely distributable.
The same holds for its supporting scripts (config.guess, config.sub,
ltmain.sh). Another support script, install-sh, is copyright by X Consortium
but is also freely distributable.
The IJG distribution formerly included code to read and write GIF files.
To avoid entanglement with the Unisys LZW patent, GIF reading support has
been removed altogether, and the GIF writer has been simplified to produce
"uncompressed GIFs". This technique does not use the LZW algorithm; the
resulting GIF files are larger than usual, but are readable by all standard
GIF decoders.
We are required to state that
"The Graphics Interchange Format(c) is the Copyright property of
CompuServe Incorporated. GIF(sm) is a Service Mark property of
CompuServe Incorporated."
------------------------------------------------------------------------------
Files: contrib/gdk-pixbuf/*
Copyright 2020 Emmanuel Gil Peyrot. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
Files: android_jni/gradlew*
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
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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
http://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.
------------------------------------------------------------------------------
Files: third_party/libyuv/*
Copyright 2011 The LibYuv Project Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Google nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Write composeApp/src/desktopTest/resources/images/colors-animated-8bpc-alpha-exif-xmp.avif
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
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: #
Write composeApp/src/desktopTest/resources/images/colors-animated-8bpc.avif
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
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: #
Write composeApp/src/desktopTest/resources/images/draw_points_idat.avif
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
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: #
Write composeApp/src/desktopTest/resources/images/white_1x1.avif
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
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: #
Write composeApp/src/desktopTest/resources/lnreader/LICENSE
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
MIT License
Copyright (c) 2021 Rajarshee Chatterjee
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Write composeApp/src/desktopTest/resources/lnreader/novelupdates-0.9.9.js
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
var e=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(a,o){function l(e){try{c(n.next(e))}catch(e){o(e)}}function s(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?a(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(l,s)}c((n=n.apply(e,t||[])).next())}))},t=this&&this.__generator||function(e,t){var r,n,a,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return l.next=s(0),l.throw=s(1),l.return=s(2),"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function s(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;l&&(l=0,s[0]&&(o=0)),o;)try{if(r=1,n&&(a=2&s[0]?n.return:s[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,s[1])).done)return a;switch(n=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(a=o.trys,(a=a.length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){o.label=s[1];break}if(6===s[0]&&o.label<a[1]){o.label=a[1],a=s;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(s);break}a[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(exports,"__esModule",{value:!0});var r=require("cheerio"),n=require("@libs/fetch"),a=require("@libs/filterInputs"),o=function(){function o(){this.id="novelupdates",this.name="Novel Updates",this.version="0.9.9",this.icon="src/en/novelupdates/icon.png",this.customCSS="src/en/novelupdates/customCSS.css",this.site="https://www.novelupdates.com/",this.filters={sort:{label:"Sort Results By",value:"popmonth",options:[{label:"Popular (Month)",value:"popmonth"},{label:"Popular (All)",value:"popular"},{label:"Last Updated",value:"sdate"},{label:"Rating",value:"srate"},{label:"Rank",value:"srank"},{label:"Reviews",value:"sreview"},{label:"Chapters",value:"srel"},{label:"Title",value:"abc"},{label:"Readers",value:"sread"},{label:"Frequency",value:"sfrel"}],type:a.FilterTypes.Picker},order:{label:"Order (Not for Popular)",value:"desc",options:[{label:"Descending",value:"desc"},{label:"Ascending",value:"asc"}],type:a.FilterTypes.Picker},storyStatus:{label:"Story Status (Translation)",value:"",options:[{label:"All",value:""},{label:"Completed",value:"2"},{label:"Ongoing",value:"3"},{label:"Hiatus",value:"4"}],type:a.FilterTypes.Picker},genre_operator:{label:"Genre (And/Or) (Not for Popular)",value:"and",options:[{label:"And",value:"and"},{label:"Or",value:"or"}],type:a.FilterTypes.Picker},genres:{label:"Genres",type:a.FilterTypes.ExcludableCheckboxGroup,value:{include:[],exclude:[]},options:[{label:"Action",value:"8"},{label:"Adult",value:"280"},{label:"Adventure",value:"13"},{label:"Comedy",value:"17"},{label:"Drama",value:"9"},{label:"Ecchi",value:"292"},{label:"Fantasy",value:"5"},{label:"Gender Bender",value:"168"},{label:"Harem",value:"3"},{label:"Historical",value:"330"},{label:"Horror",value:"343"},{label:"Josei",value:"324"},{label:"Martial Arts",value:"14"},{label:"Mature",value:"4"},{label:"Mecha",value:"10"},{label:"Mystery",value:"245"},{label:"Psychoical",value:"486"},{label:"Romance",value:"15"},{label:"School Life",value:"6"},{label:"Sci-fi",value:"11"},{label:"Seinen",value:"18"},{label:"Shoujo",value:"157"},{label:"Shoujo Ai",value:"851"},{label:"Shounen",value:"12"},{label:"Shounen Ai",value:"1692"},{label:"Slice of Life",value:"7"},{label:"Smut",value:"281"},{label:"Sports",value:"1357"},{label:"Supernatural",value:"16"},{label:"Tragedy",value:"132"},{label:"Wuxia",value:"479"},{label:"Xianxia",value:"480"},{label:"Xuanhuan",value:"3954"},{label:"Yaoi",value:"560"},{label:"Yuri",value:"922"}]},language:{label:"Language",value:[],options:[{label:"Chinese",value:"495"},{label:"Filipino",value:"9181"},{label:"Indonesian",value:"9179"},{label:"Japanese",value:"496"},{label:"Khmer",value:"18657"},{label:"Korean",value:"497"},{label:"Malaysian",value:"9183"},{label:"Thai",value:"9954"},{label:"Vietnamese",value:"9177"}],type:a.FilterTypes.CheckboxGroup},novelType:{label:"Novel Type (Not for Popular)",value:[],options:[{label:"Light Novel",value:"2443"},{label:"Published Novel",value:"26874"},{label:"Web Novel",value:"2444"}],type:a.FilterTypes.CheckboxGroup},reading_list_operator:{label:"Reading List (Include/Exclude) (Not for Popular)",value:"include",options:[{label:"Include",value:"include"},{label:"Exclude",value:"exclude"}],type:a.FilterTypes.Picker},reading_lists:{label:"Reading Lists (Not for Popular)",value:[],options:[{label:"All Reading Lists",value:"-1"}],type:a.FilterTypes.CheckboxGroup}}}return o.prototype.parseNovels=function(e){var t=this,r=[];return e("div.search_main_box_nu").each((function(n,a){var o=e(a).find(".search_title > a").attr("href");o&&r.push({name:e(a).find(".search_title > a").text(),cover:e(a).find("img").attr("src"),path:o.replace(t.site,"")})})),r},o.prototype.popularNovels=function(a,o){return e(this,arguments,void 0,(function(e,a){var o,l,s,c,i,u,p,h=a.showLatestNovels,d=a.filters;return t(this,(function(t){switch(t.label){case 0:return o=this.site,h?o+="series-finder/?sf=1&sort=sdate&order=desc":"popmonth"===(null==d?void 0:d.sort.value)||"popular"===(null==d?void 0:d.sort.value)?o+="series-ranking/?rank="+d.sort.value:(o+="series-finder/?sf=1",((null===(c=null==d?void 0:d.genres.value.include)||void 0===c?void 0:c.length)||(null===(i=null==d?void 0:d.genres.value.exclude)||void 0===i?void 0:i.length))&&(o+="&mgi="+d.genre_operator.value),(null==d?void 0:d.novelType.value.length)&&(o+="&nt="+d.novelType.value.join(",")),(null==d?void 0:d.reading_lists.value.length)&&(o+="&hd="+(null==d?void 0:d.reading_lists.value.join(",")),o+="&mRLi="+(null==d?void 0:d.reading_list_operator.value)),o+="&sort="+(null==d?void 0:d.sort.value),o+="&order="+(null==d?void 0:d.order.value)),(null==d?void 0:d.language.value.length)&&(o+="&org="+d.language.value.join(",")),(null===(u=null==d?void 0:d.genres.value.include)||void 0===u?void 0:u.length)&&(o+="&gi="+d.genres.value.include.join(",")),(null===(p=null==d?void 0:d.genres.value.exclude)||void 0===p?void 0:p.length)&&(o+="&ge="+d.genres.value.exclude.join(",")),(null==d?void 0:d.storyStatus.value)&&(o+="&ss="+d.storyStatus.value),o+="&pg="+e,[4,(0,n.fetchApi)(o)];case 1:return[4,t.sent().text()];case 2:return l=t.sent(),s=(0,r.load)(l),[2,this.parseNovels(s)]}}))}))},o.prototype.parseNovel=function(a){return e(this,void 0,void 0,(function(){var e,o,l,s,c,i,u,p,h,d,f,v,b,m=this;return t(this,(function(t){switch(t.label){case 0:return e=this.site+a,[4,(0,n.fetchApi)(e)];case 1:return[4,t.sent().text()];case 2:return o=t.sent(),l=(0,r.load)(o),(s={path:a,name:l(".seriestitlenu").text()||"Untitled",cover:l(".wpb_wrapper img").attr("src"),chapters:[]}).author=l("#authtag").map((function(e,t){return l(t).text().trim()})).toArray().join(", "),s.genres=l("#seriesgenre").children("a").map((function(e,t){return l(t).text()})).toArray().join(","),s.status=l("#editstatus").text().includes("Ongoing")?"Ongoing":"Completed",c=l("#showtype").text().trim(),i=l("#editdescription").text().trim(),s.summary=i+"\n\nType: ".concat(c),(u=null===(b=l(".seriesother .uvotes").text().match(/(\d+\.\d+) \/ \d+\.\d+/))||void 0===b?void 0:b[1])&&(s.rating=parseFloat(u)),p=l("input#mypostid").attr("value"),(h=new FormData).append("action","nd_getchapters"),h.append("mygrr","0"),h.append("mypostid",p),[4,(0,n.fetchApi)("".concat(this.site,"wp-admin/admin-ajax.php"),{method:"POST",body:h}).then((function(e){return e.text()}))];case 3:return d=t.sent(),f=(0,r.load)(d),v=[],f("li.sp_li_chp").each((function(e,t){var r=f(t).text().replace("v","volume ").replace("c"," chapter ").replace("part","part ").replace("ss","SS").replace(/\b\w/g,(function(e){return e.toUpperCase()})).trim(),n="https:"+f(t).find("a").first().next().attr("href");n&&v.push({name:r,path:n.replace(m.site,"")})})),s.chapters=v.reverse(),[2,s]}}))}))},o.prototype.getLocation=function(e){var t=e.match(/^(https?:)\/\/(([^:/?#]*)(?::([0-9]+))?)([/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);return t&&"".concat(t[1],"//").concat(t[3])},o.prototype.getChapterBody=function(a,o,l){return e(this,void 0,void 0,(function(){var e,s,c,i,u,p,h,d,f,v,b,m,g,y,w,x,_,A,k,C,E,T,j,S,N,F,L,P,z,O,I,R,M,G,H,B,U,J,q,W,$,D,K,X,Y,V,Q,Z,ee,te,re,ne,ae,oe,le,se,ce,ie,ue,pe,he,de,fe,ve,be,me,ge,ye,we,xe,_e,Ae,ke,Ce,Ee,Te,je,Se,Ne,Fe,Le,Pe,ze;return t(this,(function(t){switch(t.label){case 0:switch(e="",s="",c="",i=["app","blogspot","casper","wordpress","www"],u=o.find((function(e){return!i.includes(e)})),u){case"akutranslations":return[3,1];case"asuratls":return[3,5];case"brightnovels":return[3,6];case"canonstory":return[3,7];case"daoist":return[3,11];case"dreamy-translations":return[3,12];case"fictionread":return[3,13];case"genesistudio":return[3,14];case"greenz":return[3,19];case"hiraethtranslation":return[3,25];case"hostednovel":return[3,26];case"infinitenoveltranslations":return[3,27];case"inoveltranslation":return[3,31];case"isotls":return[3,32];case"ko-fi":return[3,33];case"leafstudio":return[3,34];case"machineslicedbread":return[3,35];case"mirilu":return[3,39];case"mythoriatales":return[3,40];case"novelplex":return[3,45];case"novelshub":return[3,46];case"novelworldtranslations":return[3,52];case"patreon":return[3,53];case"r-p-d":return[3,54];case"raeitranslations":return[3,63];case"rainofsnow":return[3,65];case"readingpia":return[3,66];case"redoxtranslation":return[3,67];case"sacredtexttranslations":return[3,69];case"scribblehub":return[3,70];case"skydemonorder":return[3,71];case"stabbingwithasyringe":return[3,72];case"tinytranslation":return[3,76];case"tumblr":return[3,77];case"vampiramtl":return[3,78];case"wattpad":return[3,82];case"webnovel":return[3,83];case"wetriedtls":return[3,84];case"wuxiaworld":return[3,85];case"yoru":return[3,86]}return[3,89];case 1:return t.trys.push([1,4,,5]),te=l.replace("/novel","/api/novel"),[4,(0,n.fetchApi)(te)];case 2:return[4,(ye=t.sent()).json()];case 3:if(!(null==(Ce=t.sent())?void 0:Ce.content))throw new Error("Invalid API response structure.");return s=Ce.content.trim().split(/\n+/).map((function(e){return e.trim()})).filter((function(e){return e.length>0})).map((function(e){return"<p>".concat(e,"</p>")})).join("\n"),[3,89];case 4:throw p=t.sent(),new Error("Failed to parse AkuTranslations chapter: ".concat(p));case 5:return ge=a(".post-body div b").first(),e=ge.text(),ge.remove(),s=a(".post-body").html(),[3,89];case 6:h=function(e){[".ad-container","script","style"].forEach((function(t){return e(t).remove()}));var t,n=e("#app").attr("data-page");if(!n)throw new Error("data-page attribute not found on Bright Novels.");try{t=JSON.parse(n)}catch(e){throw new Error("Failed to parse data-page JSON for Bright Novels.")}var a=t.props.chapter.title,o=t.props.chapter.content,l=(0,r.load)(o);return l("script, style").remove(),o=l.html(),"<h2>".concat(a,"</h2><hr><br>").concat(o)};try{c=h(a)}catch(e){d=a("#app").html()||a("body").html()||"",(f=(0,r.load)(d))("script, style").remove(),d=f.html(),c=d}return[3,89];case 7:if(t.trys.push([7,10,,11]),(ve=l.split("/")).length<7)throw new Error("Invalid chapter URL structure");return Z=ve[4],ee=ve[6],ke="".concat(ve[0],"//").concat(ve[2],"/api/public/chapter-by-slug/").concat(Z,"/").concat(ee),[4,(0,n.fetchApi)(ke)];case 8:return[4,(ye=t.sent()).json()];case 9:if(Ce=t.sent(),!(null===(Ee=null==Ce?void 0:Ce.data)||void 0===Ee?void 0:Ee.currentChapter))throw new Error("Invalid API response structure.");return m=Ce.data.currentChapter,re=m.chapterNumber,Y=m.title,A=m.content,ge="Chapter ".concat(re),e=Y?"".concat(ge," - ").concat(Y):ge,s=A.replace(/\n/g,"<br>"),[3,89];case 10:throw v=t.sent(),new Error("Failed to parse Canon Story chapter: ".concat(v));case 11:return e=a(".chapter__title").first().text(),a("span.patreon-lock-icon").remove(),a("img[data-src]").each((function(e,t){var r=a(t),n=r.attr("data-src");n&&(r.attr("src",n),r.removeAttr("data-src"))})),s=a(".chapter__content").html(),[3,89];case 12:return e=a("h1 > span").first().text(),(A=a(".chapter-content > div").first()).children("em").wrap("<p></p>"),s=A.html(),[3,89];case 13:return[".content > style",".highlight-ad-container",".meaning",".word"].forEach((function(e){return a(e).remove()})),e=a(".title-image span").first().text(),a(".content").children().each((function(e,t){var r;if(null===(r=a(t).attr("id"))||void 0===r?void 0:r.includes("Chaptertitle-info"))return a(t).remove(),!1})),s=a(".content").html(),[3,89];case 14:ke="".concat(l,"/__data.json?x-sveltekit-invalidated=001"),t.label=15;case 15:return t.trys.push([15,17,,18]),[4,(0,n.fetchApi)(ke).then((function(e){return e.json()}))];case 16:for(x in Ce=t.sent(),b=Ce.nodes,m=b.filter((function(e){return"data"===e.type})).map((function(e){return e.data}))[0],g="content",y="notes",w="footnotes",m)if((_=m[x])&&"object"==typeof _&&g in _&&y in _&&w in _){A=m[String(_[g])],k=m[String(_[y])],C=m[String(_[w])],c=A+(k?"<h2>Notes</h2><br>".concat(k):"")+(null!=C?C:"");break}return[3,18];case 17:throw E=t.sent(),new Error("Failed to fetch chapter data: ".concat(E));case 18:return[3,89];case 19:ee=l.split("/").pop(),te="https://greenz.com/api/chapters/slug/".concat(ee),t.label=20;case 20:return t.trys.push([20,23,,24]),[4,(0,n.fetchApi)(te)];case 21:return[4,(ye=t.sent()).json()];case 22:return Ce=t.sent(),T=Ce.data.name,re=Ce.data.chapterNumber,j=(0,r.load)(Ce.data.content),e="Chapter ".concat(re," - ").concat(T),s=j.html(),[3,24];case 23:throw S=t.sent(),new Error("Failed to parse GreenzTL chapter: ".concat(S));case 24:return[3,89];case 25:return e=a("li.active").first().text(),s=a(".text-left").html(),[3,89];case 26:return e=a("#chapter-title").first().text(),s=a("#chapter-content").html(),[3,89];case 27:return(ke=a("article > p > a").first().attr("href"))?[4,(0,n.fetchApi)(ke)]:[3,30];case 28:return[4,(ye=t.sent()).text()];case 29:we=t.sent(),a=(0,r.load)(we),t.label=30;case 30:return s=a(".entry-content").html(),e=a(".entry-title").text(),[3,89];case 31:return["header","section"].forEach((function(e){return a(e).remove()})),c=a(".styles_content__JHK8G").html(),[3,89];case 32:return["footer","header","nav",".ezoic-ad",".ezoic-adpicker-ad",".ezoic-videopicker-video"].forEach((function(e){return a(e).remove()})),e=a("head title").first().text(),s=a("main article").html(),[3,89];case 33:return(N=null===(Te=a('script:contains("shadowDom.innerHTML")').html())||void 0===Te?void 0:Te.match(/shadowDom\.innerHTML \+= '(<div.*?)';/))&&N[1]&&(c=N[1]),[3,89];case 34:return e=a(".title").first().text(),s=a(".chapter_content").map((function(e,t){return a(t).prop("outerHTML")})).get().join(""),[3,89];case 35:if(F=l.split("/").filter(Boolean),L=F.slice(2),P=L.length,z=a,1!==P)return[3,38];if(!(O=a(".entry-content a").first().attr("href")))throw new Error("Chapter path not found.");return[4,(0,n.fetchApi)(O)];case 36:if(!(ye=t.sent()).ok)throw new Error("Failed to fetch chapter: ".concat(ye.status));return[4,ye.text()];case 37:we=t.sent(),z=(0,r.load)(we),t.label=38;case 38:return c=z(".entry-content").html(),[3,89];case 39:return["#jp-post-flair"].forEach((function(e){return a(e).remove()})),ge=a(".entry-content p strong").first(),e=ge.text(),ge.remove(),s=a(".entry-content").html(),[3,89];case 40:if(!(I=a('script:contains("script-2")').html()))throw new Error("Failed to find script-2");if(R=Array.from(I.matchAll(/"script-2.*?[^_]+([^\\]+)/g)),!(M=null===(je=R[1])||void 0===je?void 0:je[1]))throw new Error("Failed to extract script-2 URL");return G=new URL("/".concat(M),l).href,[4,(0,n.fetchApi)(G)];case 41:return[4,t.sent().text()];case 42:if(H=t.sent(),!(B=null===(Se=H.match(/[a-f0-9]{42}/))||void 0===Se?void 0:Se[0]))throw new Error("Failed to extract ACTION_HASH");return U=l.split("/"),J=[U[4],parseInt(U[6],10)],q=J[0],W=J[1],[4,(0,n.fetchApi)(l,{method:"POST",headers:{Accept:"text/x-component","Content-Type":"text/plain;charset=UTF-8","next-action":B},body:JSON.stringify([q,W])})];case 43:if(!(ye=t.sent()).ok)throw new Error("Failed to fetch chapter: ".concat(ye.status));return[4,ye.text()];case 44:if($=t.sent().replace(/(\d+:[{TE])/g,"\n$1"),Q=$.split(/\n(?=\d+:[{TE])/),!(D=Q.filter((function(e){return/^\d+:T/.test(e)&&!e.startsWith("0:")})).map((function(e){return e.replace(/^\d+:T[0-9a-f]+,/,"")})).join("")))throw new Error("Could not find the chapter content segment (2:T) in the stream.");if(0===(K=D.trim().split(/(?:\r?\n|\\n)+/).map((function(e){return e.trim()})).filter((function(e){return e.length>0}))).length)throw new Error("Parsed content is empty.");if(X=Q.find((function(e){return e.startsWith("1:")})))try{ce=JSON.parse(X.slice(2)),Y=null===(Fe=null===(Ne=null==ce?void 0:ce.data)||void 0===Ne?void 0:Ne.chapter)||void 0===Fe?void 0:Fe.title,V=null!==(ze=null===(Pe=null===(Le=null==ce?void 0:ce.data)||void 0===Le?void 0:Le.chapter)||void 0===Pe?void 0:Pe.chapterNumber)&&void 0!==ze?ze:W,Y&&(e="Chapter ".concat(V,": ").concat(Y))}catch(e){}return e||(e="Chapter ".concat(W)),s=(s=K.map((function(e){return"<p>".concat(e,"</p>")})).join("\n")).replace(/\[dialogue\s+speaker="([^"]*)"\](.*?)\[\/dialogue\]/gi,"$1: $2").replace(/\[sfx\].*?\[\/sfx\]/gi,"").replace(/\[\/?(dialogue|sfx)[^\]]*\]/gi,""),[3,89];case 45:return[".passingthrough_adreminder"].forEach((function(e){return a(e).remove()})),e=a(".halChap--jud").first().text(),s=a(".halChap--kontenInner ").html(),[3,89];case 46:Q=l.split("/"),Z=Q[Q.length-2],ee=Q[Q.length-1],te="https://api.novelshub.org/api/chapter?mangaslug=".concat(Z,"&chapterslug=").concat(ee),t.label=47;case 47:return t.trys.push([47,50,,51]),[4,(0,n.fetchApi)(te)];case 48:return[4,(ye=t.sent()).json()];case 49:return Ce=t.sent(),re=Ce.chapter.number,ne=(0,r.load)(Ce.chapter.content),e="Chapter ".concat(re),ne("div").each((function(e,t){var r=ne(t),n=r.attr("style");n&&(/border:.*#ff6b00/.test(n)?r.removeAttr("style").addClass("novels-hub_box_orange"):/color:.*#ff6b00.*text-transform:.*uppercase/.test(n)?r.removeAttr("style").addClass("novels-hub_box-title_orange"):/color:.*white.*border-top:.*#ff6b00/.test(n)?r.removeAttr("style").addClass("novels-hub_box-text_orange"):/border:.*#00ff88/.test(n)?r.removeAttr("style").addClass("novels-hub_box_green"):/color:.*#00ff88.*text-transform:.*uppercase/.test(n)?r.removeAttr("style").addClass("novels-hub_box-title_green"):/border-left:.*#00ff88/.test(n)?r.removeAttr("style").addClass("novels-hub_comment_green"):/border:.*#0066ff/.test(n)?r.removeAttr("style").addClass("novels-hub_box_blue"):/color:.*#0099ff.*text-transform:.*uppercase/.test(n)?r.removeAttr("style").addClass("novels-hub_box-title_blue"):/color:.*#d0d0d0/.test(n)&&r.removeAttr("style").addClass("novels-hub_box-text_blue"))})),ne("span").each((function(e,t){var r=ne(t),n=r.attr("style");n&&(/color:.*#ff6b6b/.test(n)?r.removeAttr("style").addClass("novels-hub_text_red"):/color:.*#4d9fff/.test(n)?r.removeAttr("style").addClass("novels-hub_text_blue"):/color:.*#a78bfa/.test(n)&&r.removeAttr("style").addClass("novels-hub_text_purple"))})),s=ne.html(),[3,51];case 50:throw ae=t.sent(),new Error("Failed to parse GreenzTL chapter: ".concat(ae));case 51:return[3,89];case 52:return[".separator img"].forEach((function(e){return a(e).remove()})),a(".entry-content a").filter((function(e,t){var r;return(null===(r=a(t).attr("href"))||void 0===r?void 0:r.includes("https://novelworldtranslations.blogspot.com"))||!1})).each((function(e,t){a(t).parent().remove()})),e=a(".entry-title").first().text(),s=a(".entry-content").html().replace(/ /g,"").replace(/\n/g,"<br>"),(oe=(0,r.load)(s))("span, p, div").each((function(e,t){""===oe(t).text().trim()&&oe(t).remove()})),s=oe.html(),[3,89];case 53:return a('#track-click,[class*="hidden "]').remove(),e=a('h1[data-tag="post-title"]').text(),s=a('[data-tag="post-card"] [class*="PaddingTop"]').html(),[3,89];case 54:return ve=l.split("/"),[4,(0,n.fetchApi)("".concat(ve[0],"//").concat(ve[2],"/resolve?p=/").concat(ve.slice(3).join("/")))];case 55:return[4,t.sent().json()];case 56:return le=t.sent().location,ve=le.split("/"),se="".concat(ve[0],"//").concat(ve[2]),[4,(0,n.fetchApi)("".concat(se,"/api/chapter-meta?seriesSlug=").concat(ve[4],"&chapterSlug=").concat(ve[5])).then((function(e){return e.json()}))];case 57:return ce=t.sent(),ie=ce.chapter.id,[4,(0,n.fetchApi)("".concat(se,"/api/chapters/").concat(ie,"/parts-token")).then((function(e){return e.json()}))];case 58:ue=t.sent().token,pe=1,he=1,t.label=59;case 59:return he<=pe?[4,(0,n.fetchApi)("".concat(se,"/api/chapters/").concat(ie,"/parts?index=").concat(he,"&token=").concat(ue)).then((function(e){return e.json()}))]:[3,62];case 60:de=t.sent(),fe="<p>"+de.markdown.replace(/\n\n/g,"</p><p>")+"</p>",c+=fe,pe=de.total,t.label=61;case 61:return he++,[3,59];case 62:return[3,89];case 63:return ve=l.split("/"),ke="".concat(ve[0],"//api.").concat(ve[2],"/api/chapters/single?id=").concat(ve[3],"&num=").concat(ve[4]),[4,(0,n.fetchApi)(ke).then((function(e){return e.json()}))];case 64:return Ce=t.sent(),ge="Chapter ".concat(Ce.currentChapter.chapTag),e=Ce.currentChapter.chapTitle?"".concat(ge," - ").concat(Ce.currentChapter.chapTitle):ge,s=(s=[Ce.novelHead,"<br><hr><br>",Ce.currentChapter.body,"<br><hr><br>Translator's Note:<br>",Ce.currentChapter.note].join("")).replace(/\n/g,"<br>"),[3,89];case 65:return be=a(".bb-item").filter((function(){return"block"===a(this).css("display")})),me=(0,r.load)(be.html()),[".responsivevoice-button",".zoomdesc-cont p img",".zoomdesc-cont p noscript"].forEach((function(e){return me(e).remove()})),s=me(".zoomdesc-cont").html(),(ge=me(".scroller h2").first()).length&&(e=ge.text(),ge.remove(),s=me(".zoomdesc-cont").html()),[3,89];case 66:return[".ezoic-ad",".ezoic-adpicker-ad",".ez-video-wrap"].forEach((function(e){return a(e).remove()})),c=a(".chapter-body").html(),[3,89];case 67:return Ae=l.split("/").pop(),e="Chapter ".concat(Ae),ke="".concat(l.split("chapter")[0],"txt/").concat(Ae,".txt"),[4,(0,n.fetchApi)(ke).then((function(e){return e.text()})).then((function(e){return e.split("\n").map((function(e){return e.includes("{break}")?"<br> <p>****</p>":e=(e=e.replace(/\*\*(.*?)\*\*/g,"<strong>$1</strong>")).replace(/\+\+(.*?)\+\+/g,"<em>$1</em>")})).join("<br>")}))];case 68:return s=t.sent(),[3,89];case 69:return[".entry-content blockquote",".entry-content div",".reaction-buttons"].forEach((function(e){return a(e).remove()})),e=a(".entry-title").first().text(),s=a(".entry-content").html(),[3,89];case 70:return[".wi_authornotes"].forEach((function(e){return a(e).remove()})),e=a(".chapter-title").first().text(),s=a(".chp_raw").html(),[3,89];case 71:if(a("main").text().toLowerCase().includes("age verification required"))throw new Error("Age verification required, please open in webview.");return e="".concat(a("header .font-medium.text-sm").first().text().trim()),s=a("#chapter-body").html(),[3,89];case 72:return(ke=a(".entry-content a").attr("href"))?[4,(0,n.fetchApi)(ke)]:[3,75];case 73:return[4,(ye=t.sent()).text()];case 74:we=t.sent(),a=(0,r.load)(we),t.label=75;case 75:return[".has-inline-color",".wp-block-buttons",".wpcnt","#jp-post-flair"].forEach((function(e){return a(e).remove()})),s=a(".entry-content").html(),(ge=a(".entry-content h3").first()).length&&(e=ge.text(),ge.remove(),s=a(".entry-content").html()),[3,89];case 76:return[".content noscript",".google_translate_element",".navigate",".post-views","br"].forEach((function(e){return a(e).remove()})),e=a(".title-content").first().text(),a(".title-content").first().remove(),s=a(".content").html(),[3,89];case 77:return c=a(".post").html(),[3,89];case 78:return(ke=a(".entry-content a").attr("href"))?[4,(0,n.fetchApi)(l+ke)]:[3,81];case 79:return[4,(ye=t.sent()).text()];case 80:we=t.sent(),a=(0,r.load)(we),t.label=81;case 81:return e=a(".entry-title").first().text(),s=a(".entry-content").html(),[3,89];case 82:return e=a(".h2").first().text(),s=a(".part-content pre").html(),[3,89];case 83:return e=a(".cha-tit .pr .dib").first().text(),(s=a(".cha-words").html())||(s=a("._content").html()),[3,89];case 84:return(xe=a('script:contains("p dir=")').html()||a('script:contains("u003c")').html())&&(_e=xe.slice(xe.indexOf(".push(")+6,xe.lastIndexOf(")")),c=JSON.parse(_e)[1]),[3,89];case 85:return[".MuiLink-root"].forEach((function(e){return a(e).remove()})),e=a("h4 span").first().text(),s=a(".chapter-content").html(),[3,89];case 86:return Ae=l.split("/").pop(),ke="https://pxp-main-531j.onrender.com/api/v1/book_chapters/".concat(Ae,"/content"),[4,(0,n.fetchApi)(ke).then((function(e){return e.json()}))];case 87:return Ce=t.sent(),[4,(0,n.fetchApi)(Ce).then((function(e){return e.text()}))];case 88:return c=t.sent(),[3,89];case 89:return c||(c=e?"<h2>".concat(e,"</h2><hr><br>").concat(s):s),[2,c]}}))}))},o.prototype.parseChapter=function(a){return e(this,void 0,void 0,(function(){var e,o,l,s,c,i,u,p,h,d,f,v,b,m,g,y,w,x;return t(this,(function(t){switch(t.label){case 0:return[4,(0,n.fetchApi)(this.site+a)];case 1:return[4,(o=t.sent()).text()];case 2:if(l=t.sent(),s=o.url,c=s.toLowerCase().split("/")[2].split("."),i=(0,r.load)(l),u=["bot verification","just a moment...","redirecting...","un instant...","you are being redirected..."],p=i("title").text().trim().toLowerCase(),u.includes(p))throw new Error("Captcha detected, please open in webview.");if(!o.ok)throw new Error("Failed to fetch ".concat(o.url,": ").concat(o.status," ").concat(o.statusText));return d=[(h=function(e,t,r){var n=!1;return i(e).each((function(e,a){var o=t?i(a).attr(t):i(a).html()||i(a).text();if(o&&r.test(o.toLowerCase()))return n=!0,!1})),n})('meta[name="generator"]',"content",/wordpress|site kit/i),h("link, script, img","src",/\/wp-content\/|\/wp-includes\//i),h("link","href",/\/wp-content\/|\/wp-includes\//i),h('link[rel="https://api.w.org/"]',"href",/.*/),h('link[rel="EditURI"]',"href",/xmlrpc\.php/i),h("body","class",/wp-admin|wp-custom-logo|logged-in/i),h("script",null,/wp-embed|wp-emoji|wp-block/i)].some(Boolean),f=[h('meta[name="generator"]',"content",/blogger/i),h('meta[name="google-adsense-platform-domain"]',"content",/blogspot/i),h('link[rel="alternate"]',"href",/blogger\.com\/feeds|blogspot\.com\/feeds/i),h("link","href",/www\.blogger\.com\/static|www\.blogger\.com\/dyn-css/i),h("script",null,/_WidgetManager\._Init|_WidgetManager\._RegisterWidget/i)].some(Boolean),v=["asuratls","fictionread","hiraethtranslation","infinitenoveltranslations","leafstudio","machineslicedbread","mirilu","novelworldtranslations","sacredtexttranslations","stabbingwithasyringe","tinytranslation","vampiramtl"],c.some((function(e){return v.includes(e)}))&&(d=!1,f=!1),b={wordpress:{bloat:[".ad",".author-avatar",".chapter-warning",".entry-meta",".ezoic-ad",".mb-center",".modern-footnotes-footnote__note",".patreon-widget",".post-cats",".pre-bar",".sharedaddy",".sidebar",".swg-button-v2-light",".wp-block-buttons",".wp-dark-mode-switcher",".wp-next-post-navi","#hpk","#jp-post-flair","#textbox"],title:[".entry-title",".chapter__title",".title-content",".wp-block-post-title",".title_story","#chapter-heading",".chapter-title","head title","h1:first-of-type","h2:first-of-type",".active"],content:[".chapter__content",".entry-content",".text_story",".post-content",".contenta",".single_post",".main-content",".reader-content","#content","#the-content","article.post",".chp_raw"]},blogspot:{bloat:[".button-container",".ChapterNav",".ch-bottom",".separator"],title:[".entry-title",".post-title","head title"],content:[".content-post",".entry-content",".post-body"]}},d||f?[3,4]:[4,this.getChapterBody(i,c,s)];case 3:return e=t.sent(),[3,5];case 4:(m=d?b.wordpress:b.blogspot).bloat.forEach((function(e){return i(e).remove()})),g=m.title.map((function(e){return i(e).first().text().trim()})).find((function(e){return e.length>0})),(y=i(".cat-series").first().text()||i("h1.leading-none ~ span").first().text()||i(".breadcrumb .active").first().text())&&(g=y),w=m.content.map((function(e){var t=i(e).first();return t.text().trim().length>50?t.html():null})).find((function(e){return e})),e=g&&w?"<h2>".concat(g,"</h2><hr><br>").concat(w):w||"",t.label=5;case 5:return e||(["nav","header","footer",".hidden"].forEach((function(e){return i(e).remove()})),e=i("body").html()),e=e.replace(/href="\//g,'href="'.concat(this.getLocation(o.url),"/")),(x=(0,r.load)(e))("noscript").remove(),x("img").each((function(e,t){var r=x(t);r.attr("data-lazy-src")&&r.attr("src",r.attr("data-lazy-src")),r.attr("data-lazy-srcset")&&r.attr("srcset",r.attr("data-lazy-srcset")),r.hasClass("lazyloaded")&&r.removeClass("lazyloaded")})),[2,x.html()]}}))}))},o.prototype.searchNovels=function(a,o){return e(this,void 0,void 0,(function(){var e,l,s,c,i;return t(this,(function(t){switch(t.label){case 0:return e=a.split("*"),l=e.reduce((function(e,t){return e.length>t.length?e:t}),""),a=l.replace(/[‘’]/g,"'").replace(/\s+/g,"+"),s="".concat(this.site,"series-finder/?sf=1&sh=").concat(a,"&sort=srank&order=asc&pg=").concat(o),[4,(0,n.fetchApi)(s)];case 1:return[4,t.sent().text()];case 2:return c=t.sent(),i=(0,r.load)(c),[2,this.parseNovels(i)]}}))}))},o}();exports.default=new o;
Write scripts/test-browser-storage.mjs
Create this path in your reconstruction project. Source set: build / host / supporting material. Exact file download.
The source describes its contract as:
Real-browser OPFS/service-worker contract checks. Pass a playwright-core module path if needed.
/** Real-browser OPFS/service-worker contract checks. Pass a playwright-core module path if needed. */
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { fileURLToPath, pathToFileURL } from 'node:url';
const { chromium } = await import(process.argv[2] ? pathToFileURL(process.argv[2]).href : 'playwright-core');
const resources = new URL('../composeApp/src/wasmJsMain/resources/', import.meta.url);
const server = createServer(async (request, response) => {
const path = new URL(request.url, 'http://localhost').pathname;
if (path === '/') { response.setHeader('Content-Type', 'text/html'); response.end('<script src="browser-storage.js"></script>'); return; }
if (!['/browser-storage.js', '/browser-files-sw.js', '/browser-archives.js', '/vendor/zipjs-2.23.0/zip-native.min.js'].includes(path)) { response.writeHead(404).end(); return; }
response.setHeader('Content-Type', 'application/javascript');
response.setHeader('Cache-Control', 'no-store');
response.end(await readFile(fileURLToPath(new URL(path.slice(1), resources))));
});
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
let browser;
try {
browser = await chromium.launch({ channel: 'chrome', headless: true });
const page = await browser.newPage();
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.goto(`http://127.0.0.1:${server.address().port}/`);
const first = await page.evaluate(async () => {
const store = yokanBrowserFiles.open('/yokan');
await store.prepare();
const folder = '/yokan/downloads/Manga/Source/Title/Chapter 1';
const path = folder + '/0001.mp4';
const chunk = btoa('a'.repeat(256 * 1024));
await store.begin(path + '.part', false);
for (let i = 0; i < 48; i++) await store.chunk(path + '.part', chunk);
await store.end(path + '.part', true);
await store.promote(path + '.part', path);
await store.write(path + '.complete', '');
await store.flush();
let bounded = false, traversal = false, root = false, outside = false;
try { await store.read(path, 1024); } catch { bounded = true; }
try { await store.write('/yokan/../escape', ''); } catch { traversal = true; }
try { await store.remove('/yokan'); } catch { root = true; }
try { await store.write('/other-profile/file', ''); } catch { outside = true; }
// A rejected operation remains visible at the flush boundary, then retry can proceed.
try { await store.flush(); } catch {}
const url = await store.url(path);
const range = await fetch(url, { headers: { Range: 'bytes=100-199' } });
const suffix = await fetch(url, { headers: { Range: 'bytes=-7' } });
const invalid = await fetch(url, { headers: { Range: 'bytes=90000000-' } });
return { bounded, traversal, root, outside, bytes: store.size(path), folderBytes: store.size(folder),
files: JSON.parse(store.list(folder)).length, status: range.status, body: await range.text(),
contentRange: range.headers.get('Content-Range'), suffix: await suffix.text(), invalid: invalid.status,
temporaryRemoved: !store.exists(path + '.part'), url };
});
assert.equal(first.bytes, 12 * 1024 * 1024);
assert.equal(first.folderBytes, first.bytes);
assert.equal(first.files, 2);
assert.equal(first.status, 206);
assert.equal(first.body, 'a'.repeat(100));
assert.equal(first.contentRange, `bytes 100-199/${first.bytes}`);
assert.equal(first.suffix, 'a'.repeat(7));
assert.equal(first.invalid, 416);
for (const property of ['bounded', 'traversal', 'root', 'outside', 'temporaryRemoved']) assert.equal(first[property], true, property);
await page.reload();
const second = await page.evaluate(async () => {
const store = yokanBrowserFiles.open('/yokan');
await store.prepare();
const folder = '/yokan/downloads/Manga/Source/Title/Chapter 1';
const path = folder + '/0001.mp4';
const persisted = store.size(path);
const partial = folder + '/partial';
await store.begin(partial, false);
await store.chunk(partial, btoa('first'));
let activeProtected = false, duplicateWriter = false, closeProtected = false;
try { await store.remove(folder); } catch { activeProtected = true; }
try { await store.begin(partial, false); } catch { duplicateWriter = true; }
try { await store.close(); } catch { closeProtected = true; }
try { await store.flush(); } catch {}
await store.end(partial, true);
await store.begin(partial, true);
await store.chunk(partial, btoa('second'));
await store.end(partial, true);
const resumed = atob(await store.read(partial, 20));
await store.write(folder + '/unsafe.html', btoa('<script>window.compromised=true</script>'));
const html = await fetch(await store.url(folder + '/unsafe.html'));
const csp = html.headers.get('Content-Security-Policy');
await store.remove(folder);
const removed = !store.exists(folder) && store.size(folder) === 0 && JSON.parse(store.list(folder)).length === 0;
await store.close();
const reopened = yokanBrowserFiles.open('/yokan');
await reopened.prepare();
return { persisted, activeProtected, duplicateWriter, closeProtected, resumed, removed, csp, stillRemoved: !reopened.exists(folder) };
});
assert.equal(second.persisted, first.bytes);
assert.equal(second.resumed, 'firstsecond');
for (const property of ['activeProtected', 'duplicateWriter', 'closeProtected', 'removed', 'stillRemoved']) assert.equal(second[property], true, property);
assert.match(second.csp, /sandbox/);
const archive = await page.evaluate(async () => {
const store = yokanBrowserFiles.open('/yokan');
await store.prepare();
const folder = '/yokan/downloads/Manga/Source/Title/Archive Chapter';
await store.write(folder + '/0010.jpg', btoa('ten'));
await store.write(folder + '/0002.jpg', btoa('two'));
await store.write(folder + '/metadata.json', btoa('{"name":"Archive Chapter"}'));
await store.write(folder + '/0002.jpg.complete', '');
await store.begin(folder + '/0001.png', false);
for (let i = 0; i < 48; i++) await store.chunk(folder + '/0001.png', btoa('b'.repeat(256 * 1024)));
await store.end(folder + '/0001.png', true);
const path = await store.zip(folder, true);
const index = JSON.parse(await store.archiveEntries(path));
const url = await store.url(path);
const image = await fetch(url + '?entry=' + encodeURIComponent('0002.jpg'));
const large = await fetch(url + '?entry=' + encodeURIComponent('0001.png'));
let bytes = 0;
for await (const chunk of large.body) { if (chunk.some(byte => byte !== 98)) throw new Error('Corrupt archive image'); bytes += chunk.length; }
const missing = await fetch(url + '?entry=missing.jpg');
const head = await fetch(url + '?entry=0002.jpg', { method: 'HEAD' });
return { path, index, removed: !store.exists(folder), status: image.status, image: await image.text(), type: image.headers.get('Content-Type'),
bytes, missing: missing.status, headSize: head.headers.get('Content-Length') };
});
assert.equal(archive.removed, true);
assert.equal(archive.status, 200);
assert.equal(archive.image, 'two');
assert.equal(archive.type, 'image/jpeg');
assert.equal(archive.bytes, 12 * 1024 * 1024);
assert.equal(archive.missing, 404);
assert.equal(archive.headSize, '3');
assert.deepEqual(archive.index.map(entry => entry.name).sort(), ['0001.png', '0002.jpg', '0010.jpg', 'metadata.json']);
await page.reload();
const archivedReload = await page.evaluate(async path => {
const store = yokanBrowserFiles.open('/yokan'); await store.prepare();
const index = JSON.parse(await store.archiveEntries(path));
return { count: index.length, page: await (await fetch(await store.url(path) + '?entry=0010.jpg')).text() };
}, archive.path);
assert.deepEqual(archivedReload, { count: 4, page: 'ten' });
const archiveLimits = await page.evaluate(async () => {
const store = yokanBrowserFiles.open('/yokan'); await store.prepare();
const root = '/yokan/downloads/Manga/Source/Title';
// Load the vendored codec, then construct compressed and deliberately invalid archives.
await store.archiveEntries(root + '/Archive Chapter.cbz');
const encode = bytes => { let s = ''; for (const byte of bytes) s += String.fromCharCode(byte); return btoa(s); };
async function make(name, bytes, level = 0) {
const writer = new zip.ZipWriter(new zip.Uint8ArrayWriter(), { useWebWorkers: false });
await writer.add(name, new zip.Uint8ArrayReader(bytes), { level });
return writer.close();
}
const compressed = await make('pages/page 1.jpg', new TextEncoder().encode('compressed '.repeat(1000)), 6);
const compressedPath = root + '/compressed.cbz';
await store.write(compressedPath, encode(compressed));
const compressedPage = await (await fetch(await store.url(compressedPath) + '?entry=' + encodeURIComponent('pages/page 1.jpg'))).text();
let traversal = false, oversizedIndex = false, corrupt = false, unarchivedProtected = false, failedWriterRecovered = false, nestedProtected = false;
await store.write(root + '/traversal.cbz', encode(await make('../escape.jpg', new Uint8Array([1]))));
try { await store.archiveEntries(root + '/traversal.cbz'); } catch { traversal = true; }
try { await store.flush(); } catch {}
const invalidIndex = new Uint8Array(22); const view = new DataView(invalidIndex.buffer);
view.setUint32(0, 0x06054b50, true); view.setUint16(8, 65535, true); view.setUint16(10, 65535, true);
await store.write(root + '/index.cbz', encode(invalidIndex));
try { await store.archiveEntries(root + '/index.cbz'); } catch { oversizedIndex = true; }
try { await store.flush(); } catch {}
const broken = await make('page.jpg', new Uint8Array([1, 2, 3]));
const header = new DataView(broken.buffer, broken.byteOffset, broken.byteLength);
const dataOffset = 30 + header.getUint16(26, true) + header.getUint16(28, true);
broken[dataOffset] ^= 255;
await store.write(root + '/corrupt.cbz', encode(broken));
try { await (await fetch(await store.url(root + '/corrupt.cbz') + '?entry=page.jpg')).arrayBuffer(); } catch { corrupt = true; }
await store.write(root + '/Protected/page.jpg', btoa('image'));
await store.write(root + '/Protected/notes.txt', btoa('keep me'));
try { await store.zip(root + '/Protected', true); } catch { unarchivedProtected = store.exists(root + '/Protected/notes.txt'); }
try { await store.flush(); } catch {}
await store.write(root + '/Nested/page.jpg', btoa('image'));
await store.write(root + '/Nested/extra/image.jpg', btoa('keep me'));
try { await store.zip(root + '/Nested', true); } catch { nestedProtected = store.exists(root + '/Nested/extra/image.jpg'); }
try { await store.flush(); } catch {}
const write = yokanBrowserArchives.write;
await store.write(root + '/Failed/page.jpg', btoa('preserved'));
yokanBrowserArchives.write = async (_files, output) => {
const writer = output.getWriter();
try { await writer.write(new Uint8Array([1, 2, 3])); } finally { writer.releaseLock(); }
throw new Error('Simulated archive write failure');
};
try { await store.zip(root + '/Failed', true); } catch { failedWriterRecovered = store.exists(root + '/Failed/page.jpg'); }
finally { yokanBrowserArchives.write = write; }
try { await store.flush(); } catch {}
failedWriterRecovered = failedWriterRecovered && await store.zip(root + '/Failed', true) === root + '/Failed.cbz';
return { compressedPage, traversal, oversizedIndex, corrupt, unarchivedProtected, failedWriterRecovered, nestedProtected };
});
assert.equal(archiveLimits.compressedPage, 'compressed '.repeat(1000));
for (const property of ['traversal', 'oversizedIndex', 'corrupt', 'unarchivedProtected', 'failedWriterRecovered', 'nestedProtected']) assert.equal(archiveLimits[property], true, property);
assert.deepEqual(errors, []);
console.log('PASS: OPFS streaming/recovery/ranges/isolation; streamed CBZ creation, reload, compressed pages, CRC errors, archive limits and protected originals.');
} finally {
if (browser) await browser.close();
await new Promise(resolve => server.close(resolve));
}
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: every chapter gate and file-ledger task is complete, deterministic checks pass, platform integrations have recorded evidence, packages launch on clean hosts and the release scripts pass fixture tests. Remaining unsupported behavior is documented accurately.